DEV Community

Pratik Bandgar
Pratik Bandgar

Posted on

LeetCode Solution: 1. Two Sum

Two Sum: Your First LeetCode Challenge & Why It Matters!

Hello, future coding rockstars! πŸ‘‹ Are you ready to embark on your LeetCode journey? There's no better place to start than with problem number one: Two Sum. This isn't just any problem; it's a rite of passage, a classic, and a fantastic way to grasp fundamental algorithmic thinking.

Let's dive in and conquer it together!

🀝 Problem Explanation: Finding the Perfect Pair

Imagine you have a list of numbers, like [2, 7, 11, 15]. Now, imagine I give you a target number, say 9. Your mission, should you choose to accept it, is to find two different numbers in that list that, when added together, equal our target.

But there's a twist! You don't return the numbers themselves; you return their positions (their indices) in the list.

Let's look at our example:
nums = [2, 7, 11, 15], target = 9

  • 2 is at index 0
  • 7 is at index 1
  • 11 is at index 2
  • 15 is at index 3

Can you spot the pair that adds up to 9?
Bingo! 2 + 7 = 9.
Since 2 is at index 0 and 7 is at index 1, our answer would be [0, 1].

A few crucial points:

  • Exactly one solution: You'll always find one perfect pair. No need to worry about multiple pairs or no pair at all.
  • Don't use the same element twice: If nums = [3, 3], target = 6, you use the 3 at index 0 and the other 3 at index 1. You can't use nums[0] with nums[0] to make 6.
  • Any order: [0, 1] or [1, 0] are both valid for our example.

πŸ€” The Intuition: The Brute-Force Detective

How would you, a human, solve this if you had a small list of numbers and a target?

You'd probably pick the first number, say 2. Then, you'd look at every other number in the list (7, 11, 15) and ask: "Does 2 plus any of these equal 9?"

  • 2 + 7 = 9? Yes! Found it!

If 2 didn't work, you'd move to the next number, 7. Then you'd check 7 against all subsequent numbers, and so on. This "check every possible pair" strategy is what we call brute force. It's straightforward, and it's often the first idea that comes to mind for many problems.

πŸšΆβ€β™‚οΈ Our Approach: The Nested Loop Saga

To translate our human intuition into code, we need to systematically check every possible pair. How do we do that? With nested loops!

Here's the step-by-step breakdown of how the provided solution works:

  1. Outer Loop (Picking the First Number): We start with a loop that iterates through each number in our nums array. Let's say this loop uses an index i. This i will represent the index of our first potential number.

    For i from 0 to (length of nums - 1):
        Let current_num_1 = nums[i]
    
  2. Inner Loop (Finding the Partner): Inside our first loop, we start another loop. This inner loop will iterate through the remaining numbers in nums, looking for a partner for nums[i]. Let's say this loop uses an index j.

*   Crucially, `j` starts from `i`. Why `i`? Because we want to check numbers from the current position onwards.
*   To ensure we don't use the *same element twice* (as required by the problem), we'll add a condition: `i != j`. This makes sure we're always comparing two distinct positions.
Enter fullscreen mode Exit fullscreen mode
```
For j from i to (length of nums - 1):
    Let current_num_2 = nums[j]
```
Enter fullscreen mode Exit fullscreen mode
  1. The Check: Inside the inner loop, after we've picked nums[i] and nums[j], we perform our core check:

    • Is nums[i] + nums[j] equal to our target?
    • AND, is i not equal to j (to make sure we're using two different elements)?
    If (current_num_1 + current_num_2 == target) AND (i != j):
        We found our pair! Return the indices [i, j].
    
  2. No Return (The Unlikely Scenario): According to the problem constraints, we are guaranteed to find exactly one solution. So, the code will always return [i, j] inside the loops and never reach the return {}; statement at the end. It's good practice to have a fallback return, but in this specific problem, it's theoretically unreachable.

Let's walk through nums = [2, 7, 11, 15], target = 9 again with this approach:

i nums[i] j nums[j] i != j? nums[i] + nums[j] == target? Action
0 2 0 2 False 4 No Skip
0 2 1 7 True 9 Yes! Return [0, 1]

And that's it! We found the solution on the very first "real" check.

πŸ’» Code: The Brute-Force in C++

class Solution {
public:
    std::vector<int> twoSum(std::vector<int>& nums, int target) {
        // Outer loop iterates through each number from the start
        for (int i = 0; i < nums.size(); i++) {
            // Inner loop iterates through numbers starting from the current 'i'
            // This ensures we check all pairs without repeating (e.g., (2,7) vs (7,2))
            for (int j = i; j < nums.size(); j++) {
                // Check if the sum equals the target AND
                // if we are not using the same element twice (i.e., different indices)
                if ((nums[i] + nums[j] == target) && (i != j)) {
                    // If both conditions are met, we found our pair!
                    // Return their indices in a vector.
                    return {i, j};
                }
            }
        }
        // According to the problem constraints, there will always be exactly one solution,
        // so this line should theoretically never be reached.
        return {}; 
    }
};
Enter fullscreen mode Exit fullscreen mode

⏱️ Time & Space Complexity Analysis

Understanding how efficient your code is, is crucial for competitive programming and software development.

  • Time Complexity: O(nΒ²)

    • We have two nested loops.
    • The outer loop runs n times (where n is the number of elements in nums).
    • The inner loop, in the worst case, also runs n times for each iteration of the outer loop.
    • So, n * n = nΒ² operations. This is generally considered a "slower" approach for larger inputs, but it's a perfectly valid starting point.
  • Space Complexity: O(1)

    • We are not using any extra data structures that grow with the input size n. We only use a few variables (i, j, nums[i], nums[j]) to store current values.
    • This means our solution uses a constant amount of extra memory, regardless of how large the input array nums is. Pretty efficient on memory!

✨ Key Takeaways

  1. Brute Force is a Starting Point: Don't be afraid to start with the most straightforward approach that comes to mind. It's a great way to understand the problem and get a solution working.
  2. Nested Loops for Pairwise Checks: When you need to check every combination of two elements in a list, nested loops are your go-to pattern.
  3. Complexity Matters: Always think about how your solution scales. O(nΒ²) might be fine for small inputs, but for larger datasets, you'll often need something faster.
  4. Read Constraints Carefully: "Exactly one solution" and "not use the same element twice" are critical details that guide your logic.

This problem has a famous "Follow-up" asking for an algorithm less than O(nΒ²) time complexity. This is where Hash Maps (or Dictionaries in Python) shine, allowing you to solve it in O(n) time! But that's a story for another day, once you've mastered the basics!

Congratulations on tackling your first LeetCode problem! Keep coding, keep learning, and you'll be solving complex algorithms in no time.


Authored by pratik_bandgar9009 | Published: 2026-05-23 16:28:17

Top comments (0)