Skip to content
Go back

Leetcode Problem-Solving Notes (1)

Published:  at  08:00 AM

Two Sum is one of the most classic problems on Leetcode — and usually the first one people solve. Even though I’ve solved it before, I wanted to clearly articulate my thought process, so I decided to write it up. Let’s get started.

Two Sum

Problem Description

Given an array nums and an integer target, return the indices of the two elements that add up to target. The problem guarantees exactly one solution.

Approach

Solution 1

The first instinct is a brute-force approach using two nested loops — return immediately once a valid pair is found. Here’s the Java implementation:

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            int ans = nums[i] + nums[j];
            if (ans == target) return new int[]{i, j};
        }
    }
    return new int[]{-1, -1};
}

This works, but the time complexity is O(n²) — in the worst case we perform roughly n²/2 comparisons. Space complexity is O(1) since no extra data structures are used.

Solution 2

The optimal approach uses a HashMap to bring time complexity down from O(n²) to O(n). The idea: store each element’s value and index in the map. For each element, check whether its complement (target - nums[i]) already exists in the map. If it does, we’ve found the pair.

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();

    for (int i = 0; i < nums.length; i++) {
        if (!map.containsKey(target - nums[i])) {
            map.put(nums[i], i);
        } else {
            return new int[]{map.get(target - nums[i]), i};
        }
    }
    return new int[]{-1, -1};
}

Time complexity: O(n) — each element is visited once. Space complexity: O(n) — in the worst case, all n elements are stored in the map.

Summary

Two Sum is a simple problem, but it covers several important concepts:

That’s why it’s become one of the most iconic entry-level problems on Leetcode.

The key insight: instead of searching for two numbers, remember the numbers you’ve already seen and look for their “other half.” This pattern applies to many other problems as well.

Remove Duplicates from Sorted Array

Problem Description

Given a sorted array in ascending order, modify it in-place so that the first k elements are unique and ordered, then return k.

Approach

Solution 1

Use a single loop to scan the array while tracking a duplicates counter (initialized to 0). When the current element equals the previous one, it’s a duplicate — increment the counter. Shift each element left by the number of duplicates seen so far. The final length is nums.length - duplicates.

public int removeDuplicates(int[] nums) {
    int duplicates = 0;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] == nums[i - 1]) {
            duplicates++;
        }
        nums[i - duplicates] = nums[i];
    }
    return nums.length - duplicates;
}

Solution 2

A cleaner alternative using an explicit fast/slow pointer pattern. The slow pointer advances only when a new unique element is found.

public int removeDuplicates(int[] nums) {
    int slow = 1;
    for (int fast = 1; fast < nums.length; fast++) {
        if (nums[fast] != nums[fast - 1]) {
            nums[slow] = nums[fast];
            slow++;
        }
    }
    return slow;
}

Summary

Both solutions have O(n) time complexity and O(1) space complexity.

The core idea is the same: use a pointer to track the next valid write position. The difference is that Solution 1 uses the duplicate count as an offset, while Solution 2 uses explicit fast/slow pointers. In an interview setting, Solution 2 is more readable and is the recommended choice.

Best Time to Buy and Sell Stock

Problem Description

Given an array where each element represents a stock price, find the maximum profit you can achieve from a single buy-sell transaction.

Approach

Maximizing profit means finding the minimum price seen so far and tracking the largest difference between the current price and that minimum.

public int maxProfit(int[] prices) {
    int minPrice = Integer.MAX_VALUE;
    int maxProfit = 0;
    for (int price : prices) {
        minPrice = Math.min(minPrice, price);
        int profit = price - minPrice;
        maxProfit = Math.max(maxProfit, profit);
    }
    return maxProfit;
}

Summary

Time complexity: O(n). Space complexity: O(1).

The key insight: there’s no need to enumerate all buy-sell combinations. Just scan the array once, maintaining the current minimum price, and you’ll find the maximum profit in O(n).


Suggest Changes
Share this post on:

Next Post
Leetcode Problem-Solving Notes (2)