LeetCopilot Logo
LeetCopilot
LeetCode Pattern/Two Pointers/When to Use Hash Map Instead of Two Pointers (Decision Framework)

When to Use Hash Map Instead of Two Pointers (Decision Framework)

LeetCopilot Team
Dec 9, 2025
10 min read
Two PointersHash MapDecision FrameworkTrade-offsInterview Strategy
Confused whether to use a hash map or two pointers for pair-finding problems? Learn the exact decision criteria, trade-offs, and when each approach wins.

You're solving a "find two numbers" problem. You know there are two approaches:

Approach 1: Two Pointers

python
left, right = 0, len(nums) - 1
while left < right:
    # ...

Approach 2: Hash Map

python
seen = {}
for num in nums:
    # ...

Which one should you use?

Choosing the wrong approach costs you time in interviews. Use two pointers on unsorted data? Wrong answer. Use a hash map when the array is sorted? You've wasted O(n) space unnecessarily.

This guide will give you a decision framework to choose the right approach in under 30 seconds, understand the trade-offs, and know when each technique wins.

TL;DR

Use Two Pointers when:

  • Array is sorted (or you can sort it)
  • You don't need original indices
  • You want O(1) space complexity
  • You're finding pairs/triplets in sorted context

Use Hash Map when:

  • Array is unsorted and you need original indices
  • Sorting would lose required information
  • O(n) space is acceptable
  • You need O(n) time (can't afford O(n log n) sorting)

The Core Trade-Off: Time vs Space vs Constraints

Two Pointers

  • Time: O(n) if sorted, O(n log n) if you sort first
  • Space: O(1)
  • Requirement: Sorted array (or sortable)
  • Returns: Can return indices or values

Hash Map

  • Time: O(n)
  • Space: O(n)
  • Requirement: No sorting needed
  • Returns: Original indices preserved

The Decision Framework

When you see a pair-finding problem, ask these questions in order:

Question 1: Is the array already sorted?

YES → Two Pointers

python
# LeetCode #167: Two Sum II (Input Array Is Sorted)
def twoSum(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        current_sum = nums[left] + nums[right]
        if current_sum == target:
            return [left + 1, right + 1]  # 1-indexed
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    return []

NO → Go to Question 2

Question 2: Do you need the original indices?

YES → Hash Map

python
# LeetCode #1: Two Sum (need original indices)
def twoSum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

NO → Go to Question 3

Question 3: Can you afford O(n log n) time to sort?

YES → Sort first, then Two Pointers

python
# LeetCode #15: 3Sum (values only, no indices needed)
def threeSum(nums):
    nums.sort()  # O(n log n)
    result = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i-1]:
            continue
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total == 0:
                result.append([nums[i], nums[left], nums[right]])
                # Skip duplicates...
                left += 1
                right -= 1
            elif total < 0:
                left += 1
            else:
                right -= 1
    return result

NO → Hash Map

Question 4: What are the space constraints?

Must be O(1) space → Sort + Two Pointers

O(n) space is fine → Hash Map (simpler, no sorting)

Visual Decision Tree

code
Find pairs/triplets problem
         |
         v
   Is array sorted?
    /           \
  YES            NO
   |              |
   v              v
Two Pointers   Need original indices?
 O(n), O(1)     /              \
              YES               NO
               |                 |
               v                 v
          Hash Map        Can afford O(n log n)?
          O(n), O(n)       /              \
                         YES               NO
                          |                 |
                          v                 v
                   Sort + Two Pointers   Hash Map
                   O(n log n), O(1)    O(n), O(n)

Side-by-Side Comparison

CriterionTwo PointersHash Map
Time ComplexityO(n) sorted, O(n log n) unsortedO(n)
Space ComplexityO(1)O(n)
Requires SortedYesNo
Preserves IndicesNo (unless tracked)Yes
Handles DuplicatesEasily (skip logic)Requires care
Extends to 3Sum/4SumYes (nested loops)Complex
Code SimplicityMediumSimple

Real Interview Scenarios

Scenario 1: Two Sum (LeetCode #1)

Problem: Given an unsorted array, return indices of two numbers that sum to target.

Analysis:

  • Array: Unsorted ✗
  • Need indices: Yes ✓
  • Space constraint: None

Decision: Hash Map

javascript
function twoSum(nums, target) {
    const map = new Map();
    for (let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        if (map.has(complement)) {
            return [map.get(complement), i];
        }
        map.set(nums[i], i);
    }
    return [];
}

Why not Two Pointers? Sorting would lose original indices.

Scenario 2: Two Sum II (LeetCode #167)

Problem: Given a sorted array, return 1-indexed positions of two numbers that sum to target.

Analysis:

  • Array: Sorted ✓
  • Need indices: Yes (but 1-indexed, not original)
  • Space constraint: None

Decision: Two Pointers

javascript
function twoSum(numbers, target) {
    let left = 0, right = numbers.length - 1;
    while (left < right) {
        const sum = numbers[left] + numbers[right];
        if (sum === target) {
            return [left + 1, right + 1];
        }
        if (sum < target) left++;
        else right--;
    }
    return [];
}

Why not Hash Map? Sorted array allows O(1) space solution.

Scenario 3: 3Sum (LeetCode #15)

Problem: Find all unique triplets that sum to zero.

Analysis:

  • Array: Unsorted
  • Need indices: No (just values)
  • Need to avoid duplicates: Yes
  • Extends to multiple elements: Yes

Decision: Sort + Two Pointers

python
def threeSum(nums):
    nums.sort()
    result = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i-1]:
            continue
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total == 0:
                result.append([nums[i], nums[left], nums[right]])
                while left < right and nums[left] == nums[left+1]:
                    left += 1
                while left < right and nums[right] == nums[right-1]:
                    right -= 1
                left += 1
                right -= 1
            elif total < 0:
                left += 1
            else:
                right -= 1
    return result

Why not Hash Map? Two pointers extends naturally to 3Sum/4Sum. Hash map approach is more complex.

Scenario 4: Two Sum with Space Constraint

Problem: Two Sum, but you must use O(1) space.

Analysis:

  • Array: Unsorted
  • Need indices: Yes
  • Space constraint: O(1) required

Decision: Sort + Track Original Indices

python
def twoSum(nums, target):
    # Create pairs of (value, original_index)
    indexed = [(num, i) for i, num in enumerate(nums)]
    indexed.sort()  # Sort by value
    
    left, right = 0, len(indexed) - 1
    while left < right:
        current_sum = indexed[left][0] + indexed[right][0]
        if current_sum == target:
            return [indexed[left][1], indexed[right][1]]
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    return []

Trade-off: O(n log n) time, but O(1) extra space (sorting in-place).

When Hash Map Wins

Advantage 1: No Sorting Required

If the problem explicitly states "do not modify the input" or sorting is not allowed, hash map is your only choice.

Advantage 2: Faster for Single Pass

Hash map is O(n) time, while sort + two pointers is O(n log n). For very large arrays, this matters.

Advantage 3: Preserves Original Indices

When you need to return original positions, hash map naturally preserves them.

Advantage 4: Works on Unsorted Data

No preprocessing needed—just iterate and check.

When Two Pointers Wins

Advantage 1: O(1) Space

No extra data structure needed. Just two integer variables.

Advantage 2: Extends to k-Sum Problems

3Sum, 4Sum, etc. are natural extensions of the two-pointer pattern.

python
# 4Sum: Fix two elements, two pointers on rest
for i in range(len(nums) - 3):
    for j in range(i + 1, len(nums) - 2):
        left, right = j + 1, len(nums) - 1
        # ... two pointers logic

Advantage 3: Handles Duplicates Elegantly

Skipping duplicates is straightforward with sorted data:

python
while left < right and nums[left] == nums[left + 1]:
    left += 1

Advantage 4: Intuitive for Sorted Data

If the array is already sorted, two pointers is the natural choice.

Common Mistakes

Mistake 1: Using Two Pointers on Unsorted Data

python
# WRONG: nums is unsorted
def twoSum(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        # This won't work correctly!

Fix: Sort first or use hash map.

Mistake 2: Using Hash Map When Sorted

python
# INEFFICIENT: nums is already sorted
def twoSum(nums, target):
    seen = {}  # Wastes O(n) space
    for i, num in enumerate(nums):
        # ...

Fix: Use two pointers for O(1) space.

Mistake 3: Sorting When Indices Are Required

python
# WRONG: Sorting loses original indices
def twoSum(nums, target):
    nums.sort()  # Original indices lost!
    # ...

Fix: Use hash map or track indices during sorting.

Code Templates

Template 1: Hash Map (Unsorted, Need Indices)

python
def twoSum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

Template 2: Two Pointers (Sorted)

python
def twoSum(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        current_sum = nums[left] + nums[right]
        if current_sum == target:
            return [left, right]
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    return []

Template 3: Sort + Two Pointers (Unsorted, No Indices Needed)

python
def twoSum(nums, target):
    nums.sort()
    left, right = 0, len(nums) - 1
    while left < right:
        current_sum = nums[left] + nums[right]
        if current_sum == target:
            return [nums[left], nums[right]]  # Values, not indices
        elif current_sum < target:
            left += 1
        else:
            right -= 1
    return []

Practice Strategy

To master the decision:

  1. Solve Two Sum (#1) with hash map
  2. Solve Two Sum II (#167) with two pointers
  3. Compare both solutions side-by-side
  4. Solve 3Sum (#15) to see when sorting enables two pointers
  5. Create a decision flowchart and practice identifying which to use
  6. Use LeetCopilot's pattern recognition to train on mixed problems

FAQ

Q: Can I always use a hash map instead of two pointers?

A: Technically yes, but you'll waste space and might fail space-constrained problems. Also, two pointers extends better to 3Sum/4Sum.

Q: When should I sort the array first?

A: When you don't need original indices and either (1) the array is unsorted but you want to use two pointers, or (2) you need to handle duplicates easily.

Q: What if the problem says "O(1) space"?

A: You must use two pointers. Sort the array first if needed (sorting is often allowed even with O(1) space constraint, as it's in-place).

Q: Which is faster: hash map or two pointers?

A: Hash map is O(n), two pointers on sorted array is O(n), but sorting first is O(n log n). So hash map is faster if the array is unsorted. But two pointers uses less space.

Q: Can I use both techniques together?

A: Rarely. Usually you pick one. But in some complex problems, you might use a hash map for one part and two pointers for another.

Conclusion

The choice between hash map and two pointers comes down to three factors:

  1. Is the array sorted? (or can you sort it?)
  2. Do you need original indices?
  3. What are the space constraints?

Quick decision rules:

  • Sorted array → Two Pointers
  • Unsorted + need indices → Hash Map
  • Unsorted + no indices + O(1) space → Sort + Two Pointers
  • Unsorted + no indices + O(n) space OK → Hash Map (simpler)

Remember:

  • Two Pointers: O(n) time (if sorted), O(1) space, extends to k-Sum
  • Hash Map: O(n) time, O(n) space, preserves indices

Master this decision framework, and you'll choose the right approach instantly in interviews. For more on two pointers, see the complete guide and sorted arrays.

Next time you see a pair-finding problem, you'll know exactly which tool to reach for.

Want to Practice LeetCode Smarter?

LeetCopilot is a free browser extension that enhances your LeetCode practice with AI-powered hints, personalized study notes, and realistic mock interviews — all designed to accelerate your coding interview preparation.

Also compatible with Edge, Brave, and Opera

Related Tutorials