Summary of "3 Sum | Brute - Better - Optimal with Codes"

Summary of “3 Sum | Brute - Better - Optimal with Codes”

This video is a detailed tutorial on solving the classic 3 Sum problem from Data Structures and Algorithms (DSA). It is part of Striver’s A to Z DSA course, an in-depth resource for mastering DSA with over 455 modules and 400+ problems solved.


Problem Statement


Approaches Covered

1. Brute Force Solution (O(n³))

Concept:

Steps:

  1. Loop i from 0 to n-3.
  2. Loop j from i+1 to n-2.
  3. Loop k from j+1 to n-1.
  4. If arr[i] + arr[j] + arr[k] == 0, sort the triplet and insert into a set.

Complexity:

Drawback: Time limit exceeded for large inputs; inefficient.


2. Better Solution Using Hashing (O(n² log m))

Concept:

Key Points:

Steps:

  1. Loop i from 0 to n-2.
  2. Initialize empty hash set.
  3. Loop j from i+1 to n-1.
  4. Calculate third = -(arr[i] + arr[j]).
  5. If third in hash set, add sorted triplet to answer set.
  6. Add arr[j] to hash set.

Complexity:

Drawback: Still uses extra space for sets; interviewer might ask for further optimization.


3. Optimal Solution Using Sorting + Two Pointers (O(n²))

Concept:

Key Points:

Steps:

  1. Sort array.
  2. For i in 0 to n-3:
    • Skip if arr[i] is same as previous to avoid duplicates.
    • Set j = i+1, k = n-1.
    • While j < k:
      • Calculate sum = arr[i] + arr[j] + arr[k].
      • If sum == 0, add triplet and move pointers skipping duplicates.
      • Else if sum < 0, move j forward.
      • Else move k backward.

Complexity:

Advantages:


Additional Notes


Speakers / Source


Summary

The video teaches how to solve the 3 Sum problem with three approaches:

This progression shows how to optimize a naive solution into an interview-ready efficient algorithm.

Category ?

Educational

Share this summary

Video