DEV Community

Cover image for How to Solve Your First LeetCode Problem: A Beginner's Guide
Felipe Castillo
Felipe Castillo

Posted on • Originally published at blog.opencodex.app

How to Solve Your First LeetCode Problem: A Beginner's Guide

How to Solve Your First LeetCode Problem: A Beginner's Guide

LeetCode has become the favorite playground for developers preparing for technical interviews. With over 3,500 problems ranging from "easy" to "hard," it's easy to feel overwhelmed before you even write your first line of code.

If you've ever opened LeetCode, stared at a problem for 30 minutes, and closed the tab in frustration, you're not alone. This guide exists because every developer who now aced their coding interview was once exactly where you are now.

We'll solve a real LeetCode problem together, step by step. By the end, you'll have a repeatable system for tackling any new problem.


Índice


Why LeetCode Matters

LeetCode isn't just about solving puzzles. It's about developing algorithmic thinking, the ability to break down complex problems into manageable pieces.

What LeetCode Actually Tests

  • Problem decomposition: Can you understand what the problem is asking?
  • Pattern recognition: Have you seen similar problems before?
  • Code implementation: Can you translate your idea into working code?
  • Optimization: Can you improve your initial solution?

Real-World Benefits

Beyond interviews, LeetCode helps you:

  1. Think like a programmer: You learn to approach problems systematically
  2. Understand data structures deeply: Implementation teaches more than reading
  3. Build confidence: Solving hard problems feels rewarding
  4. Join a community: Millions of developers share solutions and discuss approaches

Before You Start: The Right Mindset

Before diving into problems, set realistic expectations:

The 30-Minute Rule

Never stare at a problem for more than 30 minutes without help. If you're stuck:

  1. Re-read the problem description
  2. Try manually solving with examples
  3. Check hints (LeetCode provides them)
  4. Look at similar problems tagged with the same concepts

Easy Doesn't Mean Easy

LeetCode's "Easy" problems are called Easy because their solution is short, not because they're trivial. Many Easy problems still require insight that comes from practice.

You Will Fail

Every expert has solved hundreds of problems wrong before finding the right approach. Failure is part of the process, not a sign you don't belong.


Understanding the Problem: Two Sum

We'll solve LeetCode #1: Two Sum, the classic introductory problem that every developer encounters.

The Problem

Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example:

Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9
Enter fullscreen mode Exit fullscreen mode

This problem has been solved by over 1 million users on LeetCode. Let's solve it together.


Step 1: Read and Break Down the Problem

Before writing any code, answer these questions:

Questions to Ask Yourself

  1. What are the inputs? → An array of integers, a target integer
  2. What are the outputs? → Indices of two numbers (array order doesn't matter)
  3. What are the constraints? → We need to find exactly one solution, can't reuse the same element
  4. What should I return if no solution exists? → The problem guarantees exactly one solution exists

Write Down What You Understand

Input:  nums = [2, 7, 11, 15], target = 9
Output: [0, 1]

We need: nums[i] + nums[j] = target, where i ≠ j
Enter fullscreen mode Exit fullscreen mode

Step 2: Think Through Examples

Manually solve a few examples to build intuition.

Example 1

nums = [2, 7, 11, 15], target = 9
2 + 7 = 9 ✓ → indices [0, 1]
Enter fullscreen mode Exit fullscreen mode

Example 2

nums = [3, 2, 4], target = 6
3 + 2 = 5 ✗
3 + 4 = 7 ✗
2 + 4 = 6 ✓ → indices [1, 2]
Enter fullscreen mode Exit fullscreen mode

Example 3

nums = [3, 3], target = 6
3 + 3 = 6 ✓ → indices [0, 1]
Enter fullscreen mode Exit fullscreen mode

Step 3: Identify the Data Structure

This is where pattern recognition kicks in.

The Naive Approach (O(n²))

The brute force solution checks every pair:

def two_sum(nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n²) - we check every pair
Space Complexity: O(1) - no extra space needed

This works, but LeetCode will likely time out on large inputs. We can do better.


The Optimal Approach (O(n))

Key Insight: For each number x, we need to find target - x.

Instead of looking backward (checking all previous numbers), we can look forward using a Hash Map:

def two_sum(nums, target):
    hashmap = {}  # value -> index

    for i, num in enumerate(nums):
        complement = target - num
        if complement in hashmap:
            return [hashmap[complement], i]
        hashmap[num] = i

    return []
Enter fullscreen mode Exit fullscreen mode

How it works:

  1. For each number, calculate what we need to reach the target
  2. If that complement already exists in our map, we found our pair
  3. Otherwise, store this number and its index for future lookups

Time Complexity: O(n) - single pass
Space Complexity: O(n) - storing numbers in the map


Step 4: Write the Solution

Here's the complete solution in Python:

from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}  # Maps number -> index

        for i, num in enumerate(nums):
            complement = target - num

            if complement in hashmap:
                return [hashmap[complement], i]

            hashmap[num] = i

        return []  # No solution found (shouldn't happen per problem constraints)
Enter fullscreen mode Exit fullscreen mode

Alternative Solutions

JavaScript:

var twoSum = function (nums, target) {
    const hashmap = new Map()

    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i]

        if (hashmap.has(complement)) {
            return [hashmap.get(complement), i]
        }

        hashmap.set(nums[i], i)
    }

    return []
}
Enter fullscreen mode Exit fullscreen mode

C++:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> hashmap;

        for (int i = 0; i < nums.size(); i++) {
            int complement = target - nums[i];

            if (hashmap.count(complement)) {
                return {hashmap[complement], i};
            }

            hashmap[nums[i]] = i;
        }

        return {};
    }
};
Enter fullscreen mode Exit fullscreen mode

Step 5: Test Your Solution

LeetCode provides test cases automatically, but you should verify your solution manually.

Test Cases to Try

# Test 1: Basic case
print(two_sum([2, 7, 11, 15], 9))  # Expected: [0, 1]

# Test 2: Mid-array solution
print(two_sum([3, 2, 4], 6))  # Expected: [1, 2]

# Test 3: Duplicate values
print(two_sum([3, 3], 6))  # Expected: [0, 1]

# Test 4: Negative numbers
print(two_sum([-1, -2, -3, -4, -5], -8))  # Expected: [2, 4]
Enter fullscreen mode Exit fullscreen mode

Common Mistakes to Avoid

  1. Forgetting to check the complement before adding - Always check, then add
  2. Using the same index twice - Our approach naturally avoids this
  3. Not handling edge cases - Negative numbers, zeros, large arrays

Common Patterns to Memorize

LeetCode problems often reuse these fundamental patterns:

1. Two Pointers

# Use when: You need to find pairs in a sorted array
def two_pointer_example(arr, target):
    left, right = 0, len(arr) - 1
    while left < right:
        current = arr[left] + arr[right]
        if current == target:
            return [left, right]
        elif current < target:
            left += 1
        else:
            right -= 1
Enter fullscreen mode Exit fullscreen mode

2. Sliding Window

# Use when: Finding subarrays/substrings with specific properties
def sliding_window_example(arr, k):
    window_sum = sum(arr[:k])
    max_sum = window_sum

    for i in range(k, len(arr)):
        window_sum += arr[i] - arr[i - k]
        max_sum = max(max_sum, window_sum)

    return max_sum
Enter fullscreen mode Exit fullscreen mode

3. Hash Map for Lookups

# Use when: You need O(1) lookups for previous elements
def hashmap_example(nums, target):
    hashmap = {}
    for i, num in enumerate(nums):
        if target - num in hashmap:
            return [hashmap[target - num], i]
        hashmap[num] = i
    return []
Enter fullscreen mode Exit fullscreen mode

Resources to Keep Learning

Practice Platforms

Platform Best For Difficulty Range
LeetCode Interview prep, curated problems Easy → Hard
NeetCode Structured learning, video solutions Easy → Medium
Codeforces Competitive programming, speed Medium → Hard
HackerRank Fundamentals, certificates Easy → Medium

Study Plans

  1. NeetCode 150: Curated list of 150 essential problems
  2. LeetCode Top 100 Liked: Problems the community loves
  3. Grind 75: 75 problems optimized for interview prep

YouTube Channels

  • NeetCode: High-quality video explanations
  • Take U Forward: Systematic approach to problems
  • BackToBack SWE: Detailed visual explanations

Conclusion

Solving your first LeetCode problem is a milestone. What felt impossible becomes manageable once you have a systematic approach.

What We Learned

  1. Understand the problem before writing code
  2. Work through examples manually first
  3. Identify patterns you've seen before
  4. Start simple (brute force), then optimize
  5. Use the right data structure for fast lookups

Your Next Steps

  • Practice: Solve 1-2 Easy problems daily for the first week
  • Review: After solving, read other solutions to learn alternatives
  • Time yourself: Eventually aim for 15-20 minutes per Easy problem
  • Build habits: Consistency matters more than intensity

The Truth About LeetCode

You don't need to solve 1,000 problems to ace your interview. Most engineers who pass interviews have solved 100-300 problems with genuine understanding, not memorization.

The difference between those who succeed and those who give up isn't intelligence, it's persistence and methodical practice.

If you found this guide helpful, share it with fellow developers starting their LeetCode journey. See you in the next post!


Ready for more? Check out our guide on Data Structures Every Developer Must Know to build the foundation for tackling harder problems.

Top comments (0)