🧩

Two Sum Problem Summary and Solution

Apr 23, 2025

Lecture Notes: Coding Interview Questions - Two Sum Problem

Introduction

  • Topic: Two Sum problem from LeetCode.
  • Objective: Return indices of two numbers in an array that add up to a given target.
  • Assumption: Each input array has exactly one solution; no element is used twice.
  • Output Order: Indices can be returned in any order.

Problem Explanation

  • Example 1:

    • Input: [2, 7, 11, 15], Target: 9
    • Output: Indices 0 and 1 because 2 + 7 = 9.
  • Example 2:

    • Input: [3, 2, 4], Target: 6
    • Output: Indices 1 and 2 because 2 + 4 = 6.

Solution Strategy

  • Brute Force Approach:
    • Use two nested loops.
    • First loop variable i iterates over the array.
    • Second loop variable j iterates from i + 1 to the end of the array.
    • Check if nums[i] + nums[j] == target.
    • Return the indices i and j once the pair is found.

Implementation

  • Programming Language: Java.
  • Data Structures:
    • Use an array to store the result indices.
    • Loop through the array to find the pair adding up to the target.
  • Code Explanation:
    • Initialize int i and int j for looping.
    • Loop through i from 0 to nums.length - 1.
    • Use nested loop for j starting from i + 1 to nums.length.
    • If condition nums[i] + nums[j] == target is met:
      • Store i and j in an array arr.
      • Break the loop once the solution is found.
    • Return arr containing indices.

Code Walkthrough

  • Initialization:
    • Array arr of size 2.
    • Loop through elements using variables i and j.
  • Condition Check:
    • Add elements at i and j.
    • Check against the target.
  • Result Storage:
    • Store indices in arr.
  • Return Statement:
    • Return the indices array once condition is met.

Conclusion

  • The code successfully finds the indices of numbers that sum up to a given target.
  • The approach uses a brute force method with nested loops.
  • Further optimization can be discussed in other sessions.

Additional Information

  • Mentions ongoing Java course offering notes, quizzes, and projects.
  • Opportunity for students to engage with projects and extra resources.

Next Steps

  • Further LeetCode problems to be discussed in future videos.
  • Viewer engagement: Comments are encouraged for suggestions on specific problems or video content.