Bird
Raised Fist0
Interview Prepmodified-binary-searchmediumGoogleAmazon

Magnetic Force Between Two Balls

Choose your preparation mode4 modes available
</>
IDE
def maxDistance(position: list[int], m: int) -> int:public int maxDistance(int[] position, int m)int maxDistance(vector<int>& position, int m)function maxDistance(position, m)
def maxDistance(position, m):
    # Write your solution here
    pass
class Solution {
    public int maxDistance(int[] position, int m) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int maxDistance(vector<int>& position, int m) {
    // Write your solution here
    return 0;
}
function maxDistance(position, m) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: Too large minimum distance (e.g., 4 instead of 3)Greedy check incorrectly assumes balls can be placed with larger distance without verifying placement count.✅ Implement greedy check that counts how many balls can be placed with given distance and adjust binary search accordingly.
Wrong: Too small minimum distance (e.g., 1 instead of 3)Binary search lower bound or greedy check logic is incorrect, causing premature termination.✅ Ensure binary search updates low and high bounds correctly based on greedy check results.
Wrong: Off-by-one errors in output (e.g., 3 instead of 2)Incorrect mid calculation or comparison in binary search loop.✅ Use mid = low + (high - low + 1) // 2 and adjust low/high based on feasibility to avoid infinite loops and off-by-one errors.
Wrong: Fails on large inputs or times outUsing brute force approach with O(n*d) complexity instead of binary search on answer space.✅ Implement binary search on answer space with O(n log d) complexity and greedy feasibility check.
Wrong: Incorrect output when m equals number of positionsGreedy check skips positions or does not handle placing balls at every position.✅ Ensure greedy check places balls at every position if needed and binary search range includes minimum gap.
✓
Test Cases
t1_01basic
Input{"position":[1,2,3,4,7],"m":3}
Expected3

Place balls at positions 1, 4, and 7. The minimum distance is min(4-1=3,7-4=3) = 3, which is the largest possible.

t1_02basic
Input{"position":[5,10,15,20,25],"m":2}
Expected20

With 2 balls, placing at positions 5 and 25 yields the maximum minimum distance of 20.

t2_01edge
Input{"position":[1,2],"m":2}
Expected1

Only two positions and two balls; max minimum distance is the difference 1.

t2_02edge
Input{"position":[1,2,3,4,5],"m":5}
Expected1

All positions consecutive and m equals number of positions; minimum distance is 1.

t2_03edge
Input{"position":[1,1000000000],"m":2}
Expected999999999

Positions are very spread out; max minimum distance is the difference 999999999.

t2_04edge
Input{"position":[1],"m":1}
Expected0

Single position and one ball; minimum distance is 0 since only one ball placed.

t3_01corner
Input{"position":[1,2,4,8,9],"m":3}
Expected3

Greedy trap test: placing balls greedily with too large distance may fail; correct max minimum distance is 3.

t3_02corner
Input{"position":[1,3,5,7,9],"m":4}
Expected2

Off-by-one error test: correct max minimum distance is 2, not 3.

t3_03corner
Input{"position":[1,2,4,7,11],"m":3}
Expected4

Test for confusion between 0/1 knapsack and binary search: max minimum distance is 5.

t4_01performance
Input{"position":[1,10001,20001,30001,40001,50001,60001,70001,80001,90001,100001,110001,120001,130001,140001,150001,160001,170001,180001,190001,200001,210001,220001,230001,240001,250001,260001,270001,280001,290001,300001,310001,320001,330001,340001,350001,360001,370001,380001,390001,400001,410001,420001,430001,440001,450001,460001,470001,480001,490001,500001,510001,520001,530001,540001,550001,560001,570001,580001,590001,600001,610001,620001,630001,640001,650001,660001,670001,680001,690001,700001,710001,720001,730001,740001,750001,760001,770001,780001,790001,800001,810001,820001,830001,840001,850001,860001,870001,880001,890001,900001,910001,920001,930001,940001,950001,960001,970001,980001,990001,1000001],"m":50}
⏱ Performance - must finish in 2000ms

Large input with n=100 and spaced positions to test O(n log d) complexity within 2 seconds.

Practice

(1/5)
1. Consider the following Python code that finds the smallest divisor for nums = [1, 2, 5, 9] and threshold = 6. What is the value of the variable mid during the first iteration of the while loop inside smallest_divisor?
easy
A. 4
B. 5
C. 3
D. 6

Solution

  1. Step 1: Initialize low and high

    low = 1, high = max(nums) = 9
  2. Step 2: Calculate mid in first iteration

    mid = (1 + 9) // 2 = 5; integer division yields 5.
  3. Step 3: Confirm mid value

    The first mid value is 5, matching 5.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Integer division midpoint between 1 and 9 is 5 -> [OK]
Hint: Mid is integer division of low and high boundaries [OK]
Common Mistakes:
  • Off-by-one error in calculating mid
  • Confusing mid with low or high values
  • Misunderstanding integer division behavior
2. What is the time complexity of the recursive modified binary search algorithm for finding a peak element in an array of size n, and why might some candidates mistakenly think it is worse?
medium
A. O(n) because each recursive call processes a subarray of size n-1
B. O(log n) because each recursive call halves the search space
C. O(n log n) because recursion adds a log n factor to linear scanning
D. O(log n) time but O(n) space due to recursion stack

Solution

  1. Step 1: Analyze recursive calls

    Each call halves the search space, so number of calls is O(log n).
  2. Step 2: Confirm work per call

    Each call does O(1) work (simple comparisons), so total time is O(log n).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Halving search space leads to logarithmic time [OK]
Hint: Halving input size -> O(log n) time [OK]
Common Mistakes:
  • Confusing recursion stack space with time
  • Assuming linear scan inside recursion
  • Thinking recursion multiplies complexity
3. What is the time complexity of the optimal binary search solution for finding the minimum speed to arrive on time, given n distances and a precision epsilon for floating point speed search?
medium
A. O(log n * (maxSpeed / epsilon))
B. O(n * maxSpeed)
C. O(n^2 * log(maxSpeed))
D. O(n * log((maxSpeed - minSpeed) / epsilon))

Solution

  1. Step 1: Identify the binary search iterations

    Binary search on speed range [minSpeed, maxSpeed] with precision epsilon takes O(log((maxSpeed - minSpeed)/epsilon)) steps.
  2. Step 2: Calculate per-iteration cost

    Each feasibility check sums over n distances, so O(n) per iteration.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Combining steps yields O(n log((maxSpeed - minSpeed)/epsilon)) [OK]
Hint: Binary search iterations times linear feasibility check [OK]
Common Mistakes:
  • Confusing maxSpeed with n
  • Ignoring epsilon precision in log factor
4. Suppose the problem is modified so that each number in the array can be divided multiple times (reuse allowed), and the sum of all ceiling divisions must still be ≤ threshold. Which modification to the algorithm is necessary to correctly find the smallest divisor?
hard
A. Use the same binary search with feasibility function, but modify feasibility to count repeated divisions per element
B. Switch to a greedy approach that picks divisors based on the largest elements first
C. Use dynamic programming to track all possible divisor sums with reuse
D. Binary search is no longer applicable; use brute force over all divisors

Solution

  1. Step 1: Understand the reuse modification

    Allowing multiple divisions per element means feasibility must consider repeated divisions, but the divisor search space remains monotonic.
  2. Step 2: Adapt feasibility function

    Modify feasibility to count how many times each element can be divided by the divisor (e.g., sum of ceiling divisions with reuse).
  3. Step 3: Retain binary search on answer space

    Binary search still applies because the feasibility condition remains monotonic with divisor.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Binary search with adapted feasibility handles reuse -> [OK]
Hint: Reuse changes feasibility, not binary search applicability [OK]
Common Mistakes:
  • Discarding binary search prematurely
  • Using greedy which breaks global constraints
  • Overcomplicating with DP when not needed
5. Suppose the problem is modified so that the matrix rows are sorted but columns are not guaranteed to be sorted. Which approach would correctly find the kth smallest element efficiently?
hard
A. Use the min-heap approach merging rows as before, since rows remain sorted.
B. Flatten the matrix and sort it, then return the kth element.
C. Use binary search on the value range with a counting function scanning the entire matrix.
D. Use a min-heap merging columns instead of rows.

Solution

  1. Step 1: Analyze matrix properties

    Rows are sorted but columns are not, so min-heap merging rows only partially orders elements.
  2. Step 2: Evaluate approaches

    Min-heap merging rows assumes columns sorted for correctness; binary search counting requires sorted rows and columns for efficient counting; flatten and sort works regardless.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Flatten and sort is the fallback when only rows sorted [OK]
Hint: Partial sorting breaks heap and binary search assumptions [OK]
Common Mistakes:
  • Assuming min-heap merging rows still works
  • Using binary search counting without full sorting
  • Ignoring matrix sorting properties
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