1

I have a string input by the user and an integer k. How do I get the lexicographically kth smallest character from the input string?

Here is what I have been trying

static Character find(int K, String s){
    SortedSet<Character> ss = new TreeSet<Character>();
    for(Character c : s.toCharArray()){
        ss.add(c);
    }
    Iterator it = ss.iterator();
    int i=0;
      while (it.hasNext()) {
         Object element = it.next();
         if(i==K-1)
             return (Character) element;

      }
      return null;
}
Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
g19
  • 99
  • 7

1 Answers1

1

Your code is OK, except for one thing: the handling of i variable. You should increment it at the end of the while loop in order to make it match K - 1.

There's also a more java8-friendly way of doing the same:

String str = "hello";
int k = 2;

Optional<Character> kth = 
    Stream.of(str.split(""))
        .map(c -> c.charAt(0))
        .sorted()
        .distinct()
        .skip(k - 1)
        .findFirst();

System.out.println(kth.isPresent() ? kth.get() : "k too big!"); // h

This code assumes that k is 1-based and that you're not taking duplicates into account to get the kth character.

Also, as pointed out in the comments, you shouldn't use a raw type for your Iterator. Consider changing it to Iterator<Character>, so you don't have to cast the value returned by it.next().

fps
  • 33,623
  • 8
  • 55
  • 110