← Questions

Difference between even- and odd-index sums of in-range values

0
DatabricksCodingLast asked Sep 2024

A coding interview question asked in Databricks's online assessment, last asked Sep 2024. It tests arrays.

Given an integer array, sum the values at even indices and, separately, the values at odd indices, counting only values between -100 and 100 inclusive. Return the even-index sum minus the odd-index sum.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • even_minus_odd(numbers: list[int]) -> int — indices are 0-based; values outside [-100, 100] are skipped but keep their index.

Example

even_minus_odd([101, 3, 4, 359, 2, 5])      ->  -2    # even: 4 + 2 = 6; odd: 3 + 5 = 8 (101 and 359 skipped)
even_minus_odd([-2, 234, 100, 99, 540, -1]) ->   0    # even: -2 + 100 = 98; odd: 99 - 1 = 98
even_minus_odd([-9])                        ->  -9

Constraints

  • 1 <= len(numbers) <= 1000; values are between -1000 and 1000.

Clarifying questions

  • Are indices 0-based?
  • Are the bounds -100 and 100 included?
  • Does a skipped value shift the indices of later values? (No.)

What a strong answer covers

  • One pass with the index parity and the range check; O(n) time, O(1) space.
  • Getting the boundaries right (exactly -100 and 100 count).
  • Tests: boundary values, every value out of range, a single element.

Follow-ups

  • Answer the same question for many subarrays [l, r] quickly (prefix sums of signed, filtered values).
  • The range bounds are parameters.
  • The values arrive as a stream.

Where it's asked

What it tests

arrays

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding