سوال ۶۲ کنکور ارشد علوم کامپیوتر ۱۴۰۴
یک آرایه از اعداد صحیح بهطول n و عدد x داده شده است. میخواهیم تعداد سهتاییهایی به فرم که را بیابیم (آرایه ممکن است شامل اعداد منفی نیز باشد). پیچیدگی زمانی بهینه از چه مرتبهای است؟
پاسخ صحیح: گزینهٔ B —
This is the classic 3SUM (counting variant): count index triples with .
Naive bound. Three nested loops give — that is option 3, not optimal.
The standard algorithm.
- Sort the array once: .
- Fix the first element (loop over , iterations). The subproblem becomes: count pairs with
- Solve each pair-count (a 2SUM on a sorted array) with a two-pointer sweep in : a left pointer and a right pointer move inward — if the sum is too small advance , if too large retreat , and on a hit count the matches. Each pointer crosses the array once, so per fixed .
Total:
Negative numbers cause no trouble: sorting and the two-pointer monotonicity argument only need a total order, which the integers have. Hashing gives the same expected bound but adds nothing asymptotically.
Why not lower? 3SUM is conjectured to have no truly sub- (e.g. ) algorithm — the 3SUM conjecture. So within the tools of a standard algorithms course, is the optimal achievable order, and (option 1) is not attainable.
Hence the optimal order is — option 2.
Exam trick: Whenever you must count/find items summing to a target, sort once and reduce dimension with two pointers: 2SUM drops to , 3SUM to , kSUM to — always one factor of below the brute force.