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 .…