Two Pointers pattern

4Sum

Given an array and a target, return all unique quadruples [a, b, c, d] that sum to the target. The solution set must not contain duplicate quadruples. Watch it run step by step, then write your own pseudocode and get it checked by AI.

  • LeetCode 18
  • Medium
  • 2 approaches

Sign in with Google or GitHub and you land straight on this page. DSA comes with the all labs plan and every ChaiCode batch.

Two PointersLeetCode 18

Medium

From the first idea to the best one

  1. 01 Brute force · four nested loops O(n⁴)O(1) space
  2. 02 Optimized · sort + two pointers O(n³)O(1) space
Each approach plays step by step, with its time and space.

What you will learn

  • How to read 4Sum and spot the two pointers pattern in it
  • Brute force · four nested loops: O(n⁴) time, O(1) space
  • Optimized · sort + two pointers: O(n³) time, O(1) space
  • The pseudocode for each approach, its line lit as the animation runs
  • Practice: write your own pseudocode and get it checked

More Two Pointers

See 4Sum run, step by step

Sign in and this page opens on the animation, with all 12 Two Pointers problems beside it.

DSA comes with the all labs plan and every ChaiCode batch.