Cracking the Code: Your First LeetCode Journey with Two Sum! 🚀
Hey amazing developers! 👋 Ever wondered where to begin your LeetCode adventure? Look no further! The "Two Sum" problem is famously known as LeetCode's very first problem, and it's an absolute classic for a reason. It's a fantastic starting point to understand fundamental algorithms and data structures.
Today, we're going to dive deep into Two Sum (Problem #1), break it down, understand the thinking process, and explore a straightforward solution. Let's get started!
The Problem: Two Sum Explained Simply
Imagine you have a list of numbers, say [2, 7, 11, 15]. You're also given a specific target number, like 9.
Your goal? Find two different numbers in that list that add up to your target. Once you find them, you don't return the numbers themselves, but their positions (their indices) in the list.
Here are the key rules:
- One Solution Only: You can always assume there will be exactly one pair of numbers that adds up to the target. No need to worry about multiple answers or no answers!
- No Repeats: You can't use the same number twice. For example, if
nums = [3, 2, 4]andtarget = 6, you can't use the3at index0with itself. You'd need to find2(index1) and4(index2).
Let's look at the examples:
Example 1:
nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] (which is 2) + nums[1] (which is 7) == 9.
Example 2:
nums = [3,2,4], target = 6
Output: [1,2]
Explanation: nums[1] (which is 2) + nums[2] (which is 4) == 6.
Example 3:
nums = [3,3], target = 6
Output: [0,1]
Explanation: nums[0] (which is 3) + nums[1] (which is 3) == 6.
The Intuition: How Would You Solve It? 🤔
Forget code for a second. If a friend gave you this list and a target, how would your brain tackle it?
You'd probably pick the first number, right? Say 2. Then you'd think, "Okay, what number do I need to add to 2 to get 9? Ah, 7!"
Then you'd scan the rest of the list to see if 7 is there. If you find it, boom! You have your pair.
If 7 wasn't there, or if 2 didn't lead to a pair, you'd move to the next number in your list, say 7. Then you'd ask, "What number do I need to add to 7 to get 9? 2!" You'd scan the remaining numbers for 2.
This "pick one, then check all others" approach is exactly the core intuition for our first solution!
Our Approach: Brute Force (The Straightforward Way)
The intuition above translates directly into a programming strategy called Brute Force. It simply means trying every single possible combination until we find the one that works.
Here's a step-by-step breakdown:
Pick a First Number: We'll use a loop to go through our
numsarray, picking each number one by one. Let's saynums[i]is the current "first number" we're considering.Look for its Partner: For each
nums[i], we need to find another numbernums[j]in the rest of the array such thatnums[i] + nums[j] == target. So, we'll use a second loop, nested inside the first one, to iterate through all possiblenums[j]values.Crucial Check: Different Elements: Remember the rule: "You may not use the same element twice." This means
i(the index of our first number) must not be equal toj(the index of our second number).Found It! If
nums[i] + nums[j]equalstargetANDiis not equal toj, we've found our pair! We can immediately return their indices[i, j].
Since the problem guarantees there's always exactly one solution, we know our loops will eventually find the correct pair and return.
The Code 💻
Let's translate that logic into C++ code.
class Solution {
public:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
// Outer loop: iterates through each number, considering it as the first element of our pair.
// 'i' will represent the index of the first number.
for (int i = 0; i < nums.size(); i++) {
// Inner loop: iterates through the remaining numbers to find a partner for 'nums[i]'.
// We start 'j' from 'i' (or i+1 to optimize slightly and avoid i==j check, but the problem's
// given solution starts j from i and explicitly checks i!=j, so we'll stick to that for now).
// 'j' will represent the index of the second number.
for (int j = 0; j < nums.size(); j++) { // The provided solution started j from i; let's adhere to that to illustrate its exact logic.
// Correction: The provided solution has `j = i`, let's use that.
// No, the solution actually has `for(int j = i; j < nums.size(); j++)`.
// I will adapt the comments to fit this provided code, as requested.
// Check if the sum of the current pair of numbers equals the target
// AND ensure that we are not using the same element twice (i.e., their indices must be different).
if ((nums[i] + nums[j] == target) && (i != j)) {
// If both conditions are met, we've found our unique pair!
// Return their indices as a vector.
return {i, j};
}
}
}
// This line should technically never be reached because the problem guarantees
// that exactly one solution always exists. It's good practice for function completion.
return {};
}
};
Self-correction based on the provided solution:
The provided solution is for(int j = i; j < nums.size(); j++). This is a slight optimization because it avoids redundant checks (e.g., checking (nums[0], nums[1]) and then later (nums[1], nums[0])). The i != j check inside the if statement correctly handles the "cannot use the same element twice" rule. I will adjust the code block to reflect the exact provided solution and refine the comments.
class Solution {
public:
std::vector<int> twoSum(std::vector<int>& nums, int target) {
// Outer loop: 'i' represents the index of the first number we pick.
// We iterate through each element in the 'nums' array.
for (int i = 0; i < nums.size(); i++) {
// Inner loop: 'j' represents the index of the second number we pick.
// We start 'j' from 'i'. This ensures we check all pairs without redundant checks
// like (nums[0], nums[1]) and then (nums[1], nums[0]), as the latter will be covered.
for (int j = i; j < nums.size(); j++) {
// Check if the sum of the numbers at indices 'i' and 'j' equals the target.
// ALSO, ensure that we are not using the same element twice.
// The condition `i != j` is crucial because `j` starts from `i`,
// so `i == j` would mean comparing 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, this return statement should theoretically
// never be reached, as there is always exactly one solution.
// It's a placeholder for compilation purposes.
return {};
}
};
This is a more accurate representation and explanation of the provided solution.
Time & Space Complexity Analysis ⏱️🚀
Understanding how efficient your code is, is a critical skill in competitive programming!
-
Time Complexity: O(n^2)
-
nrepresents the number of elements in ournumsarray. - Our solution uses nested loops. The outer loop runs
ntimes. For each iteration of the outer loop, the inner loop runs roughlyntimes (specifically,n-itimes). - This means, in the worst case, we are performing approximately
n * noperations. This kind of performance is called quadratic time complexity, denoted asO(n^2). - The problem description actually gives you a hint for improvement: "Can you come up with an algorithm that is less than O(n^2) time complexity?" Our current solution isn't that, but it's a great starting point!
-
-
Space Complexity: O(1)
- We are only using a few extra variables (
i,j,target,nums.size()) which take up a constant amount of memory, regardless of how large thenumsarray gets. - We are not creating any new data structures that grow significantly with the input size. This is called constant space complexity, denoted as
O(1).
- We are only using a few extra variables (
Key Takeaways ✨
- Start Simple (Brute Force): Don't be afraid to implement the most straightforward solution first. It helps you understand the problem thoroughly and provides a baseline.
- Nested Loops for Pairs: When you need to check every possible pair in an array, nested loops are a common pattern.
- Read Constraints Carefully: Details like "cannot use the same element twice" (
i != j) and "exactly one solution" are crucial for correct and efficient problem-solving. - Complexity Matters:
O(n^2)is often acceptable for small inputs, but for larger inputs, you'll need more optimized approaches. The "Two Sum" problem has a famousO(n)solution using hash maps (dictionaries) – a fantastic next step once you master this basic approach!
That's it for our deep dive into LeetCode's Two Sum! You've just tackled your first (or refreshed your knowledge of) a fundamental problem. Keep practicing, keep learning, and happy coding!
Author: pratik_bandgar9009
Published: 2026-05-23 16:35:43
Top comments (0)