Compute balances and array queries
Company: Current
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency in data structures and algorithms, focusing on array processing, aggregation for computing per-user balances, and handling mutable range-sum queries.
Compute Final Balances per User
Constraints
- 0 <= number of transactions <= 10^5
- Each amount fits in a 32-bit signed integer
- userId is a non-empty string
- A user's net balance may be zero or negative
Examples
Input: ([['a', 100], ['b', 50], ['a', -30], ['b', 20], ['c', 75]],)
Expected Output: {'a': 70, 'b': 70, 'c': 75}
Explanation: a: 100-30=70, b: 50+20=70, c: 75.
Input: ([],)
Expected Output: {}
Explanation: No transactions yields an empty balance map.
Hints
- A single hash map keyed by userId is enough.
- Accumulate each amount into the running total for its userId; you only need one pass.
- Use get(userId, 0) (or equivalent) so the first transaction for a new user starts from 0.
Minimum Size Subarray Sum (LeetCode 209)
Constraints
- 1 <= target <= 10^9
- 0 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^4 (all elements are positive)
Examples
Input: (7, [2, 3, 1, 2, 4, 3])
Expected Output: 2
Explanation: [4,3] sums to 7 with length 2; no length-1 subarray reaches 7.
Input: (4, [1, 4, 4])
Expected Output: 1
Explanation: A single element 4 already meets the target, length 1.
Hints
- All elements are positive, so a sliding window's sum grows when you extend the right end and shrinks when you advance the left end.
- Expand the window to the right; whenever the running sum is >= target, record the length and contract from the left.
- Track the minimum window length seen; return 0 if the total sum never reaches target.
Range Sum Query - Mutable (LeetCode 307)
Constraints
- 1 <= nums.length <= 3 * 10^4
- -100 <= nums[i], val <= 100
- 0 <= i, l, r < nums.length and l <= r
- 0 <= number of operations <= 3 * 10^4
Examples
Input: ([1, 3, 5], [['sumRange', 0, 2], ['update', 1, 2], ['sumRange', 0, 2]])
Expected Output: [9, 8]
Explanation: 1+3+5=9; after nums[1]=2 the array is [1,2,5] summing to 8.
Input: ([0], [['sumRange', 0, 0], ['update', 0, 5], ['sumRange', 0, 0]])
Expected Output: [0, 5]
Explanation: Single-element array: query 0, then set it to 5, then query 5.
Hints
- A Fenwick tree (Binary Indexed Tree) or a segment tree supports both point updates and range-sum queries in O(log n).
- For an update, apply the delta (newVal - currentVal) to the structure and remember the new current value so the next update on that index uses the correct delta.
- Compute a range sum [l, r] as prefix(r) - prefix(l - 1); be careful with 0- vs 1-based indexing inside the BIT.