[Toggle Comments]
package main // file: impl-003.go // Single pass using a map. // We can do lookup and hash map creation in one go. // // time: O(n); space: O(n). func onePassHashTable(nums []int, target int) []int { // Map lookup is amortized constant time. indexes := make(map[int]int, len(nums)) for i, n := range nums { complement := target - n j, found := indexes[complement] if !found { // Not found. Expand the hash map. indexes[n] = i continue } // Found a match. return []int{i, j} } // No match found. // This should not happen as per our problem definition. return []int{-1, -1} } /* * \ * \\, * \\\,^,.,,. Zero to Hero * ,;7~((\))`;;,, <zerotohero.dev> * ,(@') ;)`))\;;', stay up to date, be curious: learn * ) . ),(( ))\;, * /;`,,/7),)) )) )\,, * (& )` (,((,((;( ))\, */