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.R
arr <- c(2, 7, 11, 4, 5)
target <- 9
seen <- new.env(hash = TRUE, parent = emptyenv())
first <- -1
second <- -1
i <- 1
while (i <= length(arr)) {
value <- arr[i]
need <- target - value
key <- as.character(need)
if (exists(key, envir = seen, inherits = FALSE)) {
first <- get(key, envir = seen)
second <- i - 1
break
}
assign(as.character(value), i - 1, envir = seen)
i <- i + 1
}
cat("[", first, ", ", second, "]\n", sep = "")
Complexity
- Time: O(n) average
- Space: O(n)
Implementation notes
arr <- c(2, 7, 11, 4, 5)creates the pinned numeric R vector.target <- 9is the scalar target for this run.seen <- new.env(hash = TRUE, parent = emptyenv())uses a hashed R environment as the lookup table.- R vector access is 1-based, so the scan starts with
i <- 1and readsvalue <- arr[i]. - The lesson still prints zero-based result indexes: both stored indexes and
returned indexes use
i - 1. need <- target - valuecomputes the complement.key <- as.character(need)converts the complement to a string key because environment bindings are named.exists(key, envir = seen, inherits = FALSE)checks only the current environment, not parent scopes.- On a hit,
get(key, envir = seen)retrieves the earlier zero-based index. - On a miss,
assign(as.character(value), i - 1, envir = seen)records the current value under a string key.
Replay steps
start: arr = [2, 7, 11, 4, 5], target = 9, seen = {}
R i=1, value=2: need 7, miss, record key "2" -> 0
R i=2, value=7: need 2, hit key "2", result [0, 1]
breakstops the loop after the hit, so11,4, and5are not scanned.cat("[", first, ", ", second, "]\n", sep = "")prints[0, 1]with no extra spaces beyond the literal comma-space.
execution replay
The checked-in replay follows the language-neutral state table for `array-two-sum-hash`.
cross-language comparison
This R DSA version keeps the same data and final output as every other DSA book in this wave.