Menu

1 / 2

Find First Non Repeating Character - Java Program With Time and Space Complexity

DEV Community·Tapas Pal·6 months ago
#z1NrzgBx
Reading 0:00
15s threshold

Problem Statement Given a string: "swiss" Find the first character that appears only once. Expected Output : w Because: s repeats w appears once and comes first

Enter fullscreen mode

Exit fullscreen mode

Solution:

Best Approach (Using LinkedHashMap)

We will use: LinkedHashMap

Why? Because:

Stores frequency count

Maintains insertion order

Approach-1

// Method to find the first non-repeating character public class FirstNonRepeatingCharacter { public static Character firstNonRepeating ( final String str ) { // Check if string is null or empty // If yes, return null because no character exists if ( str == null || str . isEmpty ()){ return null ; } // Create frequency array of size 256 // Each index represents an ASCII character // Example: freq['a'] stores count of 'a' int [] freq = new int [ 256 ]; // Convert string into char array and iterate each character for ( char ch : str .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.