We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • Hackerrank Home
  • Prepare
    NEW
  • Certify
  • Compete
  • Career Fair
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Strings
  4. Sherlock and the Valid String
  5. Discussions

Sherlock and the Valid String

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • supriyaramesh98
    2 months ago+ 0 comments

    JAVA 8 simple solution:

    public static String isValid(String s) 
        {
            Map<Character,Integer> map = new HashMap<>();
            for(Character c : s.toCharArray())
            {           
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
           List<Integer> list  = new ArrayList<>(map.values());
           
           Collections.sort(list);
           int min =list.get(0);
           int max= list.get(list.size() - 1);
           if(min == max)
            {
               return "YES";
            }
            int minCount = 0;
            int maxCount = 0;
    
            for(int val : list)
            {
                if(min == val)
                {
                    minCount++;
                }
                if(max == val)
                {
                    maxCount++;
                }
            }
            System.out.println("max:"+max+"\n min:"+min);
            System.out.println("maxCount:"+maxCount+"\n minCount:"+minCount);
            if(max - min > 1 )
            {
                if(minCount != 1)
                {
                    return "NO";
                }
            }
            return ((maxCount + minCount == list.size() ) && (maxCount < 2 || minCount <2 )  ? "YES": "NO"  );
        }
    
    0|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy