惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
Martin Fowler
Martin Fowler
MyScale Blog
MyScale Blog
The GitHub Blog
The GitHub Blog
I
InfoQ
A
About on SuperTechFans
GbyAI
GbyAI
宝玉的分享
宝玉的分享
爱范儿
爱范儿
博客园 - 【当耐特】
博客园 - 司徒正美
博客园 - 聂微东
P
Proofpoint News Feed
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
Last Week in AI
Last Week in AI
阮一峰的网络日志
阮一峰的网络日志
B
Blog RSS Feed
Jina AI
Jina AI
aimingoo的专栏
aimingoo的专栏
J
Java Code Geeks
博客园 - 叶小钗

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Two Sum — LeetCode #1 (Easy)
Shubham Gupt · 2026-05-17 · via DEV Community

TL;DR

Single-pass hash map lookup: store each number's index as you go, check for the complement before storing. O(n) time, O(n) space.

The Problem

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

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

The answer is indices 0 and 1 because nums[0] + nums[1] == 9. Note: return indices, not values.

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Exactly one valid answer exists.

Naive Approach

Fix one number, scan every number after it for the complement. Repeat for each starting index.

class Solution:
    def twoSum(self, nums: list[int], target: int) -> list[int]:
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]

Enter fullscreen mode Exit fullscreen mode

O(n²) time, O(1) space — ~50 million pair checks on a 10,000-element array.

Key Insight

At every index i, you already know the complement you need: target - nums[i]. The only question is whether that value appeared earlier. Instead of scanning backwards, keep a hash map that answers "have I seen value v?" in O(1).

Two things to get right: use the value as the key and the index as the value (you look up by value, you want to retrieve the index); and check the map before inserting the current number, so a value can't match itself.

Optimal Solution

One pass. For each element, compute need = target - x. If need is already in seen, you're done. Otherwise, record x → i and continue.

class Solution:
    def twoSum(self, nums: list[int], target: int) -> list[int]:
        seen = {}
        for i, x in enumerate(nums):
            need = target - x
            if need in seen:
                return [seen[need], i]
            seen[x] = i

Enter fullscreen mode Exit fullscreen mode

Step-by-step on [2, 7, 11, 15], target 9:

  1. i=0, x=2need=7. seen={}, not found. Store seen[2]=0.
  2. i=1, x=7need=2. seen={2:0}, found. Return [seen[2], 1][0, 1].

The loop never reaches indices 2 or 3.

Complexity

Approach Time Space
Naive (nested loops) O(n²) O(1)
Hash map (one pass) O(n) O(n)

Pattern Recognition

This is the complement lookup pattern: when a problem asks for a pair satisfying some condition, storing what you've seen in a hash map turns a second scan into a O(1) lookup. You'll find the same structure in 3Sum (reduce to Two Sum), subarray sum equals k, and any problem where "what do I need to complete this?" has a clear formula.

In Interviews

The brute force buys you nothing here — interviewers expect the hash map solution immediately. What they're actually watching for: correct key/value orientation in the map, and the check-before-insert rule (if seen[x] = i runs before the lookup, x + x == target would return [i, i] — wrong).

Common follow-ups:

  • What if multiple valid pairs exist — return all of them? Collect results instead of returning early; decide whether to deduplicate.
  • What if the array is sorted? Two-pointer from both ends achieves O(n) time with O(1) space — no hash map needed.

📺 Watch the full walkthrough on YouTube: https://youtu.be/4JUNrRN16gM