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
Basic Implementation
basic.sh
#!/usr/bin/env bash
set -euo pipefail
arr=(2 7 11 4 5)
target=9
declare -A seen=()
first=-1
second=-1
for ((i = 0; i < ${#arr[@]}; i++)); do
value=${arr[i]}
need=$((target - value))
if [[ -v seen[$need] ]]; then
first=${seen[$need]}
second=$i
break
fi
seen[$value]=$i
done
echo "[$first, $second]"
Complexity
- Time: O(n) average
- Space: O(n)
Implementation notes
arr=(2 7 11 4 5)andtarget=9are the pinned inputs.declare -A seen=()creates a Bash associative array that mapsvalue -> index.first=-1andsecond=-1are sentinel outputs until a pair is found.for ((i = 0; i < ${#arr[@]}; i++)); doscans zero-based indexes0through4.value=${arr[i]}reads the current value, andneed=$((target - value))uses Bash arithmetic expansion to compute the complement.if [[ -v seen[$need] ]]; thenchecks whether the associative-array key exists without reading an unset key underset -u.- On a hit,
first=${seen[$need]}andsecond=$icapture the pair, thenbreakstops after the first match. - On a miss,
seen[$value]=$irecords the current value and index.
Replay steps
i=0 value 2 need 7: miss, seen {2:0}
i=1 value 7 need 2: hit, result [0, 1]
echo "[$first, $second]"prints exactly[0, 1].
execution replay
The checked-in replay follows the language-neutral state table for `array-two-sum-hash`.
cross-language comparison
This Bash DSA version keeps the same data and final output as every other DSA book in this wave.