K'th Non-repeating Character in Python using List Comprehension and OrderedDict

In this article, we will learn how to find the K'th non-repeating character in a string using Python's List Comprehension and OrderedDict. This approach maintains the order of first occurrence while efficiently counting character frequencies.

Algorithm

The algorithm follows these steps:

1. Create an OrderedDict from the input string to maintain insertion order
2. Count the frequency of each character by iterating through the string
3. Extract all characters that appear exactly once using list comprehension
4. Return the (k-1)th element from the non-repeating characters list

Example

Let's implement the solution to find the K'th non-repeating character ?

from collections import OrderedDict

def kthNonRepeating(inp, k):
    # Create OrderedDict to maintain insertion order
    char_dict = OrderedDict.fromkeys(inp, 0)
    
    # Count frequency of each character
    for ch in inp:
        char_dict[ch] += 1
    
    # Extract characters that appear exactly once
    non_repeat_chars = [key for (key, value) in char_dict.items() if value == 1]
    
    # Return k-1 indexed character or error message
    if len(non_repeat_chars) < k:
        return 'No output - insufficient non-repeating characters'
    else:
        return non_repeat_chars[k-1]

# Test the function
inp = "tutorialspoint"
k = 3
result = kthNonRepeating(inp, k)
print(f"Input string: {inp}")
print(f"K = {k}")
print(f"K'th non-repeating character: {result}")
Input string: tutorialspoint
K = 3
K'th non-repeating character: a

How It Works

Let's trace through the example with string "tutorialspoint":

from collections import OrderedDict

inp = "tutorialspoint"

# Step 1: Create OrderedDict with character frequencies
char_dict = OrderedDict.fromkeys(inp, 0)
for ch in inp:
    char_dict[ch] += 1

print("Character frequencies:")
for key, value in char_dict.items():
    print(f"'{key}': {value}")

# Step 2: Find non-repeating characters
non_repeat_chars = [key for (key, value) in char_dict.items() if value == 1]
print(f"\nNon-repeating characters: {non_repeat_chars}")

# Step 3: Get 3rd non-repeating character
k = 3
print(f"3rd non-repeating character: {non_repeat_chars[k-1]}")
Character frequencies:
't': 4
'u': 1
'o': 2
'r': 1
'i': 2
'a': 1
'l': 1
's': 1
'p': 1
'n': 2

Non-repeating characters: ['u', 'r', 'a', 'l', 's', 'p']
3rd non-repeating character: a

Alternative Approach Using Counter

You can also use Counter from collections for a more concise solution ?

from collections import Counter

def kthNonRepeatingCounter(inp, k):
    # Count character frequencies
    char_count = Counter(inp)
    
    # Find non-repeating characters in order
    non_repeat_chars = [char for char in inp if char_count[char] == 1]
    
    # Remove duplicates while preserving order
    seen = set()
    unique_non_repeat = []
    for char in non_repeat_chars:
        if char not in seen:
            unique_non_repeat.append(char)
            seen.add(char)
    
    return unique_non_repeat[k-1] if len(unique_non_repeat) >= k else 'No output'

# Test the alternative approach
inp = "tutorialspoint"
k = 3
result = kthNonRepeatingCounter(inp, k)
print(f"Using Counter - K'th non-repeating character: {result}")
Using Counter - K'th non-repeating character: a

Key Points

OrderedDict maintains insertion order, ensuring we get non-repeating characters in the order they first appear. List comprehension provides an elegant way to filter characters with frequency 1.

Conclusion

Using OrderedDict with list comprehension provides an efficient solution to find the K'th non-repeating character. The OrderedDict maintains insertion order while list comprehension elegantly filters single-occurrence characters.

Updated on: 2026-03-25T06:20:28+05:30

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements