Coding challenge – Unique characters in a String2 min read

Welcome to our first post in this category – Coding Challenge. We believe that each and every developer should code each and every day in order to stay in touch with the code. And this is one of the easiest ways to make your brain think, and work, and at the same time, you can code !!

So it is better to try out a couple of coding challenges once in a while to stay in shape. 😀 There are really multiple ways to solve the challenges and this solution is just one of them, the solutions are not tested in any coding platforms like leetcode, codechef etc. The idea is to give you a start with the solution and from there you can evolve and optimize the solution as per your requirement.

Today, we will start with the basic one, but look out for this space, you will definitely find some advanced challenges in the near future.

Question: Find if all the characters in the String are unique or not.

Break down:

  • Break down is simple, while looping over each and every character in the String, just use the HashMap data structure to identify whether the character is already on the map or not. (Map<Character, Boolean>)
package com.zingscoop.challenges.ArraysAndStrings;

import java.util.HashMap;
import java.util.Map;

public class UniqueCharacters {

    private static boolean isUniqueCharacters(String str) {
        Map<Character,Boolean> map = new HashMap<>();
        for (int i = 0; i < str.length(); i++) {
            if(str.codePointAt(i) <= 65535) {
                char ch = str.charAt(i);
                if(!Character.isWhitespace(ch) && map.put(ch, true) != null) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        
        String s = "ZingScoop";
        String s1 = "Zing";

        System.out.println("Is Unique Characters: " + UniqueCharacters.isUniqueCharacters(s));
        System.out.println("Is Unique Characters: " + UniqueCharacters.isUniqueCharacters(s1));

    }
    
}
Is Unique Characters: false
Is Unique Characters: true

This is one of the very basic coding challenges and the idea is to use the right data structure when needed. That’s all for this quick coding challenge.

All the above examples are available on github.

Stay subscribed. more to come in this space. Happy Scooping…