00:00

Problem Statement

Input/Output Examples

Visual Explanation

Because the array is sorted, the pointers can only move in one direction each, so every fixed value costs one linear scan. Skipping equal fixed values and equal pointer values prevents duplicates.

Approaches

Sorting plus two pointers is the standard quadratic solution. The brute force tries every triple.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements. Sorting costs O(n log n), and each fixed value needs one linear pointer scan, so the total is O(n²).

Interview Tips and Recommended Approach

  • Skip duplicates in three places: the fixed value, the left pointer and the right pointer.
  • Stop early. Once the fixed value is positive, no later triplet can sum to zero.
  • Reduce to two-sum. Explaining the problem that way shows the structure.
  • Know the generalisation: k-sum adds one loop per extra element.

Recommended Approach: Sort and Two Pointers

Why: it is the expected O(n²) answer, and sorting makes both the search and the duplicate handling simple.