Predict output when iterating ordered keys
IntersystemsSoftware Engineer · Technical ScreenLast updated
This problem tests your understanding of ordered map iteration, the impact of modifying collection traversal, and handling accumulation logic in a state-dependent loop.
Problem Statement
Given a SortedMap (a data structure that maintains keys in ascending order) and an integer target, design a function that performs the following logic:
- Iterate through the keys in descending order.
- Maintain a running sum of the values associated with the keys visited.
- If the current key is even, multiply the current running sum by 2.
- If the running sum exceeds the
target, stop iterating immediately and return the current sum. - If the map is fully traversed, return the final running sum.
Function Signature
def process_map_sum(data: dict, target: int) -> int:
# data is a dictionary representing the sorted map
# keys are integers, values are integers
pass
Constraints
- The input map will contain between 1 and 1000 keys.
- Keys and values are between -10^4 and 10^4.
targetis between -10^6 and 10^6.
Example 1
Input: data = {1: 10, 2: 20, 3: 30}, target = 50
Order (Descending): 3, 2, 1
- Key 3: sum = 30.
- Key 2 (even): sum = (30 + 20) * 2 = 100.
- 100 > 50, return 100.
Output: 100
Example 2
Input: data = {1: 5, 2: 5}, target = 100
Order (Descending): 2, 1
- Key 2 (even): sum = 5 * 2 = 10.
- Key 1: sum = 10 + 5 = 15.
Output:
15
Hints
Hint 1
Ensure you extract the keys and sort them in descending order before initiating the loop.
Hint 2
Remember that the parity check (even/odd) applies to the key, not the value.
Hint 3
Pay close attention to the order of operations: add the value to the sum first, then apply the multiplier if the key is even.
Follow-up questions
- How would your implementation change if you were required to handle a very large dataset that does not fit into memory?
- What is the time complexity of your solution, and how does the sorting step impact performance?
- How would you modify this code to handle cases where the map contains floating-point values instead of integers?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.