Program to find k-th Lexicographical String from all Happy Strings of length n in Java

A happy string is a string that:

  • consists only of letters of the set ['a', 'b', 'c'].
  • s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
class MainProgram{    private String getHappyString(int n, int k) {
char[] arr = {'a', 'b', 'c'};
String res="";
List<String> list=new ArrayList<>();
generatePerm(arr, n, res, list);
if(list.size() >= k)
return res;

private void generatePerm(char[] arr, int n, String res,
List<String> list){
if(n == 0){

for(int i=0; i<arr.length; i++){
if(res == "" || res.charAt(res.length()-1) != arr[i]){
String pre=res+arr[i];
generatePerm(arr, n-1, pre, list);
public static void main(String args[]){
System.out.println("Happy String: "+getHappyString(3,4));

Output: Happy String: acb

Hope it helps, enjoy coding!

Any improvement or suggestions are welcomed !



Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store