NOTE

First Non-Repeating Character in a Character Stream

Use a map to count character occurrences while preserving input order to find the first character that appears only once in a stream.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Implement a function that finds the first character that appears only once in a character stream. For example, after reading only the first two characters “go”, the first character that appears once is “g”. After reading the first six characters “google”, the first character that appears once is “l”.

2. Approach

  • Use a map for counting + a list to preserve order

3. Implementation

package main

var countMap = make(map[byte]int, 0)
var str = make([]byte, 0)

func Insert(ch byte) {
	countMap[ch]++
	str = append(str, ch)
}

func FirstAppearingOnce() byte {
	for _, s := range str {
		if countMap[s] == 1 {
			return s
		}
	}

	return '#'
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub