Find the first input value whose final frequency is one.

Algorithm

Canonical input [3, 5, 2, 5, 3, 8, 2] prints 8. The replay uses the same input in every language, so this Swift DSA implementation can be compared directly with the rest of the DSA track.

Basic Implementation

basic.swift
let arr = [3, 5, 2, 5, 3, 8, 2]
var count: [Int: Int] = [:]
for value in arr {
    count[value, default: 0] += 1
}
for value in arr {
    if count[value] == 1 {
        print(value)
        break
    }
}

Complexity

  • Time: O(n) average
  • Space: O(k) for k distinct values

Implementation notes

  • This checked source uses integer input, not String/Character iteration: let arr = [3, 5, 2, 5, 3, 8, 2].
  • var count: [Int: Int] = [:] is the mutable Swift dictionary used as the frequency table.
  • The first pass iterates for value in arr and updates counts with count[value, default: 0] += 1, so missing keys start from 0 before the increment.
  • The trace records logical dictionary states, ending the count pass at {3: 2, 5: 2, 2: 2, 8: 1}; it does not expose bucket order or collision behavior.
  • The second pass scans arr again in input order and checks count[value] == 1 through Swift dictionary subscript lookup.
  • Values 3, 5, 2, 5, and 3 are traced as found no with frequency 2; value 8 at index 5 has frequency 1 and becomes the result.
  • print(value) writes the first non-repeating integer directly, so the exact stdout is 8.
two-pass lookup The first pass builds a frequency table. The second pass keeps the original order and stops at the first value with frequency one.