Find Non-Repeating Characters in a String

Asked atAmazonAtlassianCCognitree
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

You are given a string s. Your task is to find all characters that appear exactly once in the string and return them in the order they appear in the original string.

Return the result as a comma-separated string of characters. If no non-repeating characters exist, return an empty string.

**Input: **s = "google" Output: "l,e" Explanation: Characters 'l' and 'e' appear only once and are in order.

Input: s = "yahoo" **Output: **"y,a,h" Explanation: Characters 'y', 'a', 'h' appear only once in order.

**Input: **s = "leetcode" Output: "l,t,c,d" Explanation: These are the characters that appear only once and appear in this order.

  • 1 <= s.length <= 105
  • The string contains only lowercase English letters ('a' to 'z')

cpp

class Solution {
public:
    string findNonRepeatingCharacters(const string& s) {
        // Your code goes here
    }
};

java

class Solution {
    public String findNonRepeatingCharacters(String s) {
        // Your code goes here
    }
}

python

class Solution:
    def find_non_repeating_characters(self, s: str) -> str:
        # Your code goes here

javascript

class Solution {
    findNonRepeatingCharacters(s) {
        // Your code goes here
    }
}

csharp

class Solution
{
    public string FindNonRepeatingCharacters(string s)
    {
        // Your code goes here
    }
}

go

func FindNonRepeatingCharacters(s string) string {
}
Stuck? Show a way to structure it+
  1. 01Count every character in a first pass.
  2. 02Scan the original string again and collect characters whose count is one.
  3. 03Join the collected characters with commas without reordering them.
  4. 04Preserve encounter order by scanning the input again rather than the map.

Reference answer

Then expect these follow-ups

  • How would you return only the first non-repeating character in a stream?

    Tests: streaming design

  • How would Unicode grapheme clusters affect the implementation?

    Tests: text representation

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question