BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features45 of 54 in topic

817. Two sum: find two prompts that exactly fill a token budget

EasyData processing and features

Why it matters Two Sum is the most asked warm-up coding question, and the hash-map trick reappears in dedup and join problems.

This is the classic Two Sum interview problem in an LLM setting. You have the token counts of many prompts and want two different prompts that together use exactly the remaining context budget.

Write two_sum(counts, target). Return the pair of indices [i, j] with i < j and counts[i] + counts[j] == target that has the smallest j, and among those the smallest i. Return [] if no pair exists. Aim for O(n) with a dictionary instead of checking every pair.

Functiondef two_sum(counts, target)

Example 1

Input: two_sum([300, 1200, 500, 700], 1200)

Output: [2, 3]

Example 2

Input: counts = [3, 3], target = 6

Output: [0, 1]

Example 3

Input: counts = [1, 2, 3], target = 100

Output: []

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 6 tests to be accepted.
Hint 1

For each element, what value would complete the pair?

Hint 2

Store each value's first index in a dict as you go, and check the dict before inserting the current value.

Common mistakes
  • Checking every pair, which is O(n^2) and too slow for 200,000 items.
  • Inserting the current value before checking, which pairs an element with itself.
Understand the idea

Walk the list once. For each value, the partner you need is target - value. A dictionary of values seen so far (keeping the first index of each) answers whether that partner appeared earlier in O(1).

Worked example

counts [300, 1200, 500, 700], target 1200. At index 3 (700) we need 500, seen at index 2, so the answer is [2, 3].

if target - c in seen: return [seen[target - c], j]; else remember c
Topics
Data processing and features
Similar questions
  • Standardise features without leaking test dataEasy
  • Scale features with the median and IQR so outliers do not dominateEasy
  • Encode hour of day and day of week as sine and cosine featuresEasy
  • Clip outliers using percentiles learned on the training set onlyEasy
All Data processing and features problems
Report
817 / 903
Python 3solution.pyPython idle
1
2
3
4
def two_sum(counts, target):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 6 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS