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:
- An array of integers,
nums. (Think of this as your list of people with numbers). - 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 usenums[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 is2) +nums[1](which is7) equals9. We return their positions:0and1.
- Why? Because
Example 2:
-
nums = [3, 2, 4] -
target = 6 - Output:
[1, 2]- Why? Because
nums[1](which is2) +nums[2](which is4) equals6. We return1and2.
- Why? Because
Example 3:
-
nums = [3, 3] -
target = 6 - Output:
[0, 1]- Why? Because
nums[0](which is3) +nums[1](which is3) equals6. Even though the numbers are the same, they are at different indices, so it's a valid pair!
- Why? Because
🤔 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.
- You'd probably start with the first number,
2. - Then, you'd ask: "If I use
2, what number do I need to reach9?" The answer is9 - 2 = 7. - Now, you'd scan the rest of the list (
7, 11, 15) to see if7exists. - Aha!
7is right there at index1. - You found your pair:
2(at index0) and7(at index1). Mission accomplished!
What if 2 didn't work? You'd move to the next number, 7, and repeat the process:
- Take
7. What do I need?9 - 7 = 2. - Scan the rest of the list (
11, 15) for2. (Actually, you'd also scan previous elements, but need to be careful not to use the same index). - Wait, we already considered
7with2. We don't want to re-check pairs we've already tried, or use7with 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:
- Pick a Number: Start with the first number in the
numsarray. Let's call its indexi. - 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]andnums[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 indexj. - Check the Sum: Add
nums[i]andnums[j]. - Is it the Target? If their sum equals
target, we've found our pair! We can immediately return their indices,[i, j]. - Keep Looking: If it's not the target, we move on to the next possible
jfor the currenti. If we run out ofj's for the currenti, we move to the nextiand start checkingj'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)
}
};
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, theni != jis always true, so you don't need(i != j)in theifcondition. This can be slightly cleaner. - My provided code with
j = iand(i != j)explicitly handles the case wherejcould bei, 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 runsntimes, wherenis the number of elements in thenumsarray. - Inner Loop: For each iteration of the outer loop, the
for (int j = i; j < nums.size(); j++)loop also runs up tontimes in the worst case (wheniis small). - Total Operations: Since we have nested loops, for roughly every element
i, we are checking against every other elementj. This leads to approximatelyn * n(orn²) 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^5elements),10^10operations 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
forloops 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









