DEV Community

Pratik Bandgar
Pratik Bandgar

Posted on

LeetCode Solution: 1. Two Sum β€” May 23 2026 16:35

Two Sum: Your First LeetCode Adventure Begins! πŸš€

Hello, future problem-solvers and coding enthusiasts! πŸ‘‹

If you're just dipping your toes into the exciting world of LeetCode, congratulations! You've found yourself at the perfect starting point: Problem #1, "Two Sum." This isn't just any problem; it's often the very first one many developers encounter, and for good reason. It's a fantastic introduction to algorithmic thinking, array manipulation, and understanding basic complexity.

Don't worry if you're a beginner – we'll break it down step-by-step, making sure you grasp every concept. Let's dive in!


🧐 Problem Explanation: Find the Perfect Pair!

Imagine you're at a party, and you have a list of people, each wearing a badge with a number on it. Your mission is to find exactly two people whose numbers, when added together, equal a specific "target" number. Once you find them, you just need to tell us where they are in the line (their positions/indices).

Here's the formal description: ""

Given:

  1. An array of integers, nums. (Think of this as your list of people with numbers).
  2. An integer, target. (This is the sum you're trying to achieve).

Task:
Return the indices (positions) of the two numbers in nums that add up to target.

Important Rules:

  • Exactly one solution: You're guaranteed to find one pair that works. No need to worry about multiple pairs or no pairs at all!
  • No duplicates: You can't use the same number twice. If nums[0] is part of the sum, you can't use nums[0] again as the second number.
  • Order doesn't matter: [0, 1] is the same as [1, 0].

Let's look at some examples to make it super clear:

Example 1:

  • nums = [2, 7, 11, 15]
  • target = 9
  • Output: [0, 1]
    • Why? Because nums[0] (which is 2) + nums[1] (which is 7) equals 9. We return their positions: 0 and 1.

Example 2:

  • nums = [3, 2, 4]
  • target = 6
  • Output: [1, 2]
    • Why? Because nums[1] (which is 2) + nums[2] (which is 4) equals 6. We return 1 and 2.

Example 3:

  • nums = [3, 3]
  • target = 6
  • Output: [0, 1]
    • Why? Because nums[0] (which is 3) + nums[1] (which is 3) equals 6. Even though the numbers are the same, they are at different indices, so it's a valid pair!

πŸ€” Intuition: How Would You Find Them?

Okay, put your computer science hat aside for a moment. If you had to solve this manually with a small list of numbers and a target, how would you do it?

Let's say nums = [2, 7, 11, 15] and target = 9.

  1. You'd probably start with the first number, 2.
  2. Then, you'd ask: "If I use 2, what number do I need to reach 9?" The answer is 9 - 2 = 7.
  3. Now, you'd scan the rest of the list (7, 11, 15) to see if 7 exists.
  4. Aha! 7 is right there at index 1.
  5. You found your pair: 2 (at index 0) and 7 (at index 1). Mission accomplished!

What if 2 didn't work? You'd move to the next number, 7, and repeat the process:

  1. Take 7. What do I need? 9 - 7 = 2.
  2. Scan the rest of the list (11, 15) for 2. (Actually, you'd also scan previous elements, but need to be careful not to use the same index).
  3. Wait, we already considered 7 with 2. We don't want to re-check pairs we've already tried, or use 7 with itself.

This "try every combination" idea is the core of our first approach!


πŸšΆβ€β™‚οΈ Approach: The Brute-Force Way

The most straightforward way to find a pair is to simply check every single possible pair of numbers in the array. This is often called the "brute-force" approach.

Here's how we'll do it step-by-step:

  1. Pick a Number: Start with the first number in the nums array. Let's call its index i.
  2. Pick Another Number: Now, pick another number from the array. This second number must be after the first number (i) to ensure we don't use the same element twice (e.g., nums[i] and nums[i]) and to avoid checking the same pair twice (e.g., checking (nums[0], nums[1]) and then later (nums[1], nums[0])). Let's call its index j.
  3. Check the Sum: Add nums[i] and nums[j].
  4. Is it the Target? If their sum equals target, we've found our pair! We can immediately return their indices, [i, j].
  5. Keep Looking: If it's not the target, we move on to the next possible j for the current i. If we run out of j's for the current i, we move to the next i and start checking j's from there.

Since we are guaranteed that "exactly one solution exists," our loops will eventually find the pair and return.


πŸ’» Code: Bringing the Brute Force to Life (C++)

class Solution {
public:
    std::vector<int> twoSum(std::vector<int>& nums, int target) {
        // Outer loop: iterates through each element with index 'i'
        for (int i = 0; i < nums.size(); i++) {
            // Inner loop: iterates through each element with index 'j'
            // We start 'j' from 'i' to ensure we consider all combinations,
            // but carefully handle the "same element twice" constraint inside the loop.
            for (int j = i; j < nums.size(); j++) {
                // Check if the sum of nums[i] and nums[j] equals the target
                // AND ensure that 'i' and 'j' are not the same index.
                // The 'j = i' in the inner loop means we start checking from the current 'i'.
                // If we didn't add 'i != j', it would incorrectly sum an element with itself.
                if ((nums[i] + nums[j] == target) && (i != j)) {
                    // If both conditions are met, we found our pair!
                    // Return their indices as a vector.
                    return {i, j};
                }
            }
        }
        // According to the problem constraints, there will always be exactly one solution.
        // So, this line should ideally never be reached in a valid test case.
        return {}; // Return an empty vector if no solution is found (for safety, though not expected)
    }
};

Enter fullscreen mode Exit fullscreen mode

A note on j = i vs. j = i + 1:
You might see other solutions where the inner loop starts with j = i + 1. Both are valid ways to prevent using the same element twice and avoid redundant checks.

  • If j = i + 1, then i != j is always true, so you don't need (i != j) in the if condition. This can be slightly cleaner.
  • My provided code with j = i and (i != j) explicitly handles the case where j could be i, but then discards it. It works perfectly fine!

⏱️ Time & Space Complexity Analysis

Understanding how "expensive" your code is in terms of time and memory is crucial in competitive programming.

Time Complexity: O(nΒ²)

  • Outer Loop: The for (int i = 0; i < nums.size(); i++) loop runs n times, where n is the number of elements in the nums array.
  • Inner Loop: For each iteration of the outer loop, the for (int j = i; j < nums.size(); j++) loop also runs up to n times in the worst case (when i is small).
  • Total Operations: Since we have nested loops, for roughly every element i, we are checking against every other element j. This leads to approximately n * n (or nΒ²) operations.
  • Big O Notation: We express this as O(nΒ²), which stands for "Order n-squared." This means the time taken grows quadratically with the input size. For small arrays, it's fine, but for very large arrays (e.g., 10^5 elements), 10^10 operations would be too slow!

Space Complexity: O(1)

  • Extra Memory: We are not using any additional data structures (like maps, hash sets, or new arrays) that grow in size with the input n. We're just using a few variables (i, j, target, nums[i], nums[j]) to store temporary values.
  • Big O Notation: We express this as O(1), which means "constant space." The amount of memory used does not depend on the size of the input array.

πŸ”‘ Key Takeaways

  • Brute Force is a Starting Point: Often, the first solution you think of (like checking every possibility) is a brute-force approach. It might not be the most efficient, but it's great for getting started and understanding the problem.
  • Nested Loops = O(nΒ²): A common pattern: if you see nested for loops where each loop iterates over the input data, it's a strong indicator of O(nΒ²) time complexity.
  • Constraints Matter: The problem statement's guarantee of "exactly one solution" simplifies things, as we don't need to handle cases where no pair is found.
  • The Follow-Up is a Hint: LeetCode problems often include "Follow-up" questions (like "Can you come up with an algorithm that is less than O(nΒ²) time complexity?"). This is a clear invitation to think about optimizations! For "Two Sum," there's a much faster O(n) solution using hash maps/dictionaries – but that's a story for another blog post! πŸ˜‰

You've just tackled your first LeetCode problem with a solid, understandable solution! This is a fantastic step on your coding journey. Keep practicing, keep learning, and happy coding!


Submission Details:
Author Account: pratik_bandgar9009
Time Published: 2026-05-23 16:34:50

Top comments (0)