Bird
Raised Fist0
Interview Prephash-maps-setseasyAmazonGoogleFacebookMicrosoftBloomberg

Two Sum

Choose your preparation mode4 modes available
</>
IDE
def two_sum(nums: list[int], target: int) -> list[int]:public int[] twoSum(int[] nums, int target)vector<int> twoSum(vector<int>& nums, int target)function twoSum(nums, target)
def two_sum(nums, target):
    # Write your solution here
    pass
class Solution {
    public int[] twoSum(int[] nums, int target) {
        // Write your solution here
        return new int[2];
    }
}
#include <vector>
using namespace std;

vector<int> twoSum(vector<int>& nums, int target) {
    // Write your solution here
    return {};
}
function twoSum(nums, target) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: [-1, -1]Returning default or error indices instead of valid pair.✅ Ensure to return indices immediately when complement found; do not return default values.
Wrong: [0,0]Using same element twice instead of two distinct indices.✅ Check complement in map before inserting current index to avoid using same element twice.
Wrong: [0,2]Greedy approach picking wrong pair or incorrect order.✅ Use hash map complement lookup and return first valid pair found during iteration.
Wrong: No output or timeoutUsing nested loops causing O(n^2) time complexity.✅ Implement hash map complement lookup for O(n) time complexity.
Wrong: [1,3]Returning wrong pair when multiple pairs possible.✅ Return the first valid pair found during iteration as guaranteed unique answer.
✓
Test Cases
t1_01basic
Input{"nums":[2,7,11,15],"target":9}
Expected[0,1]

nums[0] + nums[1] = 2 + 7 = 9

t1_02basic
Input{"nums":[3,2,4],"target":6}
Expected[1,2]

nums[1] + nums[2] = 2 + 4 = 6

t2_01edge
Input{"nums":[1,2],"target":3}
Expected[0,1]

Only two elements, sum to target exactly.

t2_02edge
Input{"nums":[-3,4,3,90],"target":0}
Expected[0,2]

nums[0] + nums[2] = -3 + 3 = 0, includes negative numbers.

t2_03edge
Input{"nums":[0,4,3,0],"target":0}
Expected[0,3]

Target zero with zeros in array; nums[0] + nums[3] = 0 + 0 = 0.

t2_04edge
Input{"nums":[1,1],"target":2}
Expected[0,1]

Exact boundary case with two identical elements summing to target.

t3_01corner
Input{"nums":[1,2,3,4,5],"target":7}
Expected[1,4]

nums[1] + nums[4] = 2 + 5 = 7; tests greedy trap of picking first complement found.

t3_02corner
Input{"nums":[3,3],"target":6}
Expected[0,1]

Tests handling of duplicates and 0/1 usage constraint; must not reuse same element twice.

t3_03corner
Input{"nums":[1,5,1,5],"target":10}
Expected[1,3]

Tests multiple pairs possible but only one valid answer guaranteed; must return correct pair.

t4_01performance
Input{"nums":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100],"target":199}
⏱ Performance - must finish in 2000ms

Large input n=100, testing O(n) hash map approach completes within time limit.

Practice

(1/5)
1. Consider the following Python function to find the longest contiguous subarray with equal number of 0s and 1s. What is the returned value when the input is [0, 1, 0, 1]?
def findMaxLength(nums):
    prefix_sum = 0
    seen = {0: -1}
    max_length = 0
    for i, num in enumerate(nums):
        prefix_sum += 1 if num == 1 else -1
        if prefix_sum in seen:
            max_length = max(max_length, i - seen[prefix_sum])
        else:
            seen[prefix_sum] = i
    return max_length
easy
A. 4
B. 2
C. 3
D. 0

Solution

  1. Step 1: Trace prefix sums and seen map

    Index 0: num=0 -> prefix_sum=-1, seen={0:-1, -1:0}, max_length=0 Index 1: num=1 -> prefix_sum=0, seen has 0 at -1, max_length=max(0,1-(-1))=2 Index 2: num=0 -> prefix_sum=-1, seen has -1 at 0, max_length=max(2,2-0)=2 Index 3: num=1 -> prefix_sum=0, seen has 0 at -1, max_length=max(2,3-(-1))=4
  2. Step 2: Return max_length

    max_length is 4, the length of the entire array.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Full array balanced, max_length=4 [OK]
Hint: Prefix sums track balance; max length updates on repeated sums [OK]
Common Mistakes:
  • Off-by-one errors in length calculation
  • Ignoring initial seen entry for sum 0
  • Confusing prefix sum updates
2. Consider the following buggy code for detecting if a number is happy. Which line contains the subtle bug that can cause incorrect results or infinite loops?
def sum_of_squares(num):
    return sum(int(d) ** 2 for d in str(num))

UNHAPPY_CYCLE = {4, 16, 37, 58, 89, 145, 42, 20}

def isHappy(n: int) -> bool:
    while n != 1 and n not in UNHAPPY_CYCLE:
        n = sum_of_squares(n)
    return true
medium
A. Line 8: return true statement
B. Line 6: while loop condition
C. Line 2: sum_of_squares function implementation
D. Line 7: updating n with sum_of_squares(n)

Solution

  1. Step 1: Analyze return statement

    The function returns true unconditionally after loop ends, ignoring if n is in unhappy cycle.
  2. Step 2: Identify correct return logic

    Should return n == 1 to distinguish happy from unhappy numbers.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Incorrect return causes false positives [OK]
Hint: Return must check if n == 1 after loop [OK]
Common Mistakes:
  • Returning true always after loop
  • Ignoring unhappy cycle detection
3. The following code attempts to find the longest subarray with sum divisible by k. Identify the line containing the subtle bug that causes incorrect results for arrays containing negative numbers.
def longest_subarray_div_by_k(nums, k):
    earliest = [-2] * k
    earliest[0] = -1
    max_length = 0
    prefix_sum = 0
    for i, num in enumerate(nums):
        prefix_sum += num
        remainder = prefix_sum % k
        # Bug: missing adjustment for negative remainder
        if earliest[remainder] != -2:
            max_length = max(max_length, i - earliest[remainder])
        else:
            earliest[remainder] = i
    return max_length
medium
A. Line computing remainder = prefix_sum % k
B. Line initializing earliest[0] = -1
C. Line updating max_length = max(max_length, i - earliest[remainder])
D. Line setting earliest[remainder] = i

Solution

  1. Step 1: Identify remainder calculation

    When prefix_sum is negative, prefix_sum % k in Python returns a non-negative remainder, but in some languages or implementations it can be negative. The code lacks adjustment for negative remainder.
  2. Step 2: Why this causes bugs

    If remainder is negative, indexing earliest array causes errors or misses correct subarrays. The fix is to add if remainder < 0: remainder += k.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Negative prefix sums require remainder adjustment [OK]
Hint: Check remainder calculation for negative sums [OK]
Common Mistakes:
  • Forgetting to adjust negative remainders
  • Misinitializing earliest array
  • Updating max_length incorrectly
4. What is the time complexity of the get operation in the optimal time-based key-value store implementation that uses a hash map with sorted timestamp lists and binary search?
medium
A. O(log n), where n is the number of timestamps stored for the key
B. O(n), where n is the number of timestamps stored for the key
C. O(log m), where m is the total number of keys stored
D. O(1), constant time due to hash map usage

Solution

  1. Step 1: Identify the data structure used for retrieval

    Retrieval uses binary search on a sorted list of timestamps for the given key.
  2. Step 2: Analyze binary search complexity

    Binary search on n timestamps takes O(log n) time. Hash map lookup is O(1) average but the dominant cost is binary search.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Binary search on timestamps list dominates get operation time [OK]
Hint: Binary search on timestamps list is O(log n) [OK]
Common Mistakes:
  • Confusing total keys with timestamps count
  • Assuming hash map makes get O(1) ignoring binary search
  • Mistaking linear search complexity for get
5. What is the time complexity of the optimal frequency counting approach for checking if two strings of length n are anagrams, assuming the strings contain only lowercase English letters?
medium
A. O(n log n) due to sorting the strings
B. O(n) because each string is traversed once and frequency updates are O(1)
C. O(n * 26) because for each character you update a frequency array of size 26
D. O(1) since the frequency array size is fixed and independent of input length

Solution

  1. Step 1: Identify loops over input strings

    Both strings are traversed once, each iteration doing O(1) work updating counts.
  2. Step 2: Analyze frequency array operations

    Frequency array is fixed size 26, so updates are constant time, not multiplied by n.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Overall time is linear in string length n [OK]
Hint: Frequency updates are O(1), total O(n) time [OK]
Common Mistakes:
  • Confusing sorting complexity with counting
  • Multiplying by 26 unnecessarily
  • Assuming constant time overall
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard