Arrays and Iteration
Two-Sum with Hash Lookup
Walk the array once, storing seen values in a lookup table. When the complement is already present, the result indices are known.
Algorithm
execution replay
The checked-in replay follows the language-neutral state table for `array-two-sum-hash`.
cross-language comparison
This C# DSA version keeps the same data and final output as every other DSA book in this wave.
Basic Implementation
basic.cs
Replay: real traced execution (multi-file project)
using System;
using System.Collections.Generic;
class Program {
static void Main() {
int[] arr = new int[] { 2, 7, 11, 4, 5 };
int target = 9;
var seen = new Dictionary<int, int>();
int first = -1;
int second = -1;
for (int i = 0; i < arr.Length; i++) {
int value = arr[i];
int need = target - value;
if (seen.ContainsKey(need)) {
first = seen[need];
second = i;
break;
}
seen[value] = i;
}
Console.WriteLine($"[{first}, {second}]");
}
}
arr ← [2, 7, 11, 4, 5], target ← 9, seen ← {}
1using System;2using System.Collections.Generic;values this step[2, 7, 11, 4, 5]arr9target{}seenseen ← {2: 0}, hit ← no
12int value = arr[i];13int need = target - value;14if (seen.ContainsKey(need)) {values this step{} → {2: 0}seennohit0i2arr[i]7needhit ← yes, result ← [0, 1]
12int value = arr[i];13int need = target - value;14if (seen.ContainsKey(need)) {values this stepyeshit[0, 1]result1i7arr[i]2need{2: 0}seen
Complexity
- Time: O(n) average
- Space: O(n)
Implementation notes
- Keep the explicit control flow. Library shortcuts would hide the state changes this lesson is meant to replay.
Dictionary<int, int>stores the last seen index for each value; integer hashing gives average O(1) lookup, while collisions are handled inside the container. Assigningseen[value] = iintentionally overwrites duplicate values with the latest index.- The
int[]input is a managed reference array, soarr[i]reads are bounds-checked by the CLR whilearr.Lengthdrives the scan.