question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
combinations | Backtracking and recursion || c++ || easy Implementation | backtracking-and-recursion-c-easy-implem-se2i | Intuition\n Describe your first thoughts on how to solve this problem. \nIntution is basically picking number or notpicking that number.\n\n# Approach\n Describ | M_S_L | NORMAL | 2023-08-01T08:56:55.836443+00:00 | 2023-08-01T08:56:55.836478+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntution is basically picking number or notpicking that number.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis method uses a binary tree-like recursion structure where, at each step, it either includes the current num in the combination or skips it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(2^n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(recursion stack space)\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>>res;\n void f(int num,int total,int k,vector<int>&ans){\n if(num==total+1){\n if(ans.size()==k)\n res.push_back(ans);\n return;\n }\n\n ans.push_back(num);\n f(num+1,total,k,ans);\n ans.pop_back();\n f(num+1,total,k,ans);\n }\n vector<vector<int>> combine(int n, int k) {\n vector<int>ans;\n f(1,n,k,ans);\n return res;\n }\n};\n``` | 5 | 0 | ['Backtracking', 'Recursion', 'C++'] | 0 |
combinations | Backtracking Solution | C++ | backtracking-solution-c-by-ayumsh-a5ov | Code\n\nclass Solution {\npublic:\n void backtrack(vector<vector<int>> &ans,vector<int> &temp,int ind, int n, int k)\n { \n if(k==0)\n {\n | ayumsh | NORMAL | 2023-08-01T07:07:39.482172+00:00 | 2023-08-01T07:08:12.816472+00:00 | 841 | false | # Code\n```\nclass Solution {\npublic:\n void backtrack(vector<vector<int>> &ans,vector<int> &temp,int ind, int n, int k)\n { \n if(k==0)\n {\n ans.push_back(temp);\n return;\n }\n for(int i=ind;i<=n-k+1;i++) \n {\n temp.push_back(i);\n backtrack(ans,temp,i+1,n,k-1);\n temp.pop_back();\n }\n }\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> temp;\n backtrack(ans,temp,1,n,k);\n return ans;\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
combinations | Beats 100% + Video | Java C++ Python | beats-100-video-java-c-python-by-jeevank-pet6 | \n\n\nclass Solution {\n List<List<Integer>> ans;\n public List<List<Integer>> combine(int n, int k) {\n ans = new ArrayList<>();\n helper(1 | jeevankumar159 | NORMAL | 2023-08-01T03:02:01.843938+00:00 | 2023-08-01T03:02:01.843968+00:00 | 1,227 | false | <iframe width="560" height="315" src="https://www.youtube.com/embed/DcUkm8CPeaY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n List<List<Integer>> ans;\n public List<List<Integer>> combine(int n, int k) {\n ans = new ArrayList<>();\n helper(1,n,k,new ArrayList<>());\n return ans;\n }\n \n public void helper(int start, int n, int k, List<Integer>sub){\n if(k==0) {\n ans.add(new ArrayList<>(sub));\n return;\n }\n for(int i = start;i<=n-k+1;i++){\n sub.add(i);\n helper(i+1,n,k-1, sub);\n sub.remove(sub.size()-1);\n }\n }\n}\n```\n\n```\nclass Solution {\npublic:\n vector<vector<int>> ans;\n vector<vector<int>> combine(int n, int k) {\n ans.clear();\n vector<int> sub;\n helper(1, n, k, sub);\n return ans;\n }\n\n void helper(int start, int n, int k, vector<int>& sub) {\n if (k == 0) {\n ans.push_back(sub);\n return;\n }\n for (int i = start; i <= n - k + 1; i++) {\n sub.push_back(i);\n helper(i + 1, n, k - 1, sub);\n sub.pop_back();\n }\n }\n};\n\n```\n\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n ans = []\n self.helper(1, n, k, [], ans)\n return ans\n \n def helper(self, start, n, k, sub, ans):\n if k == 0:\n ans.append(sub[:])\n return\n for i in range(start, n - k + 2):\n sub.append(i)\n self.helper(i + 1, n, k - 1, sub, ans)\n sub.pop()\n\n``` | 5 | 1 | ['C', 'Python', 'Java'] | 0 |
combinations | Easy C++ Solution | easy-c-solution-by-2005115-2qmv | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nRecursive Backtracking:\n\nThe function combine calls the recursive funct | 2005115 | NORMAL | 2023-07-26T08:54:43.722144+00:00 | 2023-07-26T08:54:43.722164+00:00 | 532 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nRecursive Backtracking:\n\nThe function combine calls the recursive function solve to find all possible combinations of k numbers from the set [1, 2, ..., n].\nThe solve function uses backtracking to generate all possible subsets of size k by making decisions to include or exclude elements from the set.\nThe base case of the recursion is when the size of the subsets vector becomes equal to k. In this case, it means that k elements have been selected, and the current subsets vector is a valid combination. The subsets vector is added to the ans vector of combinations.\nBacktracking Algorithm:\n\nThe function starts with an empty vector subsets.\nFor each index i in the range [begin, end], it includes the element i in the current subsets vector and recursively calls solve with i+1 as the new begin index. This decision represents including the element i in the combination.\nAfter the recursive call, the element i is removed (backtracked) from the subsets vector to explore other combinations.\nMain Function:\n\nThe combine function initializes an empty vector subsets and starts the recursive process by calling solve with begin = 1 and end = n.\nThe function solve generates all valid combinations of k elements from the set [1, 2, ..., n] and stores them in the ans vector.\nOutput:\n\nThe combine function returns the 2D vector ans, which contains all possible combinations of k numbers from the set [1, 2, ..., n].\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(n!/(-k)!k!)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n*k)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nvector<vector<int>>ans;\n\nvoid solve(int begin, int end, int k,vector<int>subsets)\n{\n if(subsets.size()==k)\n {\n return ans.push_back(subsets);\n }\n for(int i = begin ; i<=end ; i++)\n {\n subsets.push_back(i);\n solve(i+1,end,k,subsets);\n subsets.pop_back();\n }\n\n}\n vector<vector<int>> combine(int n, int k) \n {\n vector<int>subsets;\n solve(1,n,k,subsets);\n return ans;\n }\n};\n``` | 5 | 0 | ['Backtracking', 'Recursion', 'C++'] | 0 |
combinations | Fast quick backtracking method | fast-quick-backtracking-method-by-haresh-axhm | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nBACK TRACKING\n\n# Comp | haresh412 | NORMAL | 2023-05-24T16:10:50.526119+00:00 | 2023-05-24T16:10:50.526153+00:00 | 816 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBACK TRACKING\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n!)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> ans;\n void help(vector<int> output,int i,int g,int j,int n){\n if(output.size()==g){\n ans.push_back(output);\n return;\n }\n for(int k=n+1;k<=i;k++){\n output.push_back(k);\n help(output,i,g,j+1,k);\n output.pop_back();\n }\n\n }\n vector<vector<int>> combine(int n, int k) {\n vector<int>output;\n help(output,n,k,0,0);\n return ans;\n }\n};\n``` | 5 | 0 | ['Backtracking', 'Depth-First Search', 'C++'] | 1 |
combinations | [C++] | 2 Different Approaches | Easy Explanation | Clean Code | c-2-different-approaches-easy-explanatio-dcjm | \n# Generate All Possible Subset\n Describe your approach to solving the problem. \nThe approach is to find out all the possible subset and take only those whic | _horiZon_OP | NORMAL | 2023-02-17T18:53:02.523035+00:00 | 2023-02-17T18:53:51.334412+00:00 | 2,217 | false | \n# Generate All Possible Subset\n<!-- Describe your approach to solving the problem. -->\nThe approach is to find out all the possible subset and take only those which have a size == k\n\nRecommended Question ( Subset ) : [ https://leetcode.com/problems/subsets/]()\n\n# Complexity\n- Time complexity : 2^N\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(N^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void helper(vector<int>& nums, int k, int index, vector<int>& temp, vector<vector<int>>& ans){\n\n \n if(index==nums.size()){\n\n if(temp.size()==k){\n ans.push_back(temp);\n }\n return ;\n }\n\n helper(nums, k, index+1, temp, ans);\n temp.push_back(nums[index]);\n helper(nums, k, index+1, temp, ans);\n temp.pop_back();\n \n\n\n\n }\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> temp;\n vector<int> nums;\n\n for(int i = 1;i<=n;i++){\n nums.push_back(i);\n }\n\n helper(nums,k,0,temp,ans);\n return ans;\n }\n};\n```\n\n# 2nd Approach\n<!-- Describe your approach to solving the problem. -->\nTake all the possible pairs in each for loop iteration and for each index i, push them into temp and decrease size of k and call Recursion after the Recursion call ends pop back the value.\n\n# Complexity\n- Time complexity : 2^N\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : O(N^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void helper(vector<int>& nums, int k, int index, vector<int>& temp, vector<vector<int>>& ans){\n\n \n if(k==0){\n ans.push_back(temp);\n return;\n }\n \n\n if(index==nums.size()) return ;\n\n for(int i = index;i<nums.size();i++){\n temp.push_back(nums[i]);\n helper(nums,k-1,i+1,temp,ans);\n temp.pop_back();\n }\n\n\n\n }\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> temp;\n vector<int> nums;\n\n for(int i = 1;i<=n;i++){\n nums.push_back(i);\n }\n\n helper(nums,k,0,temp,ans);\n return ans;\n }\n};\n``` | 5 | 0 | ['Backtracking', 'C++'] | 1 |
combinations | 77. Combinations with step by step explanation | 77-combinations-with-step-by-step-explan-y3hr | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThis solution uses the backtracking algorithm to generate all the combina | Marlen09 | NORMAL | 2023-02-14T04:22:01.672296+00:00 | 2023-02-14T04:22:01.672338+00:00 | 1,922 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis solution uses the backtracking algorithm to generate all the combinations of k numbers from the range [1, n]. The function backtrack starts with a starting point first and an empty list curr which will store the current combination being generated. If the length of curr is equal to k, it means that a combination has been generated and it is appended to the result list res. If not, the function continues to generate combinations by adding integers from first to n to curr and recursively calling backtrack with updated values of first and curr. Before making the recursive call, the function pops the last element from curr to prepare for the next iteration.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def backtrack(first = 1, curr = []):\n if len(curr) == k:\n res.append(curr[:])\n return\n for i in range(first, n+1):\n curr.append(i)\n backtrack(i+1, curr)\n curr.pop()\n res = []\n backtrack()\n return res\n\n``` | 5 | 0 | ['Python', 'Python3'] | 0 |
combinations | C++ Solution | c-solution-by-pranto1209-pdto | Approach\n Describe your approach to solving the problem. \n Backtracking\n\n# Code\n\nclass Solution {\npublic:\n vector<vector<int>> ans;\n int nl;\n | pranto1209 | NORMAL | 2023-01-14T17:57:30.573080+00:00 | 2023-03-14T08:15:20.335772+00:00 | 1,022 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n Backtracking\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> ans;\n int nl;\n\n void solve(vector<int> &a, int id, int k) {\n if(k == 0) {\n ans.push_back(a);\n return;\n }\n for(int i=id; i<=nl; i++) {\n a.push_back(i);\n solve(a, i+1, k-1);\n a.pop_back();\n }\n }\n\n vector<vector<int>> combine(int n, int k) {\n nl = n;\n vector<int> a;\n solve(a, 1, k);\n return ans;\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
combinations | javascript backtracking | javascript-backtracking-by-egor_sh-p96j | \n/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nvar combine = function (n, k) {\n let output = [];\n\n const findCombinat | egor_sh | NORMAL | 2022-11-15T19:56:40.170482+00:00 | 2022-11-15T19:56:40.170516+00:00 | 1,012 | false | ```\n/**\n * @param {number} n\n * @param {number} k\n * @return {number[][]}\n */\nvar combine = function (n, k) {\n let output = [];\n\n const findCombinations = (start, combination) => {\n if (combination.length === k) {\n output.push([...combination]);\n return;\n }\n\n if (combination.length > k) return;\n\n for (let i = start; i <= n; i++) {\n combination.push(i);\n findCombinations(i + 1, combination);\n combination.pop();\n }\n }\n\n findCombinations(1, []);\n\n return output;\n};\n``` | 5 | 0 | ['JavaScript'] | 0 |
combinations | Python3 | Backtracking | Intuitive and Easy to Understand | python3-backtracking-intuitive-and-easy-peibz | ```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n \n nums = list(range(1, n+1))\n results = []\n \n | ahbar | NORMAL | 2022-07-06T10:41:50.625796+00:00 | 2022-07-06T10:41:50.625842+00:00 | 1,073 | false | ```\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n \n nums = list(range(1, n+1))\n results = []\n \n def backtrack(i, ans):\n if len(ans) == k:\n results.append(ans[:])\n return\n \n for num in nums[i:]:\n ans.append(num)\n # i+1 to control the search space vertically i.e. to use each element only once\n backtrack(i+1, ans)\n ans.pop()\n # to control the search space horizontally i.e. to only use successive elements\n i += 1\n \n backtrack(0, [])\n \n return results\n\t | 5 | 0 | ['Backtracking', 'Depth-First Search', 'Python', 'Python3'] | 2 |
combinations | C++ || Easy and Simple Code || Backtracking | c-easy-and-simple-code-backtracking-by-a-2ckl | \nclass Solution {\npublic:\n void backTrack(int n,int k,int it,vector<vector<int>> &ans,vector<int> &res){\n \n if(res.size()==k){\n | agrasthnaman | NORMAL | 2022-02-17T13:31:06.844299+00:00 | 2022-02-17T13:31:06.844377+00:00 | 482 | false | ```\nclass Solution {\npublic:\n void backTrack(int n,int k,int it,vector<vector<int>> &ans,vector<int> &res){\n \n if(res.size()==k){\n ans.push_back(res);\n return;\n }\n for(int i=it;i<=n;i++){\n res.push_back(i);\n backTrack(n,k,i+1,ans,res);\n res.pop_back();\n }\n }\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> res;\n backTrack(n,k,1,ans,res);\n return ans;\n }\n};\n```\nDo upvote if it helped :) | 5 | 0 | ['Backtracking', 'C', 'C++'] | 0 |
combinations | combinations || c++ || backtracking | combinations-c-backtracking-by-sheetaljo-8rxv | TC=O(n*(2^n))\nSC=O(n) this can be a topic of discussion\n\nsimilar to the question subsets\nhttps://leetcode.com/problems/subsets/discuss/1654354/3-sol.-oror-c | sheetaljoshi | NORMAL | 2021-12-29T08:38:31.817074+00:00 | 2021-12-29T08:42:17.097920+00:00 | 527 | false | TC=O(n*(2^n))\nSC=O(n) this can be a topic of discussion\n\nsimilar to the question subsets\nhttps://leetcode.com/problems/subsets/discuss/1654354/3-sol.-oror-c%2B%2B-oror-subsets-oror-backtracking-oror-bit-manipulation-oror-iterative\n\n```\nclass Solution {\npublic:\n void generate(vector<int>& nums,int idx,int k,vector<int>& curr,vector<vector<int>>&ans){\n if(curr.size()==k){\n ans.push_back(curr);\n return;}\n for( int i=idx;i<nums.size();i++){\n curr.push_back(nums[i]);\n generate(nums,i+1,k,curr,ans);\n curr.pop_back();\n }\n }\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> curr;\n vector<int> nums(n,0);\n for(int i=0;i<n;i++){\n nums[i]=i+1;\n }\n generate(nums,0,k,curr,ans);\n return ans;\n }\n};\n\n```\nupvote if found useful :) | 5 | 0 | ['Backtracking', 'Recursion', 'C', 'C++'] | 0 |
combinations | General approach to backtracking problems in C++ | general-approach-to-backtracking-problem-9c0g | Below I present a general approach to many standard backtracking problems. A similar version exists for JAVA here but I thought it would be a good idea to do th | udaiwalrohit | NORMAL | 2021-06-28T17:46:38.539309+00:00 | 2021-06-28T17:46:38.539376+00:00 | 184 | false | Below I present a general approach to many standard backtracking problems. A similar version exists for JAVA [here](https://leetcode.com/problems/subsets/discuss/27281/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partitioning)) but I thought it would be a good idea to do the same for C++ as well, even though the essence of the solutions remains the same. Most of these problems follow a single template as given below. \n\n```\n//Template\nvoid Backtrack(int start)\n{\n //Base case \n\n// loop for all possible values\n{\n //include the current element at this position if possible in the ans \n\t//More generally, make a choice \n\n Backtrack(start+1) \n\n //backtrack by removing current element \n}\n```\n\n\n**1**.[78. Subsets](https://leetcode.com/problems/subsets/)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> subsets(vector<int>& a) {\n vector<vector<int>> ans;\n vector<int> subset;\n n=a.size();\n \n GenerateSubs(a,0,subset,ans);\n return ans; \n }\nprivate:\n int n;\n void GenerateSubs(vector<int>&a,int s,vector<int>&subset,vector<vector<int>>&ans)\n {\n for(int i=s;i<n;i++)\n {\n subset.push_back(a[i]); //include element at ith position\n GenerateSubs(a,i+1,subset,ans); //generate all subsets including ith element\n subset.pop_back(); //backtrack\n }\n ans.push_back(subset);\n }\n};\n```\n\n**2**.[90. Subsets II](https://leetcode.com/problems/subsets-ii/) (Subsets with duplicates)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> subsetsWithDup(vector<int>& a) {\n vector<vector<int>> ans;\n vector<int> subset;\n n=a.size();\n \n sort(a.begin(),a.end()); //sort the elements so that we can keep track of duplicates\n GenerateSubs(a,0,subset,ans);\n return ans; \n }\nprivate:\n int n;\n void GenerateSubs(vector<int>&a,int s,vector<int>&subset,vector<vector<int>>&ans)\n {\n for(int i=s;i<n;i++)\n {\n if(i==s||a[i]!=a[i-1]) \n {\n subset.push_back(a[i]); //include element at ith position\n GenerateSubs(a,i+1,subset,ans); //generate all subsets including ith element\n subset.pop_back(); //backtrack\n }\n }\n ans.push_back(subset);\n }\n};\n```\n\n**3.** [77. Combinations](https://leetcode.com/problems/combinations/)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> combination;\n \n GenerateCombs(n,1,k,ans,combination);\n return ans;\n }\nprivate:\n void GenerateCombs(int n,int s,int k,vector<vector<int>> &ans,vector<int> &combination)\n {\n if(combination.size()==k) //base case\n {\n ans.push_back(combination);\n return;\n }\n \n for(int i=s;i<=n;i++)\n {\n combination.push_back(i); //include i in a combination\n GenerateCombs(n,i+1,k,ans,combination);\n combination.pop_back(); //remove i, i.e. backtrack\n }\n }\n};\n```\n\n**4.** [39. Combination Sum\n](https://leetcode.com/problems/combination-sum/)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> combinationSum(vector<int>& a, int sum) {\n n=a.size();\n sort(a.begin(),a.end()); // optimising by only including elements smaller than sum\n combs(a,0,sum);\n \n return ans;\n \n }\nprivate:\n vector<vector<int>>ans;\n vector<int> combination;\n int n;\n \n void combs(vector<int>&a,int s,int sum)\n {\n if(sum<0) //base case1\n return;\n \n if(sum==0)\n {\n ans.push_back(combination); //base case 2\n return;\n }\n \n for(int i=s;i<n&&a[i]<=sum;i++)\n {\n combination.push_back(a[i]);\n combs(a,i,sum-a[i]);\n combination.pop_back();\n }\n } \n};\n```\n\n**5.** [40. Combination Sum II\n](https://leetcode.com/problems/combination-sum-ii/)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> combinationSum2(vector<int>& a, int sum) {\n n=a.size();\n sort(a.begin(),a.end()); // optimising by only including elements smaller than sum\n combs(a,0,sum);\n \n return ans;\n \n }\nprivate:\n vector<vector<int>>ans;\n vector<int> combination;\n int n;\n \n void combs(vector<int>&a,int s,int sum)\n {\n if(sum<0)\n return;\n \n if(sum==0)\n {\n ans.push_back(combination);\n return;\n }\n \n for(int i=s;i<n&&a[i]<=sum;i++)\n {\n \n if(i==s||a[i]!=a[i-1])\n {\n combination.push_back(a[i]);\n combs(a,i+1,sum-a[i]);\n combination.pop_back(); \n }\n }\n }\n};\n```\n\n**6.** [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)\n```\nclass Solution {\npublic:\n vector<string> generateParenthesis(int n) {\n string s;\n Generate(0,0,s,n);\n return ans;\n }\nprivate:\n vector<string>ans;\n void Generate(int left,int right,string &s,int n)\n {\n if(left==n&&right==n) // base case: when left and right parentheses are equal to n.\n {\n ans.push_back(s);\n return;\n }\n\t\t\n // case I: if left parenteses are less than n, we can add a ( to the string. \n\t\t//But we might also add a ) so we backtrack by poppping it.\n if(left<n)\n\t\t{\n s+=\'(\';\n Generate(left+1,right,s,n);\n s.pop_back(); \n }\n \n if(left>right) //case II: follows from I.\n {\n s+=\')\';\n Generate(left,right+1,s,n);\n s.pop_back();\n } \n }\n};\n```\n\n**7.** [131. Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/)\n\n```\nclass Solution {\npublic:\n vector<vector<string>> partition(string s) {\n n=s.size();\n Generate(s,0);\n return ans; \n }\nprivate:\n vector<vector<string>>ans;\n vector<string>Partition;\n int n;\n \n bool is_pal(string &s,int start,int end)\n {\n while(start<=end)\n {\n if(s[start++]!=s[end--])\n return false;\n }\n return true;\n }\n \n void Generate(string &s,int start)\n {\n if(start==n)\n {\n ans.push_back(Partition);\n return;\n }\n \n for(int i=start;i<n;i++)\n {\n if(is_pal(s,start,i))\n {\n Partition.push_back(s.substr(start,i-start+1));\n Generate(s,i+1);\n Partition.pop_back();\n }\n }\n } \n};\n```\n\n**8.** [46. Permutations](https://leetcode.com/problems/permutations/)\n\n```\nclass Solution {\npublic:\n vector<vector<int>> permute(vector<int>& arr) {\n vector<vector<int>> ans;\n \n permutations(arr,0,ans);\n \n return ans;\n }\n void permutations(vector<int>&arr,int s,vector<vector<int>>&ans)\n {\n if(s==arr.size())\n {\n ans.push_back(arr);\n return;\n }\n for(int i=s;i<arr.size();i++)\n {\n swap(arr[s],arr[i]);\n permutations(arr,s+1,ans);\n swap(arr[s],arr[i]);\n }\n }\n};\n```\n | 5 | 0 | [] | 0 |
combinations | Python One Liner using Combinations - 76ms | python-one-liner-using-combinations-76ms-praf | The itertools module provides a combinations() method which can be used in this question.\n\n\nfrom itertools import combinations \nclass Solution:\n def com | mb557x | NORMAL | 2020-07-14T10:48:43.348307+00:00 | 2020-07-14T10:48:43.348340+00:00 | 276 | false | The ```itertools``` module provides a ```combinations()``` method which can be used in this question.\n\n```\nfrom itertools import combinations \nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n return [i for i in list(combinations([i for i in range(1, n+1)], k))]\n```\n | 5 | 2 | ['Python3'] | 0 |
combinations | {{ Swift }} Iterative Solution | swift-iterative-solution-by-nraptis-kdo7 | \nclass Solution {\n func combine(_ n: Int, _ k: Int) -> [[Int]] {\n \n var res = [[Int]]()\n var data = [Int](repeating: 0, count: k)\n | nraptis | NORMAL | 2019-06-19T18:20:58.341235+00:00 | 2019-06-19T18:20:58.341275+00:00 | 257 | false | ```\nclass Solution {\n func combine(_ n: Int, _ k: Int) -> [[Int]] {\n \n var res = [[Int]]()\n var data = [Int](repeating: 0, count: k)\n var i = 0\n \n while data[0] <= (n - k + 1) {\n \n data[i] += 1\n if data[i] > n {\n i -= 1\n } else if i == (k - 1) {\n res.append(data)\n } else {\n i += 1\n data[i] = data[i - 1]\n }\n }\n \n return res\n }\n}\n```\n\nThe best I can tell, the TC of this is upper-bound by\n\nO ( N! / K! )\n\nI am not sure how to prove it. The bottom term may even be something larger size. Don\'t even know the true MATHZ.\n\nPlease pray for my solution. | 5 | 0 | [] | 0 |
combinations | 5 lines python solution, very easy to understand | 5-lines-python-solution-very-easy-to-und-mp9q | ```\nclass Solution:\n def combine(self, n, k):\n if n == k:\n return [list(range(1,n+1))]\n if k == 1:\n return [ [i] fo | haefjdhfsf | NORMAL | 2018-10-11T07:28:53.677797+00:00 | 2018-10-24T06:31:45.322458+00:00 | 547 | false | ```\nclass Solution:\n def combine(self, n, k):\n if n == k:\n return [list(range(1,n+1))]\n if k == 1:\n return [ [i] for i in range(1,n+1) ]\n return self.combine(n-1,k) + [ j + [n] for j in self.combine(n-1,k-1) ] | 5 | 0 | [] | 1 |
combinations | Python recursive solution | python-recursive-solution-by-google-sjtd | class Solution:\n # @return a list of lists of integers\n # 9:14\n def __init__(self):\n self.output = []\n \n def com | google | NORMAL | 2015-03-09T02:22:58+00:00 | 2015-03-09T02:22:58+00:00 | 3,731 | false | class Solution:\n # @return a list of lists of integers\n # 9:14\n def __init__(self):\n self.output = []\n \n def combine(self, n, k, pos=0, temp=None):\n temp = temp or []\n \n if len(temp) == k:\n self.output.append(temp[:])\n return\n \n for i in range(pos, n):\n temp.append(i+1)\n self.combine(n, k, i+1, temp)\n temp.pop()\n \n return self.output | 5 | 0 | ['Python'] | 3 |
combinations | Time Limit Exceeded... Why? | time-limit-exceeded-why-by-hammerking-onb9 | It works for n = 4, k = 2, but TLE for 20, 16. Anyone knows why it's inefficient?\n\n```class Solution(object):\n def combine(self, n, k):\n res = [] | hammerking | NORMAL | 2016-09-19T02:13:28.098000+00:00 | 2016-09-19T02:13:28.098000+00:00 | 1,416 | false | It works for n = 4, k = 2, but TLE for 20, 16. Anyone knows why it's inefficient?\n\n```class Solution(object):\n def combine(self, n, k):\n res = []\n self.combineHelper(n, k, res, [], 1)\n return res\n \n def combineHelper(self, n, k, res, temp, i):\n if len(temp) == k:\n res.append(temp)\n else:\n for i in xrange(i, n+1):\n tempList = temp + [i]\n self.combineHelper(n, k, res, tempList, i+1) | 5 | 0 | [] | 5 |
combinations | Backtracking to Combine Numbers: Fast, Simple, and No Looking Back! | backtracking-to-combine-numbers-fast-sim-x7zp | Intuition\n Describe your first thoughts on how to solve this problem. \nThe first thought? It\u2019s pretty straightforward\u2014if we gotta pick k numbers out | satya78550 | NORMAL | 2024-10-18T17:07:14.367180+00:00 | 2024-10-18T17:07:14.367233+00:00 | 532 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thought? It\u2019s pretty straightforward\u2014if we gotta pick k numbers out of n, we\u2019re basically aiming to get all possible combinations of size k from 1 to n. Backtracking instantly pops into mind because it\u2019s perfect for trying all possible paths without skipping anything.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo here\u2019s the move: use backtracking. You keep adding numbers one by one, and once you\u2019ve hit k numbers, you lock that combo in and move on. You start from 1 and only go forward\u2014no looking back, literally! This makes sure we don\u2019t repeat numbers. Recursion takes care of the combo-building and when we have a full set (meaning, when K == 0), we just add it to our results and return.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nk)\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```python3 []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n result = []\n\n def backtrack( K , arr ):\n if ( K == 0 ):\n result.append( arr )\n return\n start = arr[ -1 ] + 1 if arr else 1\n for i in range( start , ( n - K + 2 )):\n backtrack( K - 1 , arr + [i] )\n backtrack( k , [] )\n return result\n``` | 4 | 0 | ['Python3'] | 0 |
combinations | simple and easy C++ solution 😍❤️🔥 | simple-and-easy-c-solution-by-shishirrsi-llu6 | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook | shishirRsiam | NORMAL | 2024-08-23T09:47:47.591135+00:00 | 2024-08-23T09:47:47.591198+00:00 | 1,118 | false | \n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int n, k;\n vector<int>path, nums;\n vector<vector<int>> ans;\n void backtrack(int start)\n {\n if(path.size() == k)\n {\n ans.push_back(path);\n return;\n }\n for(int i=start;i<n;i++)\n {\n path.push_back(nums[i]);\n backtrack(i+1);\n path.pop_back();\n }\n }\n vector<vector<int>> combine(int num, int kk) \n {\n n = num, k = kk; \n for(int i=1;i<=n;i++)\n nums.push_back(i);\n backtrack(0);\n return ans;\n }\n};\n``` | 4 | 0 | ['Backtracking', 'C++'] | 3 |
combinations | ✅💯🔥Simple Code📌🚀| 🔥✔️Easy to understand🎯 | 🎓🧠Beginner friendly🔥| O(n) Time Complexity💀💯 | simple-code-easy-to-understand-beginner-azal3 | Solution tuntun mosi ki photo ke baad hai. Scroll Down\n\n# Code\njava []\nclass Solution {\n public List<List<Integer>> combine(int n, int k){\n List | atishayj4in | NORMAL | 2024-08-21T19:32:22.593521+00:00 | 2024-08-21T19:32:22.593559+00:00 | 158 | false | Solution tuntun mosi ki photo ke baad hai. Scroll Down\n\n# Code\n```java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k){\n List<List<Integer>> ans = new ArrayList<>();\n fnc(n, k, 1, new ArrayList<>(), ans);\n return ans;\n }\n\n private void fnc(int n, int k, int s, List<Integer> comb, List<List<Integer>> ans){\n if(comb.size() == k){\n ans.add(new ArrayList<>(comb));\n return;\n }\n for(int i=s; i<=n; i++){\n comb.add(i);\n fnc(n, k, i+1, comb, ans);\n comb.remove(comb.size()-1);\n }\n }\n}\n```\n | 4 | 0 | ['Backtracking', 'C', 'Python', 'C++', 'Java', 'JavaScript'] | 0 |
combinations | ✅Easy and simple solution ✅clean code | easy-and-simple-solution-clean-code-by-a-hmkt | Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F\nFoll | ayushluthra62 | NORMAL | 2024-07-23T13:19:00.342817+00:00 | 2024-07-23T13:19:00.342864+00:00 | 470 | false | ***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]**\n\n# Complexity\n- Time complexity:\nO(NcK)\n\n# Code\n```\nclass Solution {\npublic:\nvoid solve(vector<vector<int>>& ans, vector<int> &temp, int currIndex,int k,vector<int>&temp2){\n\n if(currIndex>=temp.size() || k==0) {\n if(k==0)\n ans.push_back(temp2);\n return ;\n }\n\n solve(ans,temp,currIndex+1,k,temp2);\n temp2.push_back(temp[currIndex]);\n solve(ans,temp,currIndex+1,k-1,temp2);\n temp2.pop_back();\n}\n vector<vector<int>> combine(int n, int k) {\n vector<int>temp;\n\n for(int i=1;i<=n;i++){\n temp.push_back(i);\n } \n\n vector<vector<int>>ans;\n vector<int>temp2;\n solve(ans,temp,0,k,temp2);\n\n\n return ans;\n }\n};\n```\n***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]** | 4 | 0 | ['Backtracking', 'C++'] | 0 |
combinations | Solution By Dare2Solve | Detailed Explanation | Clean Code | solution-by-dare2solve-detailed-explanat-rzag | Explanation []\nauthorslog.com/blog/EtIaoat6mn\n\n# Code\n\ncpp []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<v | Dare2Solve | NORMAL | 2024-07-20T17:38:43.954833+00:00 | 2024-07-20T17:38:43.954858+00:00 | 840 | false | ```Explanation []\nauthorslog.com/blog/EtIaoat6mn\n```\n# Code\n\n```cpp []\nclass Solution {\npublic:\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> result;\n vector<int> combination;\n\n backtrack(n, k, 1, combination, result);\n return result;\n }\n\nprivate:\n void backtrack(int n, int k, int start, vector<int>& combination, vector<vector<int>>& result) {\n if (combination.size() == k) {\n result.push_back(combination);\n return;\n }\n\n for (int i = start; i <= n; ++i) {\n combination.push_back(i);\n backtrack(n, k, i + 1, combination, result);\n combination.pop_back();\n }\n }\n};\n\n```\n\n```python []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n def backtrack(start, combination):\n if len(combination) == k:\n result.append(combination[:])\n return\n\n for i in range(start, n + 1):\n combination.append(i)\n backtrack(i + 1, combination)\n combination.pop()\n\n result = []\n backtrack(1, [])\n return result \n```\n\n```java []\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n List<List<Integer>> result = new ArrayList<>();\n List<Integer> combination = new ArrayList<>();\n backtrack(n, k, 1, combination, result);\n return result;\n }\n\n private void backtrack(int n, int k, int start, List<Integer> combination, List<List<Integer>> result) {\n if (combination.size() == k) {\n result.add(new ArrayList<>(combination));\n return;\n }\n\n for (int i = start; i <= n; ++i) {\n combination.add(i);\n backtrack(n, k, i + 1, combination, result);\n combination.remove(combination.size() - 1);\n }\n }\n}\n```\n\n```javascript []\nvar combine = (n, k) => \n{\n let q = [], r = []\n\n for(let i = 1; i <=n; i++) q.push([i])\n \n while(q.length) {\n let Q = []\n\n q.forEach(e => {\n if(e.length === k) return r.push(e)\n\n for(let i = e[e.length - 1] + 1; i <= n; i++) Q.push([...e, i])\n })\n\n q = Q\n }\n return r\n}\n``` | 4 | 0 | ['Backtracking', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 1 |
combinations | C++ and Python3 || Backtracking || Simple and Optimal | c-and-python3-backtracking-simple-and-op-0gx7 | \n# Code\nC++ []\nclass Solution {\npublic:\n void bt(int idx, int k, int n, vector<int> &comb, vector<vector<int>> &ans) {\n if(comb.size() == k) {\n | meurudesu | NORMAL | 2024-02-28T11:01:25.962614+00:00 | 2024-02-28T11:01:25.962636+00:00 | 598 | false | > \n# Code\n```C++ []\nclass Solution {\npublic:\n void bt(int idx, int k, int n, vector<int> &comb, vector<vector<int>> &ans) {\n if(comb.size() == k) {\n ans.push_back(comb);\n return;\n }\n for(int i = idx; i <= n; i++) {\n comb.push_back(i);\n bt(i + 1, k, n, comb, ans);\n comb.pop_back();\n }\n }\n\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> comb;\n bt(1, k, n, comb, ans);\n return ans;\n }\n};\n```\n```Python3 []\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n ans = []\n def bt(idx, comb):\n if len(comb) == k:\n ans.append(comb[:])\n return\n for i in range(idx, n + 1):\n comb.append(i)\n bt(i + 1, comb)\n comb.pop()\n bt(1, [])\n return ans\n``` | 4 | 0 | ['Backtracking', 'Depth-First Search', 'Recursion', 'C++', 'Python3'] | 2 |
combinations | Easy Beginner friendly Solution || Java || C++ || Python | easy-beginner-friendly-solution-java-c-p-1b8w | Intuition\n Describe your first thoughts on how to solve this problem. \nThis Java code provides a solution to generate combinations of k elements from the numb | Aditya_Mohan_Gupta02 | NORMAL | 2024-02-13T19:02:39.587008+00:00 | 2024-02-13T19:02:39.587038+00:00 | 319 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis Java code provides a solution to generate combinations of k elements from the numbers 1 to n.\nIn summary, this code employs a recursive backtracking approach to generate all possible combinations of k elements from the numbers 1 to n. It avoids duplicates and ensures that each combination is unique. The final list of combinations is stored in the ll variable and returned by the combine method.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet\'s break down the approach:\n\ncombine method: This is the entry point of the program. It takes two parameters $$n$$ and $$k$$ and returns a list of lists containing the combinations. It initializes a static variable $$ll$$ (list of lists) and calls the $$rec$$ method to generate combinations.\n\n$$rec method$$: This method is a recursive function that generates combinations. It takes four parameters:\n\n$$n$$: The maximum number.\n\n$$k$$: The number of elements in each combination.\n\n$$result$$: A list that stores the current combination being built.\n\n$$idx$$: The index to start from in the iteration.\nInside the method:\n\nIf the size of $$result$$ equals $$k$$, it means a valid combination has been found, so it\'s added to the list $$ll$$.\nOtherwise, it iterates from $$idx$$ to $$n$$ (inclusive) and recursively calls itself, incrementing $$idx$$ by 1 each time to move to the next element in the combination. This ensures that each element is considered only once in a combination.\nBefore making the recursive call, the current element is added to $$result$$, and after the recursive call, it is removed to backtrack and try other combinations.\n\n$$Static$$ $$variable$$ $$ll$$: This is a static variable declared outside any method. It is used to store all the valid combinations generated by the rec method. Since it\'s static, it can be accessed and modified by all instances of the Solution class.\n\n# Code\n```\nclass Solution {\n public List<List<Integer>> combine(int n, int k) {\n ll=new ArrayList<>();\n rec(n,k,new ArrayList<>(),1);\n return ll;\n }\n static List<List<Integer>> ll;\n public static void rec(int n,int k,List<Integer> result,int idx){\n if(result.size()==k){\n ll.add(new ArrayList<>(result));\n return;\n }\n for(int i=idx;i<=n;i++){\n result.add(i);\n rec(n,k,result,i+1); // i+1 for combinations\n result.remove(result.size()-1);\n }\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
combinations | Best Solution | best-solution-by-kumar21ayush03-lc8n | Approach\nRecursion\n\n# Complexity\n- Time complexity:\nO(2^n)\n\n- Space complexity:\nO(n) \n\n# Code\n\nclass Solution {\npublic:\n void solve(int i, int | kumar21ayush03 | NORMAL | 2023-08-02T05:37:00.391601+00:00 | 2023-08-02T05:37:00.391629+00:00 | 19 | false | # Approach\nRecursion\n\n# Complexity\n- Time complexity:\n$$O(2^n)$$\n\n- Space complexity:\n$$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n void solve(int i, int k, vector<int>& temp, vector<vector<int>>& ans) {\n if (k == 0) {\n ans.push_back(temp);\n return;\n }\n if (i == 0) {\n return;\n }\n temp.push_back(i);\n solve(i-1, k-1, temp, ans);\n temp.pop_back();\n solve(i-1, k, temp, ans);\n }\n\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> temp;\n solve(n, k, temp, ans);\n\n return ans;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
combinations | Simple and basic approach using recursion of take and nottake case | simple-and-basic-approach-using-recursio-8pdr | Intuition\n simply used take and nottake cases for combinations \n\n# Approach\n used backtracking first push element into array untill size of temp bacomes K a | mahadev_lover | NORMAL | 2023-08-01T08:22:04.272204+00:00 | 2023-08-01T08:22:04.272239+00:00 | 92 | false | # Intuition\n<!-- simply used take and nottake cases for combinations -->\n\n# Approach\n<!-- used backtracking first push element into array untill size of temp bacomes K and then pop the element that is pushed so that next element can be taken -->\n\n# Complexity\n- Time complexity:\n<!-- O(2^k) -->\n\n- Space complexity:\n<!-- O(2^n) -->\n\n# Code\n```\nclass Solution {\npublic:\n void f(int ind,int k,vector<int> &temp,vector<vector<int>> &ans) \n {\n if(k==0)\n {\n ans.push_back(temp);\n return ;\n }\n if(ind==0) return ;\n f(ind-1,k,temp,ans);\n temp.push_back(ind);\n f(ind-1,k-1,temp,ans);\n temp.pop_back();\n\n }\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n vector<int> temp;\n f(n,k,temp,ans);\n return ans;\n\n\n }\n};\n``` | 4 | 0 | ['Array', 'Backtracking', 'C++'] | 0 |
combinations | Bitmasking || Easily explained in Hindi || Clean and concise code | bitmasking-easily-explained-in-hindi-cle-4kfd | Approach\n1. We have to choose exactly K numbers out of N numbers.\n2. To choose that we will create bit masks.\n3. What bit masks will do is, we have all the n | ashay028 | NORMAL | 2023-08-01T07:49:47.657507+00:00 | 2023-08-01T07:49:47.657531+00:00 | 57 | false | # Approach\n1. We have to choose exactly K numbers out of N numbers.\n2. To choose that we will create bit masks.\n3. What bit masks will do is, we have all the numbers which have only K set bits and it is less than 2^N (i.e. total number of bits are less equal to N) so these will help to choose the K numbers. \n\nSo what we did is : \n- Saare numbers genrate kar liye jisne K set bits hai.\n- Jin position ki bit set hai unko ek array m push kra \n- Usko result m push kr diya\n\n\n# Complexity\n- Time complexity: O(2^N * log(N))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(log K)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // ye function ek number ko lega aur usme jis position \n // pr set bit (1) hai usko array m push krega \n vector<int> fun(int num)\n {\n vector<int> ans;\n int cnt=1;\n while(num)\n {\n if(num%2) ans.emplace_back(cnt);\n num/=2;\n cnt++;\n }\n return ans;\n }\n vector<vector<int>> combine(int n, int k) {\n vector<vector<int>> ans;\n // (1<<n) = 2^n\n // Loop chala do 2^N taki saare numbers aa jaaye \n for(int i=0; i< (1<<n) ; i++) \n {\n // Jis numbers mai bits exactly K hai vo he kaam k hai bs\n if(__builtin_popcount(i) == k) \n ans.emplace_back(fun(i));\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Python3] Easy Python3 BFS + Graph Like | python3-easy-python3-bfs-graph-like-by-l-kla5 | nextLetter is like a graph. a -> bc, b -> ac, c -> ab. \nSince we are doing BFS with the next node in the graph already sorted, \nwe are guaranteed to have a so | localhostghost | NORMAL | 2020-04-18T21:55:14.264218+00:00 | 2020-04-20T11:53:01.555206+00:00 | 5,715 | false | ` nextLetter ` is like a graph. `a -> bc`, `b -> ac`, `c -> ab`. \nSince we are doing BFS with the next node in the graph already sorted, \nwe are guaranteed to have a sorted queue with all the element of the \nsame length.\n\nBreak when the first string in the queue is length `n` and find the `k`th value in the queue.\n\n```\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n nextLetter = {\'a\': \'bc\', \'b\': \'ac\', \'c\': \'ab\'} \n q = collections.deque([\'a\', \'b\', \'c\'])\n while len(q[0]) != n:\n u = q.popleft() \n for v in nextLetter[u[-1]]:\n q.append(u + v)\n return q[k - 1] if len(q) >= k else \'\' \n``` | 130 | 1 | [] | 12 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [C++/Java] DFS and Math | cjava-dfs-and-math-by-votrubac-l5d3 | Aproach 1: DFS\nHere, DFS builds all possible strings in a lexicographical order. Each time a string is built, we decrease the global counter k. When k reaches | votrubac | NORMAL | 2020-04-18T16:03:12.591819+00:00 | 2020-05-14T06:26:07.636302+00:00 | 11,352 | false | #### Aproach 1: DFS\nHere, DFS builds all possible strings in a lexicographical order. Each time a string is built, we decrease the global counter `k`. When `k` reaches zero, we short-circut DFS and build the resulting string right-to-left. \n\n> Exploring references and optional parameters for a concise code.\n\n```cpp\nstring getHappyString(int n, int &k, int p = 0, char last_ch = 0) {\n if (p == n)\n --k;\n else\n for (char ch = \'a\'; ch <= \'c\'; ++ch) {\n if (ch != last_ch) {\n auto res = getHappyString(n, k, p + 1, ch);\n if (k == 0)\n return string(1, ch) + res;\n }\n }\n return "";\n}\n```\n**Complexity Analysis**\n- Time: O(n * k); we evaluate `k` strings of the size `n`.\n- Memory: O(n) for the stack (not including the output).\n\n#### Aproach 2: Math\nFor the string of size `n`, we can build `3 * pow(2, n - 1)` strings. So, if `k <= pow(2, n - 1)`, then the first letter is `a`, `k <= 2 * pow(2, n - 1)` - then `b`, otherwise `c`. We can also return empty string right away if `k > 3 * pow(2, n - 1)`.\n\nWe continue building the string using the same approach but now with two choices.\n\n**C++**\n```cpp\nstring getHappyString(int n, int k) {\n auto prem = 1 << (n - 1);\n if (k > 3 * prem)\n return "";\n string s = string(1, \'a\' + (k - 1) / prem);\n while (prem > 1) {\n k = (k - 1) % prem + 1;\n prem >>= 1;\n s += (k - 1) / prem == 0 ? \'a\' + (s.back() == \'a\') : \'b\' + (s.back() != \'c\');\n }\n return s;\n}\n```\n\n**Java**\n```java\npublic String getHappyString(int n, int k) {\n int prem = 1 << (n - 1);\n if (k > 3 * prem)\n return "";\n int ch = \'a\' + (k - 1) / prem;\n StringBuilder sb = new StringBuilder(Character.toString(ch));\n while (prem > 1) {\n k = (k - 1) % prem + 1;\n prem >>= 1;\n ch = (k - 1) / prem == 0 ? \'a\' + (ch == \'a\' ? 1 : 0) : \'b\' + (ch != \'c\' ? 1 : 0);\n sb.append((char)ch);\n }\n return sb.toString();\n} \n```\n\n**Complexity Analysis**\n- Time: O(n); we build one string of the size `n`.\n- Memory: O(1) - not considering output. | 110 | 3 | [] | 30 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 🚀 Beats 100% | Algorithm: Depth-First Search (DFS) for K-th Happy String | Explaination with Video | beats-100-algorithm-depth-first-search-d-kjjr | Youtube🚀🚀 Beats 100% | Algorithm: Depth-First Search (DFS) for K-th Happy String | Explanation with Video 🔍🔼 Please Upvote🔼 Please Upvote🔼 Please Upvote🔼 Please | rahulvijayan2291 | NORMAL | 2025-02-19T04:58:50.055162+00:00 | 2025-02-19T04:58:50.055162+00:00 | 15,454 | false | # Youtube
https://youtu.be/fsFdfuF_8zs

---
# 🚀 **🚀 Beats 100% | Algorithm: Depth-First Search (DFS) for K-th Happy String | Explanation with Video 🔍**
---
# **🔼 Please Upvote**
# **🔼 Please Upvote**
# **🔼 Please Upvote**
# **🔼 Please Upvote**
💡 **If this helped, don’t forget to upvote! 🚀🔥**
---
### **💡 Problem Breakdown**
A **Happy String** consists of letters from the set `['a', 'b', 'c']` and must not contain consecutive identical characters. Given two integers `n` and `k`, the task is to return the k-th lexicographically smallest happy string of length `n`. If no such string exists, return an empty string.
---
### **Approach Overview (Algorithm: Depth-First Search (DFS))**
The solution uses **DFS (Depth-First Search)** to generate all possible happy strings and return the k-th smallest:
1. **DFS Traversal:** Explore all combinations of happy strings recursively.
2. **Lexicographical Order:** The search starts from `'a'`, `'b'`, and `'c'` to ensure order.
3. **String Construction:** The search avoids consecutive same characters.
4. **Efficient Search Pruning:** The count of valid strings at each step is calculated using powers of 2. Pruning is done based on the remaining `k`.
DFS is preferred over backtracking as it eliminates unnecessary exploration by counting valid strings at each level.
---
## **📝 Code Implementations**
---
### **🔵 Java Solution**
```java []
class Solution {
int n2;
public String getHappyString(int n, int k) {
n2 = n;
return dfs(new StringBuilder(), n, k);
}
public String dfs(StringBuilder prefix, int n, int k){
if (n == 0)
return prefix.toString();
for (char c = 'a'; c <= 'c'; c++) {
if (prefix.length() > 0 && c == prefix.charAt(prefix.length() - 1))
continue;
int cnt = (int) Math.pow(2, n2 - prefix.length() - 1);
if (cnt >= k)
return dfs(prefix.append(c), n - 1, k);
else
k -= cnt;
}
return "";
}
}
```
---
### **🟢 C++ Solution**
```cpp []
class Solution {
int n2;
string dfs(string prefix, int n, int k) {
if (n == 0)
return prefix;
for (char c = 'a'; c <= 'c'; c++) {
if (!prefix.empty() && c == prefix.back())
continue;
int cnt = (1 << (n2 - prefix.length() - 1));
if (cnt >= k)
return dfs(prefix + c, n - 1, k);
else
k -= cnt;
}
return "";
}
public:
string getHappyString(int n, int k) {
n2 = n;
return dfs("", n, k);
}
};
```
---
### **🟣 Python Solution**
```python []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
def dfs(prefix, n, k):
if n == 0:
return prefix
for c in 'abc':
if prefix and c == prefix[-1]:
continue
cnt = 2 ** (n2 - len(prefix) - 1)
if cnt >= k:
return dfs(prefix + c, n - 1, k)
else:
k -= cnt
return ""
n2 = n
return dfs("", n, k)
```
---
### **🟡 C Solution**
```c []
char* dfs(char* prefix, int n, int n2, int* k) {
if (n == 0)
return prefix;
for (char c = 'a'; c <= 'c'; c++) {
int len = strlen(prefix);
if (len > 0 && c == prefix[len - 1])
continue;
int cnt = (int) pow(2, n2 - len - 1);
if (cnt >= *k) {
prefix[len] = c;
prefix[len + 1] = '\0';
return dfs(prefix, n - 1, n2, k);
} else
*k -= cnt;
}
return "";
}
char* getHappyString(int n, int k) {
int n2 = n;
char* prefix = (char*) malloc((n + 1) * sizeof(char));
prefix[0] = '\0';
return dfs(prefix, n, n2, &k);
}
```
---
### **🔴 JavaScript Solution**
```javascript []
var getHappyString = function(n, k) {
let n2 = n;
function dfs(prefix, n, k) {
if (n === 0) return prefix;
for (let c of ['a', 'b', 'c']) {
if (prefix.length > 0 && c === prefix[prefix.length - 1]) continue;
let cnt = 2 ** (n2 - prefix.length - 1);
if (cnt >= k) return dfs(prefix + c, n - 1, k);
else k -= cnt;
}
return "";
}
return dfs("", n, k);
};
```
---
### **⚡ Complexity Analysis**
- **Time Complexity:** `O(3^n)` — Without pruning, all combinations would be generated. However, pruning reduces the effective search.
- **Space Complexity:** `O(n)` — Space is used by the recursion stack and the prefix string.
---
# **🔼 Please Upvote**
# **🔼 Please Upvote**
# **🔼 Please Upvote**
# **🔼 Please Upvote**
💡 **If this helped, don’t forget to upvote! 🚀🔥** | 78 | 1 | ['String', 'Depth-First Search', 'C', 'C++', 'Java', 'Python3', 'JavaScript'] | 7 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | C++ Recursive fully explained solution | c-recursive-fully-explained-solution-by-1wt3a | \n//This is my first try to put code into discussion part hope you like it and if like please upvote :)\n\nclass Solution {\npublic:\n \n void solve(vecto | harsh_114 | NORMAL | 2020-04-19T03:49:10.235671+00:00 | 2020-04-19T03:50:39.490401+00:00 | 3,099 | false | ```\n//This is my first try to put code into discussion part hope you like it and if like please upvote :)\n\nclass Solution {\npublic:\n \n void solve(vector<string>& ans,string& cur,int n,int& k,vector<char>& v){\n //before base cases please refer lower part :)\n if(ans.size()==k){\n //if size of answer vector is equal to k that means I found kth string with n length\n return;\n }\n if(cur.size()==n){\n //length of cur is equal to n means cur is part of ans and after that no further recursive call required so I have returned\n ans.push_back(cur);\n return;\n }\n //here I\'m iterate over all three elements of v if possible, it is possible if cur\'s length is equal to zero otherwise I have to check if last element of cur shouldn\'t equal to v[i]\n for(int i=0;i<3;i++){\n if(cur.size()==0 || cur[cur.size()-1]!=v[i]){\n //if condition satisifed then I should append that character to cur\n cur+=v[i];\n //call solve() with new value of cur\n solve(ans,cur,n,k,v);\n //after calling we should remove that character and try for other character for same length of cur for example after calling for "ab" I should call for "ac" calls are obviously in lexicogrphic order now you can see base cases :)\n cur.pop_back();\n }\n }\n }\n \n string getHappyString(int n, int k) {\n string cur=""; //cur string with no characters\n vector<string> ans; //ans is vector of string which is going to store all string of length of cur string\n vector<char> v={\'a\',\'b\',\'c\'}; //vector of character in which characters \'a\',\'b\',\'c\' are stored\n solve(ans,cur,n,k,v); //firs function call with empty string with empty vector of string ans and n,k now, please refer implementation of solve :)\n if(ans.size()==k){\n //if program reach here from base case 1 which is ans\'s size equals to k that means I should return last element of ans\n return ans.back();\n }\n else{\n //else I should return empty string\n return "";\n }\n }\n};\n```\n\n | 53 | 0 | ['Recursion', 'C'] | 5 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Easiest solution using bfs---C++ | easiest-solution-using-bfs-c-by-mr_233-juzm | \nclass Solution {\npublic:\n string getHappyString(int n, int k) {\n vector<string> ans;\n queue<string> q;\n q.push("a");\n q.p | mr_233 | NORMAL | 2020-04-18T16:01:48.680325+00:00 | 2020-04-19T07:20:29.988701+00:00 | 3,023 | false | ```\nclass Solution {\npublic:\n string getHappyString(int n, int k) {\n vector<string> ans;\n queue<string> q;\n q.push("a");\n q.push("b");\n q.push("c");\n while(!q.empty())\n {\n string x=q.front();\n q.pop();\n if(x.length()==n)\n {\n ans.push_back(x);\n }\n string s1="",s2="";\n if(x[x.length()-1]==\'a\')\n {\n s1=x+"b";\n s2=x+"c";\n \n }\n if(x[x.length()-1]==\'b\')\n {\n s1=x+"a";\n s2=x+"c";\n \n }\n if(x[x.length()-1]==\'c\')\n {\n s1=x+"a";\n s2=x+"b";\n \n }\n \n //push only when less than n\n \n if(s1.length()<=n)\n {\n q.push(s1);\n }\n if(s2.length()<=n)\n {\n q.push(s2);\n }\n }\n \n string s="";\n if(k-1>=ans.size())\n {\n s="";\n }\n else\n {\n s=ans[k-1];\n }\n return s;\n \n \n }\n};\n``` | 43 | 0 | [] | 8 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Combinatorics+ binary expression||C++ Py3 beats 100% | combinatorics-binary-expressionc-beats-1-a6k7 | IntuitionThere are exactly3×2n−1happy strings of lengthn(combinatorical question).The set of happy strings can be divided into 3 subsets consisting of strings b | anwendeng | NORMAL | 2025-02-19T00:21:49.052019+00:00 | 2025-02-19T04:19:51.096889+00:00 | 5,627 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
There are exactly $3\times 2^{n-1}$ happy strings of length $n$ (combinatorical question).
The set of happy strings can be divided into 3 subsets consisting of strings beginning with a, b & c.
The kth one must be in 1 of them. So the expression can be described by
$
(s[0], binary \ expression\ of\ the\ rest )
$
Use the transform matrix `xx[3]={{'b', 'c'}, {'a', 'c'}, {'a', 'b'}}` to obtain the answer
# Approach
<!-- Describe your approach to solving the problem. -->
[Please turn on English subtitles if necessary]
[https://youtu.be/M4EWbcynu68?si=sES9U5-wtC9atweg](https://youtu.be/M4EWbcynu68?si=sES9U5-wtC9atweg)
1. let `sz=3*(1<<(n-1))`
2. if `k>sz` return empty string
3. set `k--`, let `q, r=divmod(k, 1<<(n-1))`
4. `s[0]='a'+q`
5. Use bitset to get the binary expression for `r`, say `bin(r)`
6. The transform matrix is given by `xx[3]={{'b', 'c'}, {'a', 'c'}, {'a', 'b'}}`
7. Use a loop to proceed i=n-2 to 0 step -1 to do:
```
char idx=s[n-2-i]-'a';
s[n-1-i]=(bin[i])?xx[idx][1]:xx[idx][0];
```
8. `s` is the answer
9. Python code is made in the similar way.
10. bitmask versions are made for Python & C++
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$O(n)$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
extra: $O(n)\to O(1)$
# Code||C++ Python 0ms beats 100%
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
int sz=3*(1<<(n-1));
if (k>sz) return "";
auto [q, r]=div(k-1, 1<<(n-1));// k-1
string s(n, ' ');
s[0]='a'+q;
bitset<9> bin(r);
array<char, 2> xx[3]={{'b', 'c'}, {'a', 'c'}, {'a', 'b'}};
for(int i=n-2; i>=0; i--){
char idx=s[n-2-i]-'a';
s[n-1-i]=(bin[i])?xx[idx][1]:xx[idx][0];
}
return s;
}
};
```
```Python []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
sz=3*(1<<(n-1))
if k>sz: return ""
q, r=divmod(k-1, 1<<(n-1))
s=[' ']*n
s[0]=chr(ord('a') + q)
B=format(r, f'0{n-1}b') # Equivalent to bitset<9> bin(r) with n-1 bits
xx = [['b', 'c'], ['a', 'c'], ['a', 'b']]
for i in range(n-1): # Iterating from 0 to n-2
idx=ord(s[i]) - ord('a')
s[i+1]=xx[idx][1] if B[i]=='1' else xx[idx][0]
return "".join(s)
```
# codes instead of bitset using bitmask||Py3, C++ 0ms
```Python []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
sz = 3*(1<<(n-1))
if k>sz: return ""
q, r=divmod(k-1, 1<<(n-1))
s=[' ']*n
s[0]=chr(ord('a') + q)
xx = [['b', 'c'], ['a', 'c'], ['a', 'b']]
for i in range(n-1): # Iterating from 0 to n-2
idx=ord(s[i]) - ord('a')
s[i+1]=xx[idx][1] if r&(1<<(n-i-2)) else xx[idx][0]
return "".join(s)
```
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
int sz=3*(1<<(n-1));
if (k>sz) return "";
auto [q, r]=div(k-1, 1<<(n-1));// k-1
string s(n, ' ');
s[0]='a'+q;
array<char, 2> xx[3]={{'b', 'c'}, {'a', 'c'}, {'a', 'b'}};
for(int i=n-2; i>=0; i--){
char idx=s[n-2-i]-'a';
s[n-1-i]=(r&(1<<i))?xx[idx][1]:xx[idx][0];
}
return s;
}
};
``` | 42 | 0 | ['String', 'Bit Manipulation', 'Combinatorics', 'Bitmask', 'C++', 'Python3'] | 11 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Java - Short and understandable #NoOverdoing | java-short-and-understandable-nooverdoin-ln84 | I am relatively new to this, so trust me if I am able to figure this one out, you can too :)!\n\nI basically generate all permutations with s[i] != s[i+1] using | narihanellaithy | NORMAL | 2020-04-18T16:22:14.453706+00:00 | 2020-04-18T16:22:37.777005+00:00 | 2,697 | false | **I am relatively new to this, so trust me if I am able to figure this one out, you can too :)!**\n\nI basically generate all permutations with s[i] != s[i+1] using this check as I append my next permutation\n```\nres.charAt(res.length()-1) != arr[i]\n```\n\n\n```\nclass Solution {\n public String getHappyString(int n, int k) {\n char[] arr = {\'a\', \'b\', \'c\'};\n String res="";\n List<String> l=new ArrayList<>();\n generatePerm(arr, n, res, l);\n if(l.size() >= k)\n res=l.get(k-1);\n return res;\n }\n \n private void generatePerm(char[] arr, int n, String res, List<String> l){\n if(n == 0){\n l.add(res);\n return;\n }\n \n for(int i=0; i<arr.length; i++){\n if(res == "" || res.charAt(res.length()-1) != arr[i]){\n String pre=res+arr[i];\n generatePerm(arr, n-1, pre, l);\n }\n }\n \n }\n}\n```\n\nIf you have any enhancements or comments please let me know. Still learning :)! | 24 | 2 | [] | 8 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 😊 Easy Solution with BFS | Generate Happy Strings! | easy-solution-with-bfs-generate-happy-st-rnne | Intuition 💡Ahappy stringis a string that:✅ Consists only of the letters'a', 'b', 'c'.✅ No two adjacent characters are the same.Given two integersnandk, we need | lasheenwael9 | NORMAL | 2025-02-19T06:47:13.724321+00:00 | 2025-02-19T06:47:13.724321+00:00 | 2,477 | false | # Intuition 💡
A **happy string** is a string that:
✅ Consists only of the letters **'a', 'b', 'c'**.
✅ No two adjacent characters are the same.
Given two integers **n** and **k**, we need to generate a list of all **happy strings** of length **n** in **lexicographical order**, then return the **kth** string.
If there are fewer than **k** happy strings, return **""**.
---
# Approach 🛠️
We use a **BFS** (`Breadth-First Search`) approach with a queue to generate all happy strings in order.
## **Steps:**
1️⃣ Start with an empty queue.
2️⃣ Build strings level by level (length **1 → n**).
3️⃣ Ensure no two adjacent characters are the same.
4️⃣ Stop once we generate the **kth** happy string.
---
# Complexity ⏳
- **Time Complexity:**
- $$O(3^n)$$ (`Since we generate all possible happy strings`)
- **Space Complexity:**
- $$O(3^n)$$ (`Storing happy strings in queue`)
---

# Code 💻
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
if (k > (3 << (n - 1))) return ""; // Check if k is out of bounds
queue<string> q;
q.push(""); // Start with an empty string
while (k) {
string curr = q.front();
q.pop();
for (char c = 'a'; c <= 'c'; c++) {
if (curr.empty() || curr.back() != c) {
q.push(curr + c);
if (curr.size() + 1 == n) k--;
}
if (k == 0) break;
}
}
return q.back();
}
};
```
```python []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
if k > (3 << (n - 1)):
return "" # If k is too large, return empty string
queue = deque([""]) # Start with an empty string
while k:
curr = queue.popleft()
for c in "abc":
if not curr or curr[-1] != c:
queue.append(curr + c)
if len(curr) + 1 == n:
k -= 1
if k == 0:
break
return queue[-1]
```
---
# **Example Walkthrough**
## **Input:**
`n = 3, k = 9`
## **Generated Happy Strings (Sorted):**
```
1. aba
2. abc
3. aca
4. acb
5. bab
6. bac
7. bca
8. bcb
9. cab <- 9th happy string
```
### **Output:**
`"cab"`
---
### Hope this helps! 🚀 Let me know if you have any questions. 😊

| 23 | 0 | ['String', 'Backtracking', 'Breadth-First Search', 'Queue', 'Python', 'C++'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Python] 7-line DFS with yield | python-7-line-dfs-with-yield-by-yanruche-9o82 | Idea\nThe property of DFS helps us iterate through all the possibilities in ascending order automatically. All we need to do is to output the kth result.\n\nPyt | yanrucheng | NORMAL | 2020-04-18T16:01:16.066999+00:00 | 2020-04-18T16:01:16.067047+00:00 | 1,820 | false | **Idea**\nThe property of DFS helps us iterate through all the possibilities in ascending order automatically. All we need to do is to output the kth result.\n\n**Python**\n```\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n def generate(prev):\n if len(prev) == n:\n yield prev; return\n yield from (res for c in \'abc\' if not prev or c != prev[-1] for res in generate(prev + c))\n \n for i, res in enumerate(generate(\'\'), 1): \n if i == k: return res\n return \'\' \n```\n\n**Python, more readable**\n```\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n def generate(prev):\n if len(prev) == n:\n yield prev\n return\n for c in \'abc\':\n if not prev or c != prev[-1]:\n yield from generate(prev + c)\n \n for i, res in enumerate(generate(\'\'), 1): \n if i == k:\n return res\n return \'\' \n``` | 23 | 3 | [] | 5 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✅✅🔥BEATS 99.09% SIMPLEST PROGRAM | JAVA 🔥 Python 🔥 C++ & C 🔥 | Simplest Program | O(2^n) & O(n) | beats-9909-simplest-program-java-python-d8toi | IntuitionGoal is to generates the k-th lexicographically smallest "happy string" of length n. A "happy string" is defined as a string that:
Consists only of the | peEAWW4Y33 | NORMAL | 2025-02-19T16:38:52.580213+00:00 | 2025-02-19T16:38:52.580213+00:00 | 1,291 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Goal is to generates the k-th lexicographically smallest "happy string" of length n. A "happy string" is defined as a string that:
- Consists only of the characters a, b, and c
- Has no two adjacent characters that are the same.
# Approach
- `count` is to store the number of valid happy strings
- `res` is used to stores the k-th happy string when it is found.
- `(ch != lastChar)` Ensures the new character ch is not the same as lastChar (prevents adjacent duplicates)
- Append ch to sb to extend the string.
- Recurse by calling `backtrack(n, k, sb, ch)`.
- Backtrack by removing the last character `(sb.setLength(sb.length() - 1))` after recursion returns.
# Complexity
- Time complexity: **O(2^n)**
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: **O(n)**
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# PLS UPVOTE ⬆️
# PLS UPVOTE ⬆️
# PLS UPVOTE ⬆️

# Code
```java []
class Solution {
static int count = 0;
static String res = "";
public String getHappyString(int n, int k) {
count = 0;
res = "";
backtrack(n, k, new StringBuilder(), ' ');
return res;
}
private static void backtrack(int n, int k, StringBuilder sb, char lastChar) {
if(sb.length() == n) {
if(++count == k) {
res = sb.toString();
}
return;
}
char[] chars = {'a', 'b', 'c'};
for(int i = 0 ; i < chars.length ; i++) {
char c = chars[i];
if(c != lastChar) {
sb.append(c);
backtrack(n,k,sb,c);
sb.setLength(sb.length()-1);
if(!res.isEmpty()) return;
}
}
}
}
```
```Python []
class Solution:
def __init__(self):
self.count = 0
self.res = ""
def getHappyString(self, n: int, k: int) -> str:
self.count = 0
self.res = ""
self.backtrack(n, k, [], ' ')
return self.res
def backtrack(self, n, k, sb, lastChar):
if len(sb) == n:
self.count += 1
if self.count == k:
self.res = "".join(sb)
return
for c in ['a', 'b', 'c']:
if c != lastChar:
sb.append(c)
self.backtrack(n, k, sb, c)
sb.pop()
if self.res:
return
```
```C++ []
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int count = 0;
string res = "";
string getHappyString(int n, int k) {
count = 0;
res = "";
string sb = "";
backtrack(n, k, sb, ' ');
return res;
}
private:
void backtrack(int n, int k, string &sb, char lastChar) {
if (sb.length() == n) {
if (++count == k) {
res = sb;
}
return;
}
char chars[] = {'a', 'b', 'c'};
for (int i = 0; i < 3; i++) {
char c = chars[i];
if (c != lastChar) {
sb.push_back(c);
backtrack(n, k, sb, c);
sb.pop_back();
if (!res.empty()) return;
}
}
}
};
```
```C []
#include <stdio.h>
#include <string.h>
int count = 0;
char res[11] = ""; // Max length n = 10
void backtrack(int n, int k, char sb[], int len, char lastChar) {
if (len == n) {
count++;
if (count == k) {
sb[len] = '\0';
strcpy(res, sb);
}
return;
}
char chars[] = {'a', 'b', 'c'};
for (int i = 0; i < 3; i++) {
char c = chars[i];
if (c != lastChar) {
sb[len] = c;
backtrack(n, k, sb, len + 1, c);
if (res[0] != '\0') return; // Early exit
}
}
}
char* getHappyString(int n, int k) {
count = 0;
res[0] = '\0'; // Reset result
char sb[11] = "";
backtrack(n, k, sb, 0, ' ');
return res;
}
``` | 21 | 0 | ['String', 'Backtracking', 'C', 'Python', 'C++', 'Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Most Optimal Solution ✅ C++| Java | Python | JavaScript | most-optimal-solution-c-java-python-java-aqcn | ⬆️Upvote if it helps ⬆️Connect with me on Linkedin [Bijoy Sing]Solution in C++, Python, Java, and JavaScriptHere’s a detailed explanation of the solution:Intuit | BijoySingh7 | NORMAL | 2025-02-19T07:08:37.802730+00:00 | 2025-02-19T07:08:37.802730+00:00 | 2,082 | false | # ⬆️Upvote if it helps ⬆️
---
## Connect with me on Linkedin [Bijoy Sing]
---
###### *Solution in C++, Python, Java, and JavaScript*
```cpp []
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
string getHappyString(int n, int k) {
queue<string> q;
q.push("a");
q.push("b");
q.push("c");
vector<string> happyStrings;
while (!q.empty()) {
string s = q.front();
q.pop();
if (s.size() == n) {
happyStrings.push_back(s);
continue;
}
for (char ch : {'a', 'b', 'c'}) {
if (s.back() != ch) {
q.push(s + ch);
}
}
}
return k > happyStrings.size() ? "" : happyStrings[k - 1];
}
};
```
```python []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
from collections import deque
q = deque(["a", "b", "c"])
happy_strings = []
while q:
s = q.popleft()
if len(s) == n:
happy_strings.append(s)
continue
for ch in "abc":
if s[-1] != ch:
q.append(s + ch)
return "" if k > len(happy_strings) else happy_strings[k - 1]
```
```java []
import java.util.*;
class Solution {
public String getHappyString(int n, int k) {
Queue<String> q = new LinkedList<>();
q.offer("a");
q.offer("b");
q.offer("c");
List<String> happyStrings = new ArrayList<>();
while (!q.isEmpty()) {
String s = q.poll();
if (s.length() == n) {
happyStrings.add(s);
continue;
}
for (char ch : new char[]{'a', 'b', 'c'}) {
if (s.charAt(s.length() - 1) != ch) {
q.offer(s + ch);
}
}
}
return k > happyStrings.size() ? "" : happyStrings.get(k - 1);
}
}
```
```javascript []
class Solution {
getHappyString(n, k) {
let q = ["a", "b", "c"];
let happyStrings = [];
while (q.length) {
let s = q.shift();
if (s.length === n) {
happyStrings.push(s);
continue;
}
for (let ch of ["a", "b", "c"]) {
if (s[s.length - 1] !== ch) {
q.push(s + ch);
}
}
}
return k > happyStrings.length ? "" : happyStrings[k - 1];
}
}
```
Here’s a detailed explanation of the solution:
---
## **Intuition**
The problem requires us to generate all "happy strings" of length `n` in lexicographical order and return the `k`-th string (if it exists).
A "happy string" is one that:
- Consists of only `a`, `b`, and `c`.
- No two adjacent characters are the same.
A brute-force approach would generate all possible strings of length `n` and filter the valid ones, but that would be inefficient. Instead, we can use **BFS (Breadth-First Search) with a queue** to systematically build happy strings in lexicographical order.
---
## **Approach**
1. **Use a queue (`q`) to generate happy strings level by level**
- Start with the three single-character strings: `"a"`, `"b"`, and `"c"`.
- Expand each string by appending `a`, `b`, or `c` while ensuring **no two adjacent characters are the same**.
- Stop when we reach strings of length `n`.
2. **Store valid happy strings in a list (`happyStrings`)**
- Once a string reaches length `n`, add it to the list.
- Continue processing until the queue is empty.
3. **Return the `k`-th happy string (if it exists)**
- If `k` is greater than the number of generated strings, return an **empty string (`""`)**.
- Otherwise, return `happyStrings[k - 1]` (since indexing is 0-based).
---
## **Complexity Analysis**
- **Time Complexity:**
- The number of happy strings of length `n` is at most **2 × 3^(n-1)**.
- Since we use BFS and generate each valid string once, the time complexity is **O(3^n)** in the worst case.
- **Space Complexity:**
- We store all valid happy strings, so the space complexity is **O(3^n)** in the worst case.
- The queue also holds intermediate strings, contributing to the space usage.
---
### 🚀 *If you have any questions or need further clarification, feel free to drop a comment! 😊* | 20 | 1 | ['String', 'Backtracking', 'Queue', 'Heap (Priority Queue)', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python3 O(n) solution using math with clear explanation | python3-on-solution-using-math-with-clea-tdix | let\'s consider n=3 and k=9\nThe lexicographical order of the strings are ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]\n | dark_wolf_jss | NORMAL | 2020-06-08T03:23:38.758499+00:00 | 2020-06-08T03:23:38.758534+00:00 | 1,612 | false | let\'s consider n=3 and k=9\nThe lexicographical order of the strings are ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]\n\nWe can observe that each element a,b,c has repeated 2**(n-1) times as the first character which is 4 in our case they are ["aba", "abc", "aca", "acb"], ["bab", "bac", "bca", "bcb"], ["cab", "cac", "cba", "cbc"]\n\nWe can also observe that total number of permutations are 3*(2**(n-1)) which 12 in our case.\n\n\n```\nfrom math import ceil\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n single_ele = 2**(n-1)\n if k>3*single_ele:\n return ""\n result = [\'a\',\'b\',\'c\'][ceil(k/single_ele)-1]\n while single_ele>1:\n k = (k-1)%single_ele +1\n single_ele = single_ele//2\n if result[-1]==\'a\':\n result+=[\'b\',\'c\'][ceil(k/single_ele)-1]\n elif result[-1]==\'b\':\n result+=[\'a\',\'c\'][ceil(k/single_ele)-1]\n else:\n result+=[\'a\',\'b\'][ceil(k/single_ele)-1]\n return result\n``` | 19 | 0 | ['Math', 'Python3'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Java O(n) solution | java-on-solution-by-chenwei713-zbmz | \nclass Solution {\n public String getHappyString(int n, int k) {\n if(n == 0) {\n return "";\n }\n \n // K is too lar | chenwei713 | NORMAL | 2020-04-18T16:39:19.692023+00:00 | 2020-04-18T16:39:19.692156+00:00 | 1,608 | false | ```\nclass Solution {\n public String getHappyString(int n, int k) {\n if(n == 0) {\n return "";\n }\n \n // K is too large\n if(k > (int)3 * Math.pow(2, n - 1)) {\n return "";\n }\n \n // Make K start from 0\n k--;\n \n StringBuilder sb = new StringBuilder();\n Map<Character, char[]> map = new HashMap<>();\n map.put(\' \', new char[]{\'a\', \'b\', \'c\'});\n map.put(\'a\', new char[]{\'b\', \'c\'});\n map.put(\'b\', new char[]{\'a\', \'c\'});\n map.put(\'c\', new char[]{\'a\', \'b\'});\n \n char prev = \' \';\n while(n > 1) {\n int nextAmount = (int)Math.pow(2, n - 1);\n int rank = k / nextAmount;\n \n sb.append(map.get(prev)[rank]);\n prev = map.get(prev)[rank];\n k = k % nextAmount;\n \n n--;\n }\n \n // n == 1\n sb.append(map.get(prev)[k]);\n return sb.toString(); \n }\n}\n``` | 16 | 3 | [] | 5 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 🔥BEATS 💯 % 🎯 |✨SUPER EASY BEGINNERS 👏| JAVA | C | C++ | PYTHON| JAVASCRIPT | DART | beats-super-easy-beginners-java-c-c-pyth-a90w | IntuitionThe problem requires generating lexicographically sorted "happy strings" of lengthnusing the characters'a','b', and'c'. Ahappy stringis defined as a st | CodeWithSparsh | NORMAL | 2025-02-19T08:42:23.529110+00:00 | 2025-02-19T08:42:23.529110+00:00 | 1,314 | false | 
---
# **Intuition**
The problem requires generating lexicographically sorted "happy strings" of length **n** using the characters `'a'`, `'b'`, and `'c'`. A **happy string** is defined as a string where **no two adjacent characters are the same**.
- The approach involves generating **all possible happy strings** of length **n** and **sorting** them lexicographically.
- Finally, we return the **k-th** happy string if it exists, otherwise return `""`.
---
# **Approach**
1. **Backtracking to Generate Happy Strings**
- Use recursion to generate all possible **happy strings** of length **n**.
- At each step, **append only those characters** that do not repeat the last character.
- Store the valid strings in a list (`happy`).
2. **Retrieve the k-th Happy String**
- Since we generate strings **in lexicographical order**, we can directly return the `k-th` element from the list.
- If `k` is greater than the number of generated strings, return `""`.
---
# **Complexity Analysis**
- **Time Complexity:**
- The number of valid strings is **O(2^n)** since at each step we choose between 2 options (excluding repetition).
- **Generating the list** takes **O(2^n)** time.
- **Retrieving the k-th element** is **O(1)**.
- **Overall complexity:** **O(2^n)**.
- **Space Complexity:**
- **O(2^n)** for storing the strings.
- **O(n)** for recursive calls.
- **Overall complexity:** **O(2^n)**.
---
```dart []
class Solution {
List<String> happy = [];
String getHappyString(int n, int k) {
List<String> chars = ['a', 'b', 'c'];
void generateHappyString(String path) {
if (path.length == n) {
happy.add(path);
return;
}
for (int i = 0; i < chars.length; i++) {
if (path.isEmpty || path[path.length - 1] != chars[i]) {
generateHappyString(path + chars[i]);
}
}
}
generateHappyString('');
return k > happy.length ? '' : happy[k - 1];
}
}
```
```java []
import java.util.*;
class Solution {
List<String> happy = new ArrayList<>();
public String getHappyString(int n, int k) {
char[] chars = {'a', 'b', 'c'};
generateHappyString("", n, chars);
return k > happy.size() ? "" : happy.get(k - 1);
}
private void generateHappyString(String path, int n, char[] chars) {
if (path.length() == n) {
happy.add(path);
return;
}
for (char c : chars) {
if (path.isEmpty() || path.charAt(path.length() - 1) != c) {
generateHappyString(path + c, n, chars);
}
}
}
}
```
```python []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
happy = []
chars = ['a', 'b', 'c']
def backtrack(path):
if len(path) == n:
happy.append("".join(path))
return
for c in chars:
if not path or path[-1] != c:
backtrack(path + [c])
backtrack([])
return "" if k > len(happy) else happy[k - 1]
```
```cpp []
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> happy;
string getHappyString(int n, int k) {
string chars = "abc";
generateHappyString("", n, chars);
return k > happy.size() ? "" : happy[k - 1];
}
void generateHappyString(string path, int n, string &chars) {
if (path.length() == n) {
happy.push_back(path);
return;
}
for (char c : chars) {
if (path.empty() || path.back() != c) {
generateHappyString(path + c, n, chars);
}
}
}
};
```
```javascript []
var getHappyString = function(n, k) {
let happy = [];
let chars = ['a', 'b', 'c'];
function generateHappyString(path) {
if (path.length === n) {
happy.push(path);
return;
}
for (let c of chars) {
if (!path || path[path.length - 1] !== c) {
generateHappyString(path + c);
}
}
}
generateHappyString('');
return k > happy.length ? "" : happy[k - 1];
};
```
---
# **Summary**
| Language | Time Complexity | Space Complexity |
|-----------|----------------|----------------|
| **Dart** | **O(2^n)** | **O(2^n)** |
| **Java** | **O(2^n)** | **O(2^n)** |
| **Python** | **O(2^n)** | **O(2^n)** |
| **C++** | **O(2^n)** | **O(2^n)** |
| **JavaScript** | **O(2^n)** | **O(2^n)** |
---
# **Final Thoughts**
✅ **Backtracking ensures all valid happy strings are generated**
✅ **Lexicographically ordered by default**
✅ **O(2^n) complexity is feasible for small `n` (up to ~20)**
✅ **Alternative Approach:** Using **binary indexing** to construct the k-th happy string directly for better performance 🚀
----
 {:style='width:250px'} | 15 | 0 | ['String', 'Backtracking', 'C', 'C++', 'Java', 'Python3', 'JavaScript', 'Dart'] | 3 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Video solution | Intuition and Approach explained in detail | C++ | Backtracking | video-solution-intuition-and-approach-ex-frtt | Hello every one i have created a video solution for this problem and solved this video by developing intutition for backtracking (its in hindi), i am pretty sur | _code_concepts_ | NORMAL | 2024-04-30T05:38:52.795287+00:00 | 2024-04-30T05:39:42.974978+00:00 | 587 | false | Hello every one i have created a video solution for this problem and solved this video by developing intutition for backtracking (its in hindi), i am pretty sure you will never have to look for solution for this video ever again after watching this.\n\n\nThis video is the part of my playlist "Master backtracking".\nVideo Link: https://youtu.be/FoJGFhHuCog\n\n# Code\n```\nclass Solution {\npublic:\n void helper(vector<string> &ans, int n,int k, string &temp,vector<char> &inp){\n if(ans.size()==k){\n return;\n }\n if(temp.size()==n){\n ans.push_back(temp);\n return;\n }\n for(int i=0;i<3;i++){\n if(temp.size()==0 || temp.back()!=inp[i]){\n temp.push_back(inp[i]);\n helper(ans,n,k,temp,inp);\n temp.pop_back();\n }\n }\n return;\n\n }\n string getHappyString(int n, int k) {\n string temp="";\n vector<char> inp={\'a\',\'b\',\'c\'};\n vector<string> ans;\n helper(ans,n,k,temp,inp);\n if(ans.size()==k){\n return ans.back();\n }\n return "";\n }\n};\n``` | 15 | 0 | ['C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✅✅100% Beats || Simple Backtracking Approach | 100-beats-simple-backtracking-approach-b-cdoj | IntuitionA "happy string" of lengthnconsists of charactersa,b, andcsuch that no two adjacent characters are the same. To find thek-th lexicographically smallest | arunk_leetcode | NORMAL | 2025-02-19T04:15:46.378656+00:00 | 2025-02-19T04:15:46.378656+00:00 | 5,217 | false | # Intuition
A "happy string" of length `n` consists of characters `a`, `b`, and `c` such that no two adjacent characters are the same. To find the `k`-th lexicographically smallest happy string, we can generate all valid strings in lexicographical order and return the `k`-th one.
# Approach
1. Use **recursive backtracking** approach to generate happy strings of length `n`.
2. Maintain **counter (`cnt`)** to track the number of happy strings generated.
3. If the current string reaches length `n`, decrement `cnt` and check if it is the `k`-th string.
4. Use **set of allowed characters `{a, b, c}`** and ensure no two adjacent characters are the same.
5. Stop recursion early once the `k`-th string is found to optimize performance.
# Complexity
- **Time Complexity:**
$$O(3^n)$$ in the worst case, as each position in the string has 3 choices. However, early termination optimizes this in practice.
- **Space Complexity:**
$$O(n)$$ for the recursion stack depth.
# Code
```cpp []
class Solution {
public:
string ans;
void solve(int len, int& cnt, int n, vector<char>& v, string& s) {
if (len == n) {
if (--cnt == 0) {
ans = s;
}
return;
}
for (int i = 0; i < 3; i++) {
if (len == 0 || s.back() != v[i]) {
s.push_back(v[i]);
solve(len + 1, cnt, n, v, s);
s.pop_back();
if (cnt == 0) return;
}
}
}
string getHappyString(int n, int k) {
vector<char> v = {'a', 'b', 'c'};
ans = "";
string s;
solve(0, k, n, v, s);
return ans;
}
};
```
```Java []
class Solution {
private String ans = "";
private void solve(int len, int[] cnt, int n, char[] chars, StringBuilder s) {
if (len == n) {
if (--cnt[0] == 0) {
ans = s.toString();
}
return;
}
for (char c : chars) {
if (len == 0 || s.charAt(len - 1) != c) {
s.append(c);
solve(len + 1, cnt, n, chars, s);
s.deleteCharAt(s.length() - 1);
if (cnt[0] == 0) return; // Stop recursion early
}
}
}
public String getHappyString(int n, int k) {
ans = "";
solve(0, new int[]{k}, n, new char[]{'a', 'b', 'c'}, new StringBuilder());
return ans;
}
}
```
```Python []
class Solution:
def __init__(self):
self.ans = ""
def solve(self, length, k, n, chars, s):
if length == n:
k[0] -= 1
if k[0] == 0:
self.ans = s
return
for c in chars:
if length == 0 or s[-1] != c:
self.solve(length + 1, k, n, chars, s + c)
if k[0] == 0:
return # Stop recursion early
def getHappyString(self, n: int, k: int) -> str:
self.ans = ""
self.solve(0, [k], n, ['a', 'b', 'c'], "")
return self.ans
```
| 14 | 0 | ['String', 'Backtracking', 'Python', 'C++', 'Java', 'Python3'] | 5 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simple Java solution::Backtracking | simple-java-solutionbacktracking-by-2018-jwga | DO UPVOTE INCASE YOU FIND IT HELPFUL!\n```\nclass Solution {\n List list=new ArrayList<>();\n StringBuilder sb = new StringBuilder();\n public String g | 20184152 | NORMAL | 2021-06-05T02:12:47.713459+00:00 | 2021-06-05T02:12:47.713489+00:00 | 1,462 | false | DO UPVOTE INCASE YOU FIND IT HELPFUL!\n```\nclass Solution {\n List<String> list=new ArrayList<>();\n StringBuilder sb = new StringBuilder();\n public String getHappyString(int n, int k) {\n backtrack(n,\' \');\n Collections.sort(list);\n if(list.size()<k) return "";\n else return list.get(k-1);\n }\n void backtrack(int n, char prev){\n if(sb.length()==n){\n list.add(sb.toString());\n return;\n }\n else{\n for(char ch=\'a\';ch<=\'c\';ch++){\n if(ch!=prev){\n sb.append(ch);\n backtrack(n,ch);\n sb.delete(sb.length()-1,sb.length());\n }\n \n }\n }\n }\n} | 14 | 1 | ['Backtracking', 'Java'] | 5 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | backtracking||beats 99.64%|| | backtrackingbeats-9964-by-srujitha_vutla-0xyx | \nthis question is similar to https://leetcode.com/problems/letter-tile-possibilities/\n 1.one of the possible way to solve this question is generating all stri | srujitha_vutla | NORMAL | 2024-02-18T04:39:26.342639+00:00 | 2024-02-18T04:39:26.342657+00:00 | 328 | false | \nthis question is similar to https://leetcode.com/problems/letter-tile-possibilities/\n 1.one of the possible way to solve this question is generating all strings of length n and returning kth string\n 2.here i generated only k strings(stored kth string in res variable) and then returned true to stop further recursion\n | 13 | 1 | [] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python 3 || 9 lines, binary map w/ example || T/S: 98% / 99% | python-3-9-lines-binary-map-w-example-ts-st2m | https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/submissions/937031498/updated run 2/18/2025I could be wrong, but | Spaulding_ | NORMAL | 2023-04-20T17:54:08.220366+00:00 | 2025-02-19T00:23:42.400658+00:00 | 629 | false | ```
class Solution:
def getHappyString(self, n: int, k: int) -> str:
d = {'a':'bc','b':'ac','c':'ab'} # Example: n = 5, k = 20
div,r = divmod(k-1,2**(n-1)) # div,r = divmod(19,16) = 1,3
if div > 2: return ''
prev = ans = 'abc'[div] # prev = ans = 'b'
r = list(map(int,bin(r)[2:].rjust(n-1,'0'))) # r = map(int, '0011') = [0,0,1,1]
for i in range(n-1): # i r[i] d[prev][r[i]] ans
prev = d[prev][r[i]] --- --- --------- ------
ans+= prev # 'b'
# 0 0 d['b'][0] = 'a' 'ba'
return ans # 1 0 d['a'][0] = 'b' 'bab'
# 2 1 d['b'][1] = 'c' 'babc'
# 3 1 d['c'][1] = 'b' 'babcb'
```
[https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/submissions/937031498/](https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/submissions/937031498/)
[updated run 2/18/2025](https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/?envType=daily-question&envId=2025-02-19)
I could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `n`.
| 13 | 0 | ['Python3'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [C++] Straightforward DFS. Skip appending same char. | c-straightforward-dfs-skip-appending-sam-n0kk | \nUPDATE:\n\nAfter contest, I think we can avoid storing all the strings in the vector, but only keep the pontential result string(cur).\nScroll down to check f | xzj104 | NORMAL | 2020-04-18T16:01:08.120985+00:00 | 2020-04-19T02:25:45.824417+00:00 | 1,491 | false | \n***UPDATE:***\n\nAfter contest, I think we can avoid storing all the strings in the vector, but only keep the pontential result string(cur).\nScroll down to check first solution.\n```\nclass Solution {\npublic:\n string getHappyString(int n, int k) {\n string cur = "";\n left = k;\n dfs(cur, n);\n return res;\n }\n \n void dfs(string& cur, int n) {\n if(res.size() || cur.size() == n) {\n if(--left == 0)\n res = cur;\n return;\n }\n \n for(int i = 0; i < 3; ++i) {\n if(cur.empty() || cur.back() != abc[i]) {\n cur.push_back(abc[i]);\n dfs(cur, n);\n cur.pop_back();\n }\n }\n }\nprivate:\n string res = "";\n int left;\n vector<char> abc{\'a\', \'b\', \'c\'}; \n};\n```\n\nSince k is not large, use DFS to generate all string.\nIn this question , we need to avoid appending a same char as the last one in current string. And we can stop when we have k strings generated.\n\n```\nclass Solution {\npublic:\n string getHappyString(int n, int k) {\n string cur = "";\n vector<char> chars{\'a\', \'b\', \'c\'};\n dfs(cur, chars, n, k);\n \n return res.size() == k ? res.back() : "";\n }\n\n void dfs(string& cur, vector<char>& chars, int n, int k) {\n if(res.size() == k)\n return;\n if(cur.size() == n) {\n res.push_back(cur);\n return;\n }\n \n for(int i = 0; i < 3; ++i) {\n //only append different char\n if(cur.empty() || (cur.back() != chars[i])) {\n cur.push_back(chars[i]);\n dfs(cur, chars, n, k);\n cur.pop_back();\n }\n }\n }\n \nprivate:\n vector<string> res;\n};\n```\n | 13 | 1 | [] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Java] Concise and clean solution, imagine problem as a tree, 0ms. | java-concise-and-clean-solution-imagine-24li0 | Update\nChanged string concatenation to StringBuilder. Performance gain from 11ms to 0ms.\n\n### Solution\n\nMy idea was to imagine the problem as a tree:\n1. O | hydro_0 | NORMAL | 2020-04-19T08:59:18.643865+00:00 | 2020-04-20T08:49:17.911962+00:00 | 1,184 | false | ### Update\nChanged string concatenation to `StringBuilder`. Performance gain from `11ms` to `0ms`.\n\n### Solution\n\nMy idea was to imagine the problem as a tree:\n1. On the first step we have three branches: `a`, `b` and `c`.\n2. On each next step we have two branches: if node is `a`: `b` and `c`, for `b`: `a` and `c` and for `c`: `a` and `b`.\n\nWe can see that number of solutions is evenly distributed among all branches on each step. What we can also say is that each branch has `2^(n-1)` elements in total, as each branch is perfect binary tree, you can easily see it when you will draw the problem on the paper.\n\nGIven this, our problem is converted to the more understandable one: find the number in perfect binary tree with one small difference that the very first node has three branches.\n\n```java\nclass Solution {\n private static final char[] CHARS = new char[] { \'a\', \'b\', \'c\' };\n public String getHappyString(int n, int k) {\n\t StringBuilder sb = new StringBuilder();\n\t build(n, \'-\', k, sb); // first we have fake `-` as parameter, so all `a`, `b` and `c` are valid as a first letter\n\t return sb.toString();\n }\n \n private static void build(int n, char last, int k, StringBuilder sb) {\n if (n == 0) {\n return; // we have reached the leaf\n }\n int step = 1 << (n - 1); // number of elements in each branch, which is perfect binary tree\n int to = step;\n for (char c : CHARS) {\n if (c == last) continue; // we can\'t have two same letters in row\n if (k <= to) {\n build(n - 1, c, k - (to - step), sb.append(c)); // get the child tree and deduct the number of elements in left branch from k, if `to` is the right boundary of current branch, then (to-step) is the right boundary of the left branch, which is the number of all elements in it\n\t\t\t\treturn;\n }\n to += step;\n }\n }\n}\n```\n\nWith this approach the problem could easily be extended to larger number of characters. Then you will have to change the `CHARS` array and line `int step = 1 << (n - 1);` to calculate the number of elements in perfect tree with more branches, which is basically `(CHARS.length-1)^(n-1)`, cause each node can have all other characters except the current one. | 11 | 0 | ['Tree', 'Java'] | 5 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 0 ms. O(n). No branching. Combinatorics. Beats 100.00% | 0-ms-no-branching-combinatorics-beats-10-r6xm | IntuitionA beautiful problem with a beautiful solution. The first letter is chosen from threea,borc. The second and subsequent letters are chosen from the two r | nodeforce | NORMAL | 2025-02-19T09:26:40.815954+00:00 | 2025-02-19T15:23:12.097402+00:00 | 905 | false | # Intuition
A beautiful problem with a beautiful solution. The first letter is chosen from three `a`, `b` or `c`. The second and subsequent letters are chosen from the two remaining. If we denote it as `0` or `1`. Which brings us to the binary code of the number.
# Approach
First, let's calculate the number of happy strings of length `n`. In the first place is one of three letters, in the second and subsequent ones - one of two. That is, $$m = 3 * 2 * 2 * ... * 2$$, or $$ m = 3 * 2^{n-1}$$. If `k` is greater than `m`, then return an empty string.
The first letter is chosen from three, it divides all the strings into three subsets. The smaller strings correspond to the smaller letter, i.e. the letter `a`, the middle ones to the letter `b`, and the large ones to the letter `c`. We need to understand to which third of the `m` the `k` belongs: to the first, second or third. This can be done like this: $$k > m / 3$$ and $$k > 2 * m / 3$$.
And the last. The second and subsequent letters divide the strings each time into two subsets. Larger subsets correspond to a larger letter, and smaller ones to a smaller one. This is the same as the binary representation of a number. Where there is `1` in the binary representation, there will be a larger letter, and where there is `0`, there will be a smaller one. The larger and smaller letters depend on the previous letter. For example, if the first letter is `b`, then the second will be `a` or `c`, where `a` will be smaller, and `c` will be larger. If the second letter is `c`, then the choice will be between `a` and `b`.
Let's represent what is written above in the form of a table for selecting the next letter based on the previous one:
| previous | smaller | larger |
|----------|----------|----------|
| a | b | c |
| b | a | c |
| c | a | b |
If we denote the letters by numbers `a, b, c = 0, 1, 2`, and the smaller and larger as `0` and `1`, we get a table `t`, which is used in the code. The table allows you to avoid branches and makes the code not only clear, but also fast. `0 ms` even in JavaScript.


# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
const int m = 3 << (n - 1);
if (m < k) return "";
int t[3][2] = {{1, 2}, {0, 2}, {0, 1}};
string s(n, 'a');
s[0] += (k > m / 3) + (k > 2 * m / 3);
--k;
for (int i = 1; i < n; ++i)
s[i] += t[s[i - 1] - 97][(k & (1 << (n - i - 1))) > 0];
return s;
}
};
```
```c []
char* getHappyString(int n, int k) {
const int m = 3 << (n - 1);
if (m < k) return "";
int t[3][2] = {{1, 2}, {0, 2}, {0, 1}};
char* s = (char*)malloc(n + 1);
s[n] = '\0';
memset(s, 'a', n);
s[0] += (k > m / 3) + (k > 2 * m / 3);
--k;
for (int i = 1; i < n; ++i)
s[i] += t[s[i - 1] - 97][(k & (1 << (n - i - 1))) > 0];
return s;
}
```
```javascript []
const getHappyString = (n, k) => {
const m = 3 << (n - 1);
if (m < k) return '';
const t = [[1, 2], [0, 2], [0, 1]];
const a = new Uint8Array(n).fill(97);
a[0] += (k > m / 3) + (k > 2 * m / 3);
--k;
for (let i = 1; i < n; ++i)
a[i] += t[a[i - 1] - 97][+((k & (1 << (n - i - 1))) > 0)];
return String.fromCharCode(...a);
};
``` | 10 | 0 | ['String', 'C', 'Combinatorics', 'Bitmask', 'Python', 'C++', 'Java', 'TypeScript', 'Python3', 'JavaScript'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python | Simple Backtracking | O(2^n), O(n) | Beats 100% | python-simple-backtracking-on-2n-on-beat-jflm | CodeComplexity
Time complexity:O(2n). backtrack() tries to make every happy string, 3∗2n−1total since 3 characters in first index and 2 for remaining, simplifi | 2pillows | NORMAL | 2025-02-19T01:01:34.455611+00:00 | 2025-02-19T04:39:29.875289+00:00 | 1,229 | false | # Code
```python3 []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
count = 0 # tracks number of completed strings made
def backtrack(i, chars):
nonlocal count
if i == n:
count += 1 # finished a string
return "".join(chars) if count == k else "" # return string if it's k string, else ""
for c in "abc": # a,b,c ensures lexicographical order
if chars and chars[-1] == c: continue # prev char can't equal current
res = backtrack(i + 1, chars + [c]) # add char and make rest of string
if res:
return res # found k string
return "" # never found k string
return backtrack(0, [])
```
# Complexity
- Time complexity: $$O(2^n)$$. backtrack() tries to make every happy string, $$\ 3 * 2^{n-1}$$ total since 3 characters in first index and 2 for remaining, simplifies to $$\ 2^n$$. backtrack() has constant time except for single join() which has n time. Overall time is $$\ 2^n + n$$, simplifies to $$\ 2^n$$.
- Space complexity: $$O(n)$$. Based on maximum recursion depth, n chars so n calls of backtrack() to make full string.
# Performance

| 10 | 1 | ['String', 'Backtracking', 'Python3'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | C++ BFS Without using sort. | c-bfs-without-using-sort-by-abhinandanka-dinw | \n string getHappyString(int n, int k) {\n vector<string> all;\n queue<string> q;\n q.push("a");\n q.push("b");\n q.push(" | abhinandankainth1999 | NORMAL | 2020-04-18T20:22:41.690075+00:00 | 2020-04-18T20:22:41.690119+00:00 | 504 | false | ```\n string getHappyString(int n, int k) {\n vector<string> all;\n queue<string> q;\n q.push("a");\n q.push("b");\n q.push("c");\n int t = n;\n while(t--){\n int sz = q.size();\n while(sz--){\n string s = q.front();\n q.pop();\n if(s.size()==n)\n all.push_back(s);\n for(auto i = \'a\';i<=\'c\';i++){\n if(s.back()!=i){\n s += i;\n q.push(s);\n s.pop_back();\n }\n }\n \n }\n }\n \n if(k>all.size())\n return {};\n return all[k-1];\n \n }\n``` | 10 | 0 | [] | 3 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 🚀 Beats 100% | Simple & Efficient O(n) Solution | No Backtracking Needed! 🚀 | beats-100-simple-efficient-on-solution-n-28j4 | IntuitionThe intuition behind this code is to efficiently determine thek-th lexicographically smallest happy stringwithout generating all possible strings.
Und | aayush8910sh | NORMAL | 2025-02-19T05:55:34.814464+00:00 | 2025-02-19T05:55:34.814464+00:00 | 402 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The intuition behind this code is to efficiently determine the **k-th lexicographically smallest happy string** without generating all possible strings.
1. **Understanding the Pattern**:
- A happy string of length `n` follows a structured pattern where the first character can be `{a, b, c}`, and each subsequent character has only **two choices** (to avoid repetition).
- The total number of valid happy strings is `3 * 2^(n-1)`, forming a structured sequence.
2. **Directly Finding the k-th String**:
- Instead of generating all strings, we mathematically determine each character one by one.
- The first character is chosen by dividing the total count into three equal parts.
- For each next character, we use a **binary decision process**:
- If `k` falls in the first half of the remaining choices, pick the smaller valid character.
- Otherwise, pick the other option and adjust `k`.
3. **Efficient Execution**:
- By iteratively reducing `k` and updating the choice space, we construct the answer **step by step**, achieving an **O(n) solution** instead of brute force.
# Approach
<!-- Describe your approach to solving the problem. -->
The code efficiently finds the `k-th` lexicographically smallest **happy string** of length `n` (a string of `{a, b, c}` where no adjacent characters are the same).
1. **Count Total Strings** → `3 * 2^(n-1)`. If `k` exceeds this, return `""`.
2. **Choose First Character** → Since the first letter can be `{a, b, c}`, divide the total into 3 equal parts to pick the correct letter.
3. **Build the Rest** → Each position has 2 choices (ensuring no adjacent repetition). Divide remaining possibilities and pick accordingly.
4. **Update `k` & Repeat** → Narrow down choices step by step using `powtwo >>= 1`.
This avoids generating all strings explicitly and finds the answer in **O(n) time**. 🚀

# Complexity
- Time complexity: **O(n) time**. 🚀
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
int total = 3 * (1 << (n - 1));
k--;
if (k >= total) return "";
string answer;
int powtwo = 1 << (n - 1);
answer.push_back('a' + (k / powtwo));
k %= powtwo;
for (int i = 1; i < n; i++) {
powtwo >>= 1;
char prev = answer.back();
if (k / powtwo == 0) {
answer.push_back(prev == 'a' ? 'b' : 'a');
} else {
answer.push_back(prev == 'c' ? 'b' : 'c');
}
k %= powtwo;
}
return answer;
}
};
``` | 9 | 0 | ['Math', 'Bit Manipulation', 'C++'] | 3 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Easy to understand cpp solution | easy-to-understand-cpp-solution-by-vp-krf8 | we will check if our previous character is not the same as the current one. If not, we will push the current character. This is the same condition as the happy | Vp- | NORMAL | 2021-07-22T12:36:00.155991+00:00 | 2021-07-22T12:36:00.156052+00:00 | 540 | false | we will check if our previous character is not the same as the current one. If not, we will push the current character. This is the same condition as the happy string.\n\n```cpp\nclass Solution {\npublic:\n void helper(int n,string check,vector<string>& ans)\n {\n if(n == 0){\n ans.push_back(check);\n return;\n }\n \n if(check.back() != \'a\') helper(n - 1, check + \'a\', ans);\n if(check.back() != \'b\') helper(n - 1, check + \'b\', ans);\n if(check.back() != \'c\') helper(n - 1, check + \'c\', ans);\n }\n \n string getHappyString(int n, int k)\n {\n vector<string> ans;\n \n helper(n, "", ans);\n \n if(k > ans.size()) return "";\n \n return ans[--k];\n }\n};\n```\n\nFeel free to give your suggestions or correct me in the comments. Thanks for reading.\uD83D\uDE43 | 9 | 0 | ['C++'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Easy Approach || Recursion | easy-approach-recursion-by-muhammednihas-fbqe | IntuitionThe problem requires us to generate lexicographically sorted "happy strings" of lengthnand return thek-th one. A happy string is defined as a string co | muhammednihas2218 | NORMAL | 2025-02-19T04:37:19.326680+00:00 | 2025-02-21T05:09:36.998083+00:00 | 795 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires us to generate lexicographically sorted "happy strings" of length `n` and return the `k`-th one. A happy string is defined as a string containing only the characters `a`, `b`, and `c` with no two adjacent characters being the same.
To solve this, we can use **backtracking** to generate all possible happy strings and store them in a list. Since we are adding characters in lexicographical order, the list will naturally contain the happy strings in sorted order.
# Approach
<!-- Describe your approach to solving the problem. -->
* **Example**:
\

1. **Backtracking to Generate Happy Strings:**
* Start with an empty string `current`.
* At each step, iterate through `['a', 'b', 'c']` and append a character to `current` only **if it does not match the last character** (to ensure no adjacent characters are the same).
* Recursively continue this process until `current` reaches length `n`.
* If a valid happy string is generated, add it to the list happy_strings.
2. **Returning the k-th Happy String:**
* Once all possible happy strings of length `n` are generated, check if `k` is within bounds.
If k is larg er than the number of generated strings, return an empty string.
* Otherwise, return the `k`-th string (1-indexed).
# Complexity
### **Time complexity**:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
* The number of possible happy strings of length n is at most
` 2.3^(n-1)`, as we pick from `{a, b, c}` while ensuring no two adjacent characters are the same.
* Since we generate all happy strings and store them in a list, the worst-case complexity is `O(3^n)`.
### **Space complexity**:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
* The space required for storing the list of happy strings is `O(3^n)`
* The recursion stack depth is `O(n) `in the worst case.
# Code
```python3 []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
current=""
count=0
happy_strings=[]
self.generate_string(n,current,happy_strings,count,k)
if len(happy_strings)<k:
return ""
return happy_strings[k-1]
def generate_string(self,n,current,happy_strings,count,k):
if count==k:
return
if len(current)==n:
happy_strings.append(current)
count+=1
return
for ch in ['a','b','c']:
if len(current)>=1 and current[-1]==ch:
continue
self.generate_string(n,current+ch,happy_strings,count,k)
```
``` javascript []
/**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getHappyString = function(n, k) {
let count = 0;
let result = "";
function generateString(n, current) {
if (count === k) return;
if (current.length === n) {
count++;
if (count === k) result = current;
return;
}
for (let ch of ['a', 'b', 'c']) {
if (current.length > 0 && current[current.length - 1] === ch) continue;
generateString(n, current + ch);
}
}
generateString(n, "");
return count < k ? "" : result;
};
```
``` Java []
import java.util.*;
class Solution {
private int count = 0;
private String result = "";
private void generateString(int n, String current, int k) {
if (count == k) return;
if (current.length() == n) {
count++;
if (count == k) result = current;
return;
}
for (char ch : new char[]{'a', 'b', 'c'}) {
if (!current.isEmpty() && current.charAt(current.length() - 1) == ch) continue;
generateString(n, current + ch, k);
}
}
public String getHappyString(int n, int k) {
generateString(n, "", k);
return count < k ? "" : result;
}
}
```
``` C++ []
#include <iostream>
using namespace std;
class Solution {
private:
int count = 0;
string result = "";
void generateString(int n, string current, int k) {
if (count == k) return;
if (current.length() == n) {
count++;
if (count == k) result = current;
return;
}
for (char ch : {'a', 'b', 'c'}) {
if (!current.empty() && current.back() == ch) continue;
generateString(n, current + ch, k);
}
}
public:
string getHappyString(int n, int k) {
generateString(n, "", k);
return count < k ? "" : result;
}
};
```
``` C []
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void generateString(int n, char *current, int *count, int k, char *result) {
if (*count == k) return;
if (strlen(current) == n) {
(*count)++;
if (*count == k) {
strcpy(result, current);
}
return;
}
char options[] = {'a', 'b', 'c'};
for (int i = 0; i < 3; i++) {
if (strlen(current) > 0 && current[strlen(current) - 1] == options[i]) continue;
char newStr[n + 1];
strcpy(newStr, current);
newStr[strlen(current)] = options[i];
newStr[strlen(current) + 1] = '\0';
generateString(n, newStr, count, k, result);
}
}
char* getHappyString(int n, int k) {
int count = 0;
char empty[1] = "";
char *result = (char *)malloc((n + 1) * sizeof(char));
result[0] = '\0';
generateString(n, empty, &count, k, result);
return (count < k) ? strdup("") : result;
}
```
``` Go []
package main
import "fmt"
func generateString(n int, current string, count *int, k int, result *string) {
if *count == k {
return
}
if len(current) == n {
*count++
if *count == k {
*result = current
}
return
}
for _, ch := range []rune{'a', 'b', 'c'} {
if len(current) > 0 && current[len(current)-1] == byte(ch) {
continue
}
generateString(n, current+string(ch), count, k, result)
}
}
func getHappyString(n int, k int) string {
count := 0
result := ""
generateString(n, "", &count, k, &result)
if count < k {
return ""
}
return result
}
```
| 8 | 1 | ['String', 'Backtracking', 'Recursion', 'C', 'C++', 'Java', 'Go', 'Python3', 'JavaScript'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✔️ Easiest Solution & Beginner Friendly ✔️ | 🔥 Recursion + Backtracking 🔥 | 2 Solutions | easiest-solution-beginner-friendly-recur-nen0 | IntuitionImagine you are forming a word using only the lettersa, b, cbut with one rule—no twoconsecutive letters can be the same. You need to generate all possi | ntrcxst | NORMAL | 2025-02-19T03:57:50.372078+00:00 | 2025-02-19T03:57:50.372078+00:00 | 971 | false | # Intuition
Imagine you are forming a word using only the letters `a, b, c` but with one rule—no two **consecutive letters can be the same**. You need to generate all possible **valid words of a given length** `n`, sort them **lexicographically**, and find the `k-th` one. Instead of **brute force**, we use **backtracking** to systematically explore **every possible valid string**, ensuring that no two adjacent letters are the **same**. By **recursively** adding letters, we construct valid **happy strings** and keep track of them until we reach the `k-th` one.
# Approach
`Step 1` **Initialize Storage**
- Create a `list` to store valid happy strings.
`Step 2` **Backtracking Function**
- Start building strings **recursively**.
`Step 3` **Base Case**
- When the string reaches length `n`, add it to the `list`.
`Step 4` **Character Choices**
- Iterate over `a, b, c` and only add a character if it does not **match the last one**.
`Step 5` **Recursive Call**
- Continue building the string by adding the **next character**.
`Step 6` **Return the k-th String**
- After generating all **happy strings**, return the `k-th` one.
- If `k` is out of bounds, return an `**empty string**`.
# Complexity
- Time complexity : $$O(3^n)$$
- Space complexity : $$O(n)$$
# Code
```Java []
class Solution
{
// Step 1: Define the backtracking function
private void backtrack(int n, String curr, List<String> happyStrings)
{
// Step 2: If the current string reaches length 'n', store it and return
if (curr.length() == n)
{
happyStrings.add(curr);
return;
}
// Step 3: Iterate over possible characters ('a', 'b', 'c')
for (char ch : new char[]{'a', 'b', 'c'})
{
// Step 4: Ensure the new character is different from the last one
if (curr.isEmpty() || curr.charAt(curr.length() - 1) != ch)
{
// Step 5: Recursively generate the next character
backtrack(n, curr + ch, happyStrings);
}
}
}
// Step 6: Main function to generate happy strings
public String getHappyString(int n, int k)
{
List<String> happyStrings = new ArrayList<>();
backtrack(n, "", happyStrings); // Step 7: Start backtracking from an empty string
// Step 8: Return k-th happy string if it exists, else return ""
return (k > happyStrings.size()) ? "" : happyStrings.get(k - 1);
}
}
```
``` C++ []
class Solution
{
public:
// Step 1: Define the backtracking function
void backtrack(int n, string curr, vector<string>& happyStrings)
{
// Step 2: If the current string reaches length 'n', store it and return
if (curr.size() == n)
{
happyStrings.push_back(curr);
return;
}
// Step 3: Iterate over possible characters ('a', 'b', 'c')
for (char ch : {'a', 'b', 'c'})
{
// Step 4: Ensure the new character is different from the last one
if (curr.empty() || curr.back() != ch)
{
// Step 5: Recursively generate the next character
backtrack(n, curr + ch, happyStrings);
}
}
}
// Step 6: Main function to generate happy strings
string getHappyString(int n, int k)
{
vector<string> happyStrings;
backtrack(n, "", happyStrings); // Step 7: Start backtracking from an empty string
// Step 8: Return k-th happy string if it exists, else return ""
return (k > happyStrings.size()) ? "" : happyStrings[k - 1];
}
};
``` | 8 | 0 | ['Array', 'String', 'Binary Search', 'Backtracking', 'Greedy', 'Tree', 'Depth-First Search', 'Breadth-First Search', 'C++', 'Java'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | The k-th Lexicographical String of All Happy Strings of Length n || simple backtracking || O(3^n) | the-k-th-lexicographical-string-of-all-h-jl4v | IntuitionThe problem requires us to generate all possible "happy strings" of length n where the string consists of the characters 'a', 'b', and 'c', with no two | Mirin_Mano_M | NORMAL | 2025-02-19T08:25:26.918502+00:00 | 2025-02-19T08:25:58.845239+00:00 | 95 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires us to generate all possible "happy strings" of length n where the string consists of the characters 'a', 'b', and 'c', with no two consecutive characters being the same. After generating all the happy strings, we need to return the k-th happy string (1-indexed). If the number of happy strings is less than k, we should return an empty string.
# Approach
<!-- Describe your approach to solving the problem. -->
**Step-by-step Plan:**
**Backtracking:**
Use a backtracking approach to generate all the valid "happy strings" of length n. This is a depth-first search (DFS) over the string construction process. Starting with an empty string, we append characters ('a', 'b', 'c') while ensuring no two consecutive characters are the same.
**Generating Strings:**
Start with each of 'a', 'b', and 'c' as possible starting characters.
At each step, append a character that is different from the last one (ensuring the "happy" condition).
**Terminate Early:**
If we've already generated enough strings (i.e., k-th string is found), we can terminate the recursion early.
**Efficiency Consideration:**
Avoid generating all strings if the size of the output list exceeds k. As soon as we have enough strings, we can stop.
**Return the k-th string:**
Once all the strings are generated, we return the k-th string (1-indexed). If there are fewer than k strings, return an empty string.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
The number of valid happy strings of length n grows exponentially, but we stop as soon as we generate enough strings. Each backtracking step involves trying 3 characters, so in the worst case, we are exploring a tree of depth n. The time complexity is approximately O(3^n), but it's bounded by k, as we stop early.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
We store all valid strings up to the size k. The space complexity is O(k) as we're only keeping the k-th string at any point.
# Code
```cpp []
class Solution {
public:
vector<string> com;
void backtrack(string s, int n){
if(s.size()==n){
com.push_back(s);
return;
}
string t = s;
for(char i='a';i<='c';i++){
if(s[s.size()-1]!=i){
t+=i;
backtrack(t, n);
t=s;
}
}
}
string getHappyString(int n, int k) {
for(char i='a';i<='c';i++){
string t = "";
t+=i;
backtrack( t, n);
}
if(com.size()<k) return "";
return com[k-1];
}
};
```
```java []
class Solution {
List<String> com = new ArrayList();
public void backtrack(String s, int n) {
if (s.length() == n) {
com.add(s);
return;
}
for (char i = 'a'; i <= 'c'; i++) {
if (s.charAt(s.length() - 1) != i) {
s += i;
backtrack(s, n);
s = s.substring(0, s.length() - 1);
}
}
}
public String getHappyString(int n, int k) {
for (char i = 'a'; i <= 'c'; i++) {
String t = "";
t += i;
backtrack(t, n);
}
if (com.size() < k) return "";
return com.get(k - 1);
}
}
``` | 6 | 0 | ['String', 'Backtracking', 'C++', 'Java'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✔️ Easiest Solution & Beginner Friendly ✔️ | 🔥 Recursion + Backtracking 🔥 | 2 Solutions | easiest-solution-beginner-friendly-recur-i08p | IntuitionImagine you are forming a word using only the lettersa, b, cbut with one rule—no twoconsecutive letters can be the same. You need to generate all possi | ntrcxst | NORMAL | 2025-02-19T03:57:45.588724+00:00 | 2025-02-19T03:57:45.588724+00:00 | 330 | false | # Intuition
Imagine you are forming a word using only the letters `a, b, c` but with one rule—no two **consecutive letters can be the same**. You need to generate all possible **valid words of a given length** `n`, sort them **lexicographically**, and find the `k-th` one. Instead of **brute force**, we use **backtracking** to systematically explore **every possible valid string**, ensuring that no two adjacent letters are the **same**. By **recursively** adding letters, we construct valid **happy strings** and keep track of them until we reach the `k-th` one.
# Approach
`Step 1` **Initialize Storage**
- Create a `list` to store valid happy strings.
`Step 2` **Backtracking Function**
- Start building strings **recursively**.
`Step 3` **Base Case**
- When the string reaches length `n`, add it to the `list`.
`Step 4` **Character Choices**
- Iterate over `a, b, c` and only add a character if it does not **match the last one**.
`Step 5` **Recursive Call**
- Continue building the string by adding the **next character**.
`Step 6` **Return the k-th String**
- After generating all **happy strings**, return the `k-th` one.
- If `k` is out of bounds, return an `**empty string**`.
# Complexity
- Time complexity : $$O(3^n)$$
- Space complexity : $$O(n)$$
# Code
```Java []
class Solution
{
// Step 1: Define the backtracking function
private void backtrack(int n, String curr, List<String> happyStrings)
{
// Step 2: If the current string reaches length 'n', store it and return
if (curr.length() == n)
{
happyStrings.add(curr);
return;
}
// Step 3: Iterate over possible characters ('a', 'b', 'c')
for (char ch : new char[]{'a', 'b', 'c'})
{
// Step 4: Ensure the new character is different from the last one
if (curr.isEmpty() || curr.charAt(curr.length() - 1) != ch)
{
// Step 5: Recursively generate the next character
backtrack(n, curr + ch, happyStrings);
}
}
}
// Step 6: Main function to generate happy strings
public String getHappyString(int n, int k)
{
List<String> happyStrings = new ArrayList<>();
backtrack(n, "", happyStrings); // Step 7: Start backtracking from an empty string
// Step 8: Return k-th happy string if it exists, else return ""
return (k > happyStrings.size()) ? "" : happyStrings.get(k - 1);
}
}
```
``` C++ []
class Solution
{
public:
// Step 1: Define the backtracking function
void backtrack(int n, string curr, vector<string>& happyStrings)
{
// Step 2: If the current string reaches length 'n', store it and return
if (curr.size() == n)
{
happyStrings.push_back(curr);
return;
}
// Step 3: Iterate over possible characters ('a', 'b', 'c')
for (char ch : {'a', 'b', 'c'})
{
// Step 4: Ensure the new character is different from the last one
if (curr.empty() || curr.back() != ch)
{
// Step 5: Recursively generate the next character
backtrack(n, curr + ch, happyStrings);
}
}
}
// Step 6: Main function to generate happy strings
string getHappyString(int n, int k)
{
vector<string> happyStrings;
backtrack(n, "", happyStrings); // Step 7: Start backtracking from an empty string
// Step 8: Return k-th happy string if it exists, else return ""
return (k > happyStrings.size()) ? "" : happyStrings[k - 1];
}
};
``` | 6 | 0 | ['Array', 'String', 'Binary Search', 'Backtracking', 'Greedy', 'Tree', 'Depth-First Search', 'Breadth-First Search', 'C++', 'Java'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Recursion | Backtracking | Solution for LeetCode#1415 | recursion-backtracking-solution-for-leet-zuo5 | IntuitionTo solve the problem of generating the k-th lexicographical happy string of length n, the first thought is to generate all possible happy strings of le | samir023041 | NORMAL | 2025-02-19T02:10:11.843965+00:00 | 2025-02-19T02:10:11.843965+00:00 | 1,462 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
To solve the problem of generating the k-th lexicographical happy string of length n, the first thought is to generate all possible happy strings of length n and then sort them lexicographically. A happy string is a string where no two adjacent characters are the same.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Generate All Possible Happy Strings: Use a recursive function to generate all possible happy strings of length n. During the generation, ensure that no two adjacent characters are the same.
2. Store the Happy Strings: Store all valid happy strings in a list.
3. Sort the List: Sort the list of happy strings lexicographically.
4. Retrieve the k-th Happy String: Return the k-th happy string from the sorted list if it exists; otherwise, return an empty string.
# Complexity
- Time complexity: $$O(3^n)$$,
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(3^n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
// List to store all happy strings
List<String> list = new ArrayList<>();
// Method to get the k-th happy string of length n
public String getHappyString(int n, int k) {
char[] chr = {'a', 'b', 'c'};
// Generate all happy strings of length n
solve(chr, n, new StringBuilder());
// Sort the list of happy strings lexicographically
Collections.sort(list);
// Return the k-th happy string if it exists, otherwise return an empty string
return list.size() < k ? "" : list.get(k - 1);
}
// Recursive method to generate happy strings
void solve(char[] chr, int n, StringBuilder sb) {
// If the current string length equals n, add it to the list
if (n == sb.length()) {
list.add(sb.toString());
return;
}
// Iterate through each character in chr array
for (int i = 0; i < chr.length; i++) {
// Skip if the current character is the same as the last character in the string
if (sb.length() > 0 && chr[i] == sb.charAt(sb.length() - 1)) continue;
// Append the current character to the string
sb.append(chr[i]);
// Recursively generate the next character
solve(chr, n, sb);
// Remove the last character to backtrack
sb.setLength(sb.length() - 1);
}
}
}
``` | 6 | 0 | ['Backtracking', 'Recursion', 'Java'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Working Explained Using Permutation Concept | Complete Walkthrough] | working-explained-using-permutation-conc-wv8h | \n/*\n 3 Key Important things to know to solve any Backtracking problem\n ----------------------------------------------------------------\n\n 1.) Choi | _LearnToCode_ | NORMAL | 2022-09-27T11:48:26.916361+00:00 | 2022-09-27T11:51:40.981173+00:00 | 495 | false | ```\n/*\n 3 Key Important things to know to solve any Backtracking problem\n ----------------------------------------------------------------\n\n 1.) Choices [Search Space from which we\'ve to choose items]\n ==========================================================\n search_space = {\'a\', \'b\', \'c\'} only 3 chars\n \n 2.) Constraints [To apply on chosen items]\n ==========================================\n Two adjacent characters should NOT be equal. i.e. s[i] != s[i + 1]\n for all 0 <= i < len(s) (string \'s\' is 0-indexed).\n \n 3.) Goal [What problem is demanding/asking for]\n ===============================================\n Return kth lexicographically sorted strings(having only a/b or c) of length n.\n \n ======================================================================================\n \n \n Let\'s see how many strings are there for n = 3\n \n \n __a__, ____, ____\n ^ \n | \n {b, c} ----> \'a\' can\'t in our possible choices because previous character is also \'a\'\n two choices\n for this empty\n block to fill.\n \n __a__, __b__, ___\n ^ ^\n | | \n | +-----------------------------------after placing \'b\' at second position\n placing \'b\' first to make we\'ve two possible choices for third empty block\n sure that the generated string(of length n) {\'a\', \'c\'}\n is lexicographically sorted order.\n \n \n __a__, __b__, __a__ => first string of length 3, if we place \'a\' at third empty block\n \n \n __a__, __b__, __c__ => second generated string(remember lexicographically larger than previous)\n ^\n |\n |\n all choices for third position exhausted\n try other left choices at second position.\n \n \n __a__, __c__, ____\n ^ ^\n | |________ two choices for third position {\'a\', \'b\'} \n if we place \'c\'\n at second place\n \n \n __a__, __c__, __a___ => third generated string\n \n __a__, __c__, __b__ => fourth generated string\n \n \n Look the above, there are 4 different strings we got starting with letter\n \'a\' i.e. {"aba", "abc", "aca", "acb"}. All of them in lexicographically sorted order.\n \n NOTE: Since, we\'re always placing the smallest possible character at first, hence it gives\n us guaranteed that geneated strings are in lexicographically sorted order.\n \n similarly, there are 4 different strings starting with letter \'b\' & \'c\'\n \n starting with letter \'b\' : {"bab", "bac", "bca", "bcb"}\n \n starting with letter \'c\' : {"cab", "cac", "cba", "cbc"}\n \n Total 12 strings are possible of length 3.\n \n _3__, __2__, __2__\n ^ ^ ^ \n | | +------ {for each previous two choices, we\'ve two choices to fill it} \n | +--- {2 different choices to fill}\n {3 different choices to fill}\n \n Hence, total count of strings with length 3 can be given by : 3 * 2 * 2 = 12\n \n \n Similarly, If we\'ve to generate all possible strings of length 4 then count\n of total such strings can be given by : 3 * 2 * 2 * 2 = 24\n \n Total count of n length strings is : 3 * (2^(n - 1))\n \n ===================================================================================================\n \n \n Approach:\n ========\n 1. Generate all possible lexicographically sorted strings of length n.\n 2. Return kth strings out of them. {if we enough at least k strings}.\n \n \n Learning Factor\n ==============\n Look at the solution, how we used \'Permutation\' type template to solve this question.\n and how we\'re maintaing the lexicographically sorted strings just by picking\n the smallest character to fill any empty position.\n + No sorting is required at all.\n \n*/\nclass Solution {\n public String getHappyString(int n, int k) {\n int totalStringCount = 3 * (1 << (n - 1)); //1 << (n - 1) : 2^(n - 1)\n if(k > totalStringCount) return "";\n List<String> sortedStrings = new ArrayList<>();\n generateAllNLengthStrings(n, \'\\0\', sortedStrings, new StringBuilder());\n return sortedStrings.get(k - 1);\n }\n \n private void generateAllNLengthStrings(int n, char previousChar, List<String> sortedStrings,\n StringBuilder runningString) {\n if(runningString.length() == n) {\n sortedStrings.add(runningString.toString());\n return;\n }\n \n for(char ch = \'a\'; ch <= \'c\'; ch += 1) {\n if(ch != previousChar) {\n runningString.append(ch);\n generateAllNLengthStrings(n, ch, sortedStrings, runningString);\n runningString.deleteCharAt(runningString.length() - 1);\n }\n }\n }\n}\n```\n\n```\nGenerating Exactly k strings [No need to store all strings at all]\n```\n\n```\nclass Solution {\n public String getHappyString(int n, int k) {\n int totalStringCount = 3 * (1 << (n - 1)); \n if(k > totalStringCount) return "";\n return generateAllNLengthStrings(n, new int[]{k}, \'\\0\', new StringBuilder());\n }\n \n private String generateAllNLengthStrings(int n, int[] cnt, char previousChar, StringBuilder runningString) {\n if(runningString.length() == n) {\n return --cnt[0] == 0 ? runningString.toString() : "";\n }\n \n for(char ch = \'a\'; ch <= \'c\'; ch += 1) {\n if(ch != previousChar) {\n runningString.append(ch);\n String kthString = generateAllNLengthStrings(n, cnt, ch, runningString);\n //found our required kth lexicographically sorted string.\n if(kthString.length() != 0) return kthString;\n runningString.deleteCharAt(runningString.length() - 1);\n }\n }\n return "";\n }\n}\n``` | 6 | 0 | ['Java'] | 3 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Backtracking solution C++ | backtracking-solution-c-by-akansha_22-96w0 | ```\nclass Solution {\npublic:\n \n vector v={\'a\',\'b\',\'c\'};\n \n void helper(vector &ans,string t,int n,char prev)\n {\n if(n==0)\n | akansha_22 | NORMAL | 2021-05-16T11:35:20.671433+00:00 | 2021-05-16T11:35:20.671473+00:00 | 553 | false | ```\nclass Solution {\npublic:\n \n vector<char> v={\'a\',\'b\',\'c\'};\n \n void helper(vector<string> &ans,string t,int n,char prev)\n {\n if(n==0)\n {\n ans.push_back(t);\n return ;\n }\n \n for(int i=0;i<v.size();i++)\n {\n if(prev!=v[i])\n {\n t.push_back(v[i]);\n helper(ans,t,n-1,v[i]);\n t.pop_back();\n }\n }\n }\n \n string getHappyString(int n, int k) {\n \n vector<string> ans;\n string t="";\n helper(ans,t,n,\'#\');\n \n //sort(ans.begin(),ans.end());\n \n if(ans.size()<k)\n {\n return "";\n }\n return ans[k-1];\n }\n}; | 6 | 0 | ['Backtracking', 'C'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Best Approach to Practice Backtracking. | best-approach-to-practice-backtracking-b-f9bd | NoteMy dear Friend here I am Not going for Optimize or Time Complexity Based Approach, i know we can solve it using DFS and Queue Optimally.My only goal is to p | Tanmay_bhure | NORMAL | 2025-02-19T19:28:59.663699+00:00 | 2025-02-19T19:28:59.663699+00:00 | 103 | false | # Note
***My dear Friend here I am Not going for Optimize or Time Complexity Based Approach, i know we can solve it using DFS and Queue Optimally.
My only goal is to provide best backtracking approach So that You can Practice It, and get view of Backtracking Working.***
# Intuition
The problem asks to generate all "happy" strings of length n and return the k-th such string. A "happy" string is defined as a string that:
Has no two consecutive characters that are the same.
The characters are restricted to be from the set {"a", "b", "c"}.
We can generate all possible happy strings using a backtracking approach. The intuition is to generate the string step by step, ensuring at each step that no two consecutive characters are the same. Once we generate a valid string, we store it in a list. After generating all valid strings, we return the k-th one, if it exists.
# Approach
# 1.Backtracking:
Start with an empty string and try to build the string step by step, choosing characters from the set {"a", "b", "c"}.
At each position, ensure that the character added is not the same as the last character added (this ensures the string remains "happy").
When the length of the string reaches n, add it to the list of happy strings.
# 2.Base Case:
If the length of the string being built is equal to n, we have a valid happy string, so we add it to the list.
# 3.Recursive Case:
For each of the 3 characters ('a', 'b', 'c'), if the last character in the current string is different from the one we are trying to add, append the character and recurse to add the next character.
After recursion, backtrack by removing the last character and trying the next character.
# 4.Final Result:
After all possible strings are generated, if the number of strings in the list is greater than or equal to k, return the k-th string (1-based index). If there are fewer than k strings, return an empty string.
# Complexity
- Time complexity:
O(2^n)
- Space complexity:
O(2^n)
# Code
```java []
class Solution {
public String getHappyString(int n, int k) {
List<String> list= new ArrayList<>();
String s="abc";
backtrack(s,n,new StringBuilder(), list);
return (list.size()>=k)? list.get(k-1):"";
}
private void backtrack(String s, int n, StringBuilder sb, List<String> list){
if(sb.length()==n){
list.add(sb.toString());
return;
}
for(int i=0;i<3;++i){
if(sb.length()>0 && sb.charAt(sb.length()-1)==s.charAt(i)) continue;
sb.append(s.charAt(i));
backtrack(s,n,sb,list);
sb.setLength(sb.length()-1);
}
}
}
```
```C++ []
class Solution {
public:
string getHappyString(int n, int k) {
vector<string> list;
string s = "abc";
backtrack(s, n, "", list);
return (list.size() >= k) ? list[k - 1] : "";
}
void backtrack(string s, int n, string sb, vector<string>& list) {
if (sb.length() == n) {
list.push_back(sb);
return;
}
for (int i = 0; i < 3; ++i) {
if (sb.length() > 0 && sb[sb.length() - 1] == s[i]) continue;
sb.push_back(s[i]);
backtrack(s, n, sb, list);
sb.pop_back();
}
}
};
```
```Python3 []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
list = []
s = "abc"
self.backtrack(s, n, "", list)
return list[k - 1] if len(list) >= k else ""
def backtrack(self, s: str, n: int, sb: str, list: list):
if len(sb) == n:
list.append(sb)
return
for i in range(3):
if len(sb) > 0 and sb[-1] == s[i]:
continue
self.backtrack(s, n, sb + s[i], list)
``` | 5 | 0 | ['String', 'Backtracking', 'C++', 'Java', 'Python3'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✅ One Line Solution | one-line-solution-by-mikposp-hml7 | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)Code #1.1 - One LineTime complexity:O(3n). Space com | MikPosp | NORMAL | 2025-02-19T09:49:05.459028+00:00 | 2025-02-19T09:50:18.612535+00:00 | 593 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)
# Code #1.1 - One Line
Time complexity: $$O(3^n)$$. Space complexity: $$O(n)$$.
```python3
class Solution:
def getHappyString(self, n: int, k: int) -> str:
return next(islice((s for p in product(*['abc']*n) if not search(r'(.)\1',s:=''.join(p))),k-1,k),'')
```
[Ref](https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/solutions/1404881/4-line-python-no-list)
# Code #1.2 - Unwrapped
```python3
class Solution:
def getHappyString(self, n: int, k: int) -> str:
for p in product('abc', repeat=n):
s = ''.join(p)
if not search(r'(.)\1', s):
k -= 1
if k == 0:
return s
return ''
```
# Code #2 - Four Lines BFS
Time complexity: $$O(2^n)$$. Space complexity: $$O(2^n)$$.
```python3
class Solution:
def getHappyString(self, n: int, k: int) -> str:
r = ['']
for _ in range(n):
r = [s+c for s in r for c in 'abc' if s[-1:]!=c]
return ''.join(r[k-1:k])
```
[Ref](https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/solutions/5533528/a-lazy-4-line-bfs)
(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not declared to be 'true' oneliners - please, remind about drawbacks only if you know how to make it better) | 5 | 0 | ['String', 'Combinatorics', 'Python', 'Python3'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Easy Peasy, Daily Grind! 🌩️ | easy-peasy-daily-grind-by-_abhiramks-i42y | IntuitionApproachComplexity
Time complexity: O(2n)
Space complexity: O(2n)
Code | _abhiramks | NORMAL | 2025-02-19T04:24:01.867941+00:00 | 2025-02-19T04:24:01.867941+00:00 | 15 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(2n)
- Space complexity: O(2n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```dart []
🔥 steps
<!-- 1. Create an empty list 'ans' to store happy strings.
2. Call _generateHappyString Generate happy strings recursively
3. Return k-th happy string else empty string
4. Base case: Stop when string reaches length n
5. Store the valid happy string -->
class Solution {
String getHappyString(int n, int k) {
List<String> ans = [];
_generateHappyString(n, "", ans);
return k <= ans.length ? ans[k-1] : "";
}
void _generateHappyString(int n, String current, List<String> ans){
if(current.length == n){
ans.add(current);
return;
}
for(String char in ['a','b','c']){
if(current.isEmpty || current[current.length - 1] != char){
_generateHappyString(n, current + char, ans);
}
}
}
}
``` | 5 | 0 | ['Array', 'String', 'Backtracking', 'Recursion', 'Dart'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Beats 100% | Easy Explaination | Combinatorics & Maths 👍 | beats-100-easy-explaination-combinatoric-lb25 | IntuitionThe problem requires generating the k-th lexicographically smallest happy string of lengthn. A happy string is defined as a string consisting only of c | com_gaurav_dev | NORMAL | 2025-02-19T04:12:45.335750+00:00 | 2025-02-19T04:12:45.335750+00:00 | 369 | false | # Intuition
The problem requires generating the k-th lexicographically smallest happy string of length `n`. A happy string is defined as a string consisting only of characters `a`, `b`, and `c` such that no two adjacent characters are the same.
The key observation here is that for each position in the string, we can choose from at most two valid characters (excluding the last used character). Given `n`, the number of valid happy strings can be computed as `3 * 2^(n-1)`. This helps in determining whether `k` is a valid index and aids in selecting the right character at each position efficiently.
# Approach
1. **Base Case Handling:**
- If `k` is greater than the number of possible happy strings (`3 * 2^(n-1)`), return an empty string as the k-th happy string does not exist.
2. **Recursive Construction:**
- Use a helper function `h(n, k, lastChar, result)` to recursively build the string.
- Iterate through characters `a`, `b`, and `c`, ensuring that the selected character is different from the previous one (`lastChar`).
- Determine if `k` falls in the first half of the possibilities (`2^(n-1)`). If not, adjust `k` accordingly by subtracting `2^(n-1)`, and move to the next choice.
- Append the chosen character to `result` and continue building the string recursively.
3. **Backtracking and String Construction:**
- The function chooses the correct character at each step based on the value of `k` and ensures a lexicographically ordered happy string is built.
- The process continues until `n` characters have been added to the `result` string.
# Complexity Analysis
- **Time Complexity:**
- The algorithm effectively selects each character in `O(1)`, iterating `n` times.
- Since each step involves a constant number of operations, the overall complexity is **O(n)**.
- **Space Complexity:**
- The recursion depth is at most `n`, and we store the result in a string.
- The space used for the result string is `O(n)`, and the recursion stack also takes `O(n)` space.
- Hence, the overall space complexity is **O(n)**.
# Code Breakdown
### **Main Function: `getHappyString`**
- Checks if `k` is out of range.
- Calls the recursive function `h` to construct the k-th happy string.
### **Recursive Function: `h`**
- Loops through three characters (`a`, `b`, `c`), ensuring no two consecutive characters are the same.
- Determines if `k` is in the current subset and either appends a character or updates `k` accordingly.
- Recursively builds the string until `n` characters are placed.
# Edge Cases Considered
- `k` is out of range (returns an empty string).
- `n = 1`, ensuring a single-character happy string is correctly selected.
- Larger values of `n` to verify efficient recursive selection.
- Cases where `k` is at the boundary of character choices.
# Code
```cpp []
// By: Gaurav Yadav
class Solution {
public:
string getHappyString(int n, int k) {
string result = "";
if(k > 3*(1<<(n-1))) return result; // if k is out of range, then return Empty string
h(n, k, -1, result); // else start building the string
return result;
}
private:
void h(int n, int k, int lastChar, string&result){
if(n==0) return; // base case
for(int i=0;i<3;i++){ // explore for options lexicographically
if(i==lastChar) continue; // consecutive chars can't be same so skip it
else{
if(1<<(n-1) < k) k-=(1<<(n-1));
else{
result.push_back(char(i + 'a'));
h(n-1, k, i, result);
return;
}
}
}
}
};
``` | 5 | 0 | ['Bit Manipulation', 'Combinatorics', 'C++'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Fast and Simple C++ | fast-and-simple-c-by-arpit_sat-qv6h | \nvoid find_all(int n,string &curr,vector<string> &v)\n{\n\tif(curr.size()==n)\n\t{\n\t\tv.push_back(curr);\n\t\treturn ;\n\t}\n\tfor(char i=\'a\';i<=\'c\';i++) | Arpit_Sat | NORMAL | 2021-03-25T14:50:25.921600+00:00 | 2021-03-25T14:50:25.921649+00:00 | 285 | false | ```\nvoid find_all(int n,string &curr,vector<string> &v)\n{\n\tif(curr.size()==n)\n\t{\n\t\tv.push_back(curr);\n\t\treturn ;\n\t}\n\tfor(char i=\'a\';i<=\'c\';i++)\n\t{\n\t\tif(curr.size()==0||i!=curr.back())\n\t\t{\n\t\t\tcurr.push_back(i);\n\t\t\tfind_all(n,curr,v);\n\t\t\tcurr.pop_back();\n\t\t}\n\t}\n}\nstring getHappyString(int n, int k) {\n\tvector<string> v;\n\tstring curr;\n\tfind_all(n,curr,v);\n\tsort(v.begin(),v.end());\n\tif(k>v.size())\n\t\treturn "";\n\treturn v[k-1];\n}\n``` | 5 | 0 | [] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Python, O(n) (faster than 99%, memory usage less than 100%) | python-on-faster-than-99-memory-usage-le-o5of | We calculate how many possible happy substrings of given length minus one exist \u2013 using this number, k, a list of possible letters and the last used letter | karbayev | NORMAL | 2020-04-20T22:38:20.223923+00:00 | 2020-05-09T12:37:55.527055+00:00 | 675 | false | We calculate how many possible happy substrings of given length minus one exist \u2013 using this number, `k`, a list of possible letters and the last used letter we easily calculate what would be the letter at the current index.\n\nThis solution has O(n) runtime complexity and O(1) space complexity (result not counted).\nEven though we\'re using `sorted(chars - set(last))` in the loop, it\'s safe to estimate the runtime complexity as linear, since the sorted list consist only of 3 elements for the first iteration and afterward always 2 elements. Could have replaced it with manual rearrangement, but `sorted` is much more concise.\n\n```python\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n # calculate total number of happy strings of length n\n total = 3 * 2**(n-1)\n if k > total:\n return ""\n\n # alphabet:\n chars = set(\'abc\')\n # last used letter (begin with empty):\n last = \'\'\n\n result = [\'\']*n\n for i in range(n):\n # list of possible letters after the last used one:\n choice = sorted(chars - set(last))\n # how many substrings of length (n-i-1) are possible:\n total //= len(choice)\n # pick the letter at index i:\n last = choice[(k-1)//total]\n result[i] = last\n # reduce k to pick from substrings:\n k %= total\n\n return \'\'.join(result)\n```\n\nExample: we\'re given n = 3, k = 9.\nThe total number of happy strings of length 3 is 12 (3\\*2^(n-1)).\nLet\'s find first letter: we can choose from a list of letters `[a, b, c]`, and after we pick one of them, there will be 4 possible happy substrings of length 2 (since we\'re reducing the number of possibilities by 3 by picking one of three letters). `(k-1) // total substrings = (9-1) // 4 = 2` is the index in our list of possible letters, so the first letter is `c`. We also need to set `k = 9 % 4 = 1` (as `k` needs to be smaller than the number of possible substrings).\nSecond letter: now we choose only from `[a, b]` and after we pick one of them, we\'ll have only 2 possible happy substrings of length 1 left. `(k-1) // total substrings = (1-1) // 2 = 0` is the index in our list of possible letters, so our second letter is `a`. Now `k = 2 % 1 = 1`.\nThird letter: a list of possible letters now is `[b,c]`, and there\'s only one possible happy substring of length 1 - an empty string. After repeating our calculations, we get the index of the third letter equal to 0 - which correspons to letter `b`.\nSo, the resulting string would be `cab`.\n\nThe same code without comments:\n```python\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n total = 3 * 2**(n-1)\n if k > total:\n return \'\'\n chars, last, result = set(\'abc\'), \'\', [\'\']*n\n for i in range(n):\n choice = sorted(chars - set(last))\n total //= len(choice)\n last = choice[(k-1)//total]\n result[i], k = last, k % total\n return \'\'.join(result)\n``` | 5 | 0 | ['Combinatorics', 'Python', 'Python3'] | 3 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Javascript Solution construct possible strings, sort and return kth string | javascript-solution-construct-possible-s-voxf | \n//contructs an array of all possible unique strings possible with \'a\', \'b\', \'c\' of length n\nvar formArray = function(res, s, pre, l, n){\n if (n == | seriously_ridhi | NORMAL | 2020-04-18T18:21:26.740492+00:00 | 2020-04-18T19:25:02.571929+00:00 | 311 | false | ```\n//contructs an array of all possible unique strings possible with \'a\', \'b\', \'c\' of length n\nvar formArray = function(res, s, pre, l, n){\n if (n == 0) \n { \n res.push(pre);\n return; \n } \n for (var i = 0; i < l; i++) \n { \n var newPre; \n \n // Next character of input added. check for last character of prefix \n if(pre[pre.length-1] !== s[i])\n { \n newPre = pre + s[i];\n formSet(res, s, newPre, l, n - 1); \n }\n \n } \n}\nvar getHappyString = function(n, k) {\n var res = []\n formArray(res, [\'a\',\'b\',\'c\'], "", 3, n);\n res.sort();\n if(res.length<k){\n return "";\n }\n return res[k-1];\n};\n``` | 5 | 1 | ['JavaScript'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Easy python recursive + [sorting(lexicographically) / heap] | easy-python-recursive-sortinglexicograph-qaq4 | Approach 1 . Generating all the strings of length n (252 ms).\n\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n res=[] # lis | codes_in_dark | NORMAL | 2020-04-18T16:09:40.216295+00:00 | 2020-04-19T01:00:00.317102+00:00 | 518 | false | Approach 1 . Generating all the strings of length n (252 ms).\n```\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n res=[] # list storing all the strings of size n \n def fun(s, curr, n): # recurisve function for finding all strings\n if n==0 : \n res.append(curr)\n return\n for i in range(3): #checking whether the currently buildup string\'s last charachter matches to the new charachter we are appending\n if curr and curr[-1]==s[i]: \n continue\n modify_curr=curr+s[i] # modify current string \n fun(s, modify_curr, n-1) \n fun([\'a\',\'b\',\'c\'],"",n)\n res=sorted(res) #lexicographically sorted\n return res[k-1] if k <= len(res) else "" \n```\n\nApproach 2 : Another approcah using heap (Much faster , 180ms)\n Need only to use heapify once . (min_heap)\n```\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n heap=[]\n def fun(s, curr, n): \n if n==0 : \n heapq.heappush(heap, curr)\n return\n for i in range(3): \n if curr and curr[-1]==s[i]:\n continue\n new_curr = curr + s[i] \n fun(s, new_curr, n-1) \n fun([\'a\',\'b\',\'c\'],"",n)\n # res=sorted(res)\n result=""\n heapq.heapify(heap)\n for i in range(k-1): #pop till k-2 th element\n heapq.heappop(heap)\n if not heap:\n break\n return heapq.heappop(heap) if heap else "" # pop k-1 the element if exits\n \n \n```\n\n \n\n | 5 | 0 | [] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | O(3^n) | Space (Only recusive stack) | Backtracking | o3n-space-only-recusive-stack-backtracki-n6cv | IntuitionApproachBacktracking TechniqueWe use backtracking to generate all valid happy strings of length n.Explore all possibilities by recursively adding chara | Developer_Ashish_1234 | NORMAL | 2025-02-19T06:35:21.441797+00:00 | 2025-02-19T06:35:21.441797+00:00 | 68 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
Backtracking Technique
We use backtracking to generate all valid happy strings of length n.
Explore all possibilities by recursively adding characters 'a', 'b', and 'c' to the current string.
Skipping Invalid Choices
If the last character is the same as the current character, we skip it to ensure no adjacent characters are identical.
Tracking the k-th String
Each time we find a valid happy string, we decrement k_.
When k_ == 0, we store the result in the ans variable and stop further recursion.
Returning the Result
If we reach the k-th happy string, we return it.
If there are fewer than k happy strings, ans remains empty, and we return it.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(3^n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
Only recursive stacks
# Code
```cpp []
class Solution {
public:
int k_,m;
string ans = "";
void f(string &s){
if(s.size()==m){
k_--;
if(k_ == 0){
ans = s;
return;
}
return ;
}
for(char c = 'a';c<='c';c++){
if(s.size()>0 && s.back()==c) continue;
s.push_back(c);
f(s);
s.pop_back();
}
}
string getHappyString(int n, int k) {
m = n;
k_ = k;
string s = "";
f(s);
return ans;
}
};
``` | 4 | 0 | ['C++'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Beats 100% ✅Easy C++ solution using backtracking | beats-100-easy-c-solution-using-backtrac-jq8a | IntuitionTry to make all the good string of size n. Return the kth lexicographically shortest .It simply implies that we can generate all the good string in lex | shivangkat07 | NORMAL | 2025-02-19T04:58:28.037591+00:00 | 2025-02-19T04:58:28.037591+00:00 | 190 | false | 
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Try to make all the good string of size n. Return the kth lexicographically shortest .It simply implies that we can generate all the good string in lexicographical order using recursion.
# Approach
<!-- Describe your approach to solving the problem. -->
Started with index 0 and try to fill it with all the elements of the given set i.e [a,b,c] .Recursively call the function to fill the other indexes. Maintain a previous character in order to make a good string.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(2^n)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(n)$$
# Code
```cpp []
class Solution {
public:
bool backtracking(int ind,char prev,string &temp,int &n,int &k)
{
if(ind==n)
{
k--;
if(k==0) return true;
else return false;
}
bool ans=false;
for(char ch='a';ch<='c';ch++)
{
if(ch!=prev)
{
temp.push_back(ch);
ans|=backtracking(ind+1,ch,temp,n,k);
if(ans==true) return true;
temp.pop_back();
}
}
return ans;
}
string getHappyString(int n, int k) {
string temp="";
backtracking(0,'d',temp,n,k);
return temp;
}
};
``` | 4 | 0 | ['C++'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | One Linear! | one-linear-by-charnavoki-8i9b | null | charnavoki | NORMAL | 2025-02-19T01:19:34.537035+00:00 | 2025-02-19T01:19:34.537035+00:00 | 414 | false |
```javascript []
const getHappyString = f = (n, k, list = ['']) =>
n ? f(n - 1, k, list.flatMap(v => [...'abc'].map(c => !v.endsWith(c) ? v + c : '').filter($=>$))) : list[k - 1] || '';
``` | 4 | 0 | ['JavaScript'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simple Clean Code with Description and recursive tree diagram. | simple-clean-code-with-description-and-r-sdo6 | Intuition\nBased on the recursive tree below we want to push the values into vector v.\n\n\n# Approach\nWe are going to save the current string in op and iterat | SSS009 | NORMAL | 2023-01-11T21:47:21.715542+00:00 | 2023-01-11T21:47:21.715579+00:00 | 472 | false | # Intuition\nBased on the recursive tree below we want to push the values into vector v.\n\n\n# Approach\nWe are going to save the current string in op and iterate over and over until the current string size is equal to n.\n\n# Complexity\n- Time complexity:\nTime complexity of this approach is 3^N.\n\n- Space complexity:\nSpace complexity of this approach is N.\n\n# Code\n```\nclass Solution {\npublic:\nvector<string> v;\n string getHappyString(int n, int k) {\n string op = "";\n solve(op, n, v);\n if ((k-1) >= v.size()) return "";\n return v[k-1];\n }\n void solve(string op, int n, vector<string> &v){\n if (n == 0){\n v.push_back(op);\n return;\n }\n for(int i = 0; i < 3;i++){\n char ch = \'a\' + i;\n if (op.size() == 0 or (op[op.size()-1] != ch)){\n solve(op+ch, n-1, v);\n }\n }\n return;\n }\n};\n```\n# Upvote if this helps. | 4 | 0 | ['Backtracking', 'Recursion', 'C++'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | C++, C# backtracking, dfs | c-c-backtracking-dfs-by-leonenko-5r6b | C++\n\nstring result;\nstring getHappyString(int n, int k) {\n\tstd::vector<char> str;\n\tdfs(str, n, k);\n\treturn result;\n}\n\nvoid dfs(std::vector<char>& st | leonenko | NORMAL | 2020-04-18T16:20:04.121388+00:00 | 2020-04-18T16:54:50.900991+00:00 | 570 | false | C++\n```\nstring result;\nstring getHappyString(int n, int k) {\n\tstd::vector<char> str;\n\tdfs(str, n, k);\n\treturn result;\n}\n\nvoid dfs(std::vector<char>& str, int n, int& k) {\n\tif (n == 0) {\n\t\tif (--k == 0) result = string(str.begin(), str.end());\n\t} else {\n\t\tfor(char ch = \'a\'; ch <= \'c\'; ++ch) {\n\t\t\tif (str.size() > 0 && ch == str[str.size() - 1]) continue;\n\t\t\tstr.push_back(ch);\n\t\t\tdfs(str, n - 1, k);\n\t\t\tstr.pop_back();\n\t\t}\n\t}\n}\n```\n\nC#\n```\n char[] ch = new char[3] { \'a\', \'b\', \'c\' };\n int kk = 0; string result = "";\n\t\n public string GetHappyString(int n, int k) {\n kk = k;\n backtrack(new List<char>(), n);\n return result;\n }\n \n void backtrack(List<char> str, int n) {\n if (n == 0) {\n if (--kk == 0) { result = new string(str.ToArray()); return;};\n } else {\n for(var i = 0; i < ch.Length; i++) {\n if (str.Count > 0 && ch[i] == str[str.Count - 1]) continue;\n str.Add(ch[i]);\n backtrack(str, n - 1);\n str.RemoveAt(str.Count - 1);\n }\n }\n }\n``` | 4 | 1 | ['Backtracking', 'Depth-First Search', 'C', 'C++'] | 1 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Java] DP (recursive) + Heap | java-dp-recursive-heap-by-manrajsingh007-xe4v | ```\nclass Solution {\n public static List func(int n, int i, int prev, HashMap> map) {\n if(i == n) {\n List ans = new ArrayList<>();\n | manrajsingh007 | NORMAL | 2020-04-18T16:01:52.792216+00:00 | 2020-04-18T16:01:52.792268+00:00 | 250 | false | ```\nclass Solution {\n public static List<String> func(int n, int i, int prev, HashMap<Integer, List<String>> map) {\n if(i == n) {\n List<String> ans = new ArrayList<>();\n ans.add("");\n return ans;\n }\n if(map.containsKey(i * 10 + prev)) return map.get(i * 10 + prev);\n List<String> curr = new ArrayList<>();\n for(int l = 0; l < 3; l++) {\n if(prev != l) {\n char ch = (char)(l + 97);\n List<String> small = func(n, i + 1, l, map);\n for(int j = 0; j < small.size(); j++) curr.add(ch + small.get(j));\n }\n }\n map.put(i * 10 + prev, curr);\n return curr;\n }\n public String getHappyString(int n, int k) {\n List<String> ans = func(n, 0, 3, new HashMap<>());\n if(ans.size() < k) return "";\n PriorityQueue<String> pq = new PriorityQueue<>(Collections.reverseOrder());\n for(int i = 0; i < k; i++) pq.add(ans.get(i));\n for(int i = k; i < n; i++) {\n if(ans.get(i).compareTo(pq.peek()) < 0) {\n pq.poll();\n pq.add(ans.get(i));\n }\n }\n return pq.peek();\n }\n} | 4 | 3 | [] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Optimized Lexicographic Happy String Generation in O(n) Time | optimized-lexicographic-happy-string-gen-ywnq | IntuitionThe problem requires generating a lexicographically ordered "happy string" of length n, where adjacent characters are different. Since there are only t | lanireddyhiteshreddy | NORMAL | 2025-02-19T12:22:24.665853+00:00 | 2025-02-19T12:22:24.665853+00:00 | 15 | false | # Intuition
The problem requires generating a lexicographically ordered "happy string" of length n, where adjacent characters are different. Since there are only three choices (a, b, c) at each position, we can generate all possible happy strings in lexicographic order and return the k-th one. Instead of generating all strings explicitly, we can directly compute the required string using mathematical calculations(Permuations and Combinations).
# Approach
1. The total number of happy strings of length n is 3 * 2^(n-1), as the first character has 3 choices and each subsequent character has 2 choices.
2. If k exceeds this total count, return an empty string.
3. Start constructing the string by selecting the first character based on (k-1) / product, where product = 2^(n-1).
4. For each subsequent character:
- Determine the valid next character (a, b, or c) based on the previous character.
- Reduce k accordingly.
- Update product by halving it at each step.
5. Continue the process until the string is formed.
# Complexity
- Time complexity:
- Best Case: 𝑂(𝑛) (when k is small, but we still traverse n characters).
- Worst Case: 𝑂(𝑛) (we iterate n times for any k).
- Space complexity:
- O(1), since we use only a few extra variables.
# Code
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
string ans = "";
int product = (1<<(n-1));
if(k>product*3) return "";
char prevChar='-1';
for(int i=0;i<n;i+=1){
int v = (k-1)/product;
char start;
if(prevChar == 'a'){
start = 'b'+v;
}
else if(prevChar =='b'){
if(v==0) start = 'a';
else start = 'c';
}
else{
start = 'a'+v;
}
ans+= start;
k-=v*(product);
prevChar = start;
product = product>>1;
}
return ans;
}
};
``` | 3 | 0 | ['C++'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | O(n) approach 100% beats, without recursion, using P&C to generate string | on-approach-100-beats-without-recursion-8e3ea | IntuitionFirst thought was only to generate all the possible strings and get to the answer, then I thought of optmization where i need to store all but just kee | v2khan | NORMAL | 2025-02-19T11:49:34.360346+00:00 | 2025-02-19T11:50:03.378043+00:00 | 78 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
First thought was only to generate all the possible strings and get to the answer, then I thought of optmization where i need to store all but just keep the counter on k to let it reach 0 and boom we got the string, but both these approaches took around $$2(^n)$$ time.
So the thought of generating the kth string came from the concept of P & C. Where for instance if we are given 3 items to fill in 4 places, and we are told that we can't fill two simiary items consecutively then we used to -
3 * 2 * 2 * 2
that is for the first place we have 3 choices but for every other place we have 2 choices only, so that means, every character will have 2 * 2 * 2 times occurence at the first index. and hence we can easily find the remaining k.
# Approach
<!-- Describe your approach to solving the problem. -->
Suppose k = 9, n = 3
maximum possible string are 3 * 2 * 2 = 12
so each of {a,b,c} will appear 4 times each at the first index,
so for the first index we will get the 9 / 4 = 2, that is character c will be placed there, and with this we got to know that of the 9th string we were asked, we are already on the 9th string because with a & b as the first characters we have already covered 8 string so the next string after that is starting with 'c' hence it is the 9th string, but we still need to fill the 2 empty places, so for that we are left with k = 1.
This above is the core logic.
Take a pen paper and dry run an example n = 4, k = 22. It will be easily clear.
Now when we are to fill the elements after the 0th index , then we will do some steps, becuase we can't fill the previous characters and also we need to maintain a lexicographical order hence some sorting on remaining elements is done.
All this part of code is self explanatory, you just try to understand the core logic of why k / 2 ^ n - 1 worked
I have added comments via ChatGPT. Hope it helps.
Thanks to Strivers - takeUforward
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(1)$$
# Code
```cpp []
class Solution {
public:
// Function to find the k-th happy string of length n
string getHappyString(int n, int k) {
// The maximum possible number of happy strings of length n
// The formula is 3 * 2^(n-1), as there are 3 choices for the first character
// and 2 choices for each subsequent character (since no two consecutive characters can be the same).
int maxm = 3 * (1 << (n - 1)); // Equivalent to 3 * 2^(n-1)
// If k is greater than the total number of possible happy strings, return an empty string
if (k > maxm) return "";
// Variable to track the previous character (starting with a character that is not 'a', 'b', or 'c')
char prev = '#';
// Vector to store the possible characters for each position ('a', 'b', 'c')
vector<char> chars = {'a', 'b', 'c'};
// Decrease k by 1 to switch to 0-based indexing
k--;
// Resulting happy string
string ans = "";
// Loop to build the k-th happy string by iterating over each position
while (n) {
n--; // Decrease the length to process the next character position
// Calculate the number of strings starting with each character at the current position
int N = 1 << n; // This is equivalent to 2^(n-1), the number of strings with a fixed prefix
// Determine which character should go at the current position based on k
int index = k / N;
ans += chars[index]; // Append the selected character to the result
prev = chars[index]; // Update the previous character for the next iteration
// Update k to be within the range of the current block of strings
k = k % N;
// Reset the list of available characters for the next position
chars.resize(0);
// Add characters that are different from the previous one (to ensure adjacent characters differ)
for (auto ch : {'a', 'b', 'c'}) {
if (ch == prev) continue; // Skip the character that is the same as the previous one
chars.push_back(ch); // Add the valid character to the list of available characters
}
// Sort the characters to maintain lexicographical order ('a', 'b', 'c')
sort(chars.begin(), chars.end());
}
// Return the generated k-th happy string
return ans;
}
};
``` | 3 | 0 | ['Combinatorics', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✅ Easy to Understand | Backtracking | Recursive Thinking | Detailed Video explanation🔥 | easy-to-understand-backtracking-recursiv-vccv | IntuitionThe problem requires generating lexicographically sorted "happy" strings of lengthnusing characters 'a', 'b', and 'c', where no two adjacent characters | sahilpcs | NORMAL | 2025-02-19T09:25:38.492748+00:00 | 2025-02-19T09:25:38.492748+00:00 | 160 | false | # Intuition
The problem requires generating lexicographically sorted "happy" strings of length `n` using characters 'a', 'b', and 'c', where no two adjacent characters are the same. The k-th happy string needs to be determined efficiently.
# Approach
We use a recursive backtracking approach to generate all possible happy strings of length `n`. A counter `k` keeps track of how many valid strings have been encountered. Whenever `k` reaches 1, we store the current string as the answer and return. We iterate over characters 'a', 'b', and 'c', ensuring adjacent characters are different, and explore all valid possibilities.
# Complexity
- Time complexity:
- The number of valid happy strings of length `n` is at most `3 * 2^(n-1)`. The recursion explores these possibilities, leading to a time complexity of approximately $$O(2^n)$$.
- Space complexity:
- The recursion depth is at most `n`, leading to a space complexity of $$O(n)$$ due to the recursive call stack.
# Code
```java []
class Solution {
String ans; // Stores the k-th happy string
int n; // Length of the happy string
int k; // Position of the required happy string in lexicographical order
char[] chars; // Allowed characters ('a', 'b', 'c')
public String getHappyString(int n, int k) {
ans = ""; // Initialize answer as empty
chars = new char[]{'a','b','c'}; // Define possible characters
this.n = n;
this.k = k;
sol(0, ""); // Start generating happy strings
return ans; // Return the k-th happy string (if exists, else empty string)
}
private boolean sol(int idx, String temp) {
// Base case: If the generated string reaches length n
if (idx == n) {
if (k == 1) { // If it's the k-th valid string, store it as the answer
ans = temp;
return true;
} else {
k--; // Decrement k and continue searching
return false;
}
}
// Try to append each character to the current string
for (char ch : chars) {
char prev = temp.length() == 0 ? 'x' : temp.charAt(temp.length() - 1); // Get last character
if (prev != ch) { // Ensure adjacent characters are different
if (sol(idx + 1, temp + ch)) return true; // If k-th string is found, return true
}
}
return false; // Continue searching if k-th string is not found
}
}
```
https://youtu.be/-zjPucyQFVk
| 3 | 0 | ['String', 'Backtracking', 'Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Generate all possible Happy Strings | generate-all-possible-happy-strings-by-d-qdc0 | How it works:We generate all possible combinations of length nReturn k - 1 possition or empty stringComplexity
Time complexity: O(3 ^ n) - In worst case
Space | Danil_M | NORMAL | 2025-02-19T08:46:33.096151+00:00 | 2025-02-19T08:46:33.096151+00:00 | 11 | false | **How it works:**
We generate all possible combinations of length n
Return k - 1 possition or empty string
# Complexity
- Time complexity: O(3 ^ n) - In worst case
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```kotlin []
class Solution {
fun getHappyString(n: Int, k: Int): String {
val res = mutableListOf<String>()
val set = "abc"
val subset = StringBuilder()
generateHappyString(0, n, set, subset, res)
return if (k > res.size) "" else res[k - 1]
}
private fun generateHappyString(
index: Int,
n: Int,
set: String,
subset: StringBuilder,
res: MutableList<String>
) {
if (index == n) {
res.add(subset.toString())
return
}
for (s in set) {
if (subset.isEmpty() || subset[subset.length - 1] != s) {
subset.append(s)
generateHappyString(index + 1, n, set, subset, res)
subset.deleteCharAt(subset.length - 1)
}
}
}
}
``` | 3 | 0 | ['Kotlin'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Math Approach || Clean code || O(n) RT and MEM | math-approach-clean-code-on-rt-and-mem-b-uo27 | Thanks to_Marat_for approach and python3-codeIntuitionYou can count the total number of happy strings depent by size (n).totalCount=3∗2n−1Because all of 3 chars | Rixaki | NORMAL | 2025-02-19T08:33:26.174982+00:00 | 2025-02-19T12:13:52.001185+00:00 | 242 | false | Thanks to_ [Marat](https://leetcode.com/u/iiByEb5iOA/) _for approach and python3-code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
You can count the total number of happy strings depent by size (n).
$$
totalCount = 3*2^{n-1}
$$
Because all of 3 chars avaliable for first place and 2 chars avaliable for another places in happy string.
Similar to binary search, we start searching for the k-th element in sorted-list of happy strings. The main feature of the search is that we divide the interval between left (min_k) and right (max_k) into 3(!) segments for 1st place and divide by 2 for next places.
***First place finding by "triply"-search:***
$$
firstLetterInKth=a \Rightarrow k \in [1...2^{n-1}]
$$
$$
firstLetterInKth=b \Rightarrow k \in [1+2^{n-1}...2*2^{n-1}]
$$
$$
firstLetterInKth=c \Rightarrow k \in [1+2*2^{n-1}...3*2^{n-1}]
$$
***Another places finding by "binary"-search:***
$$
IthLetterInKth=firstAvalibleBy(a,b,c) \Rightarrow k \in [min+1...min+2^{n-i}]
$$
$$
IthLetterInKth=secondAvalibleBy(a,b,c) \Rightarrow k \in [min+1+2^{n-i}...min+2*2^{n-i}]
$$
min=max lexicographical number by (i-1)-size subString by k-th Happy String
# Approach
<!-- Describe your approach to solving the problem. -->
For ease of calculation, we will create an array of size n+1, where the first element will be "help-char" ('_') in order to be able to put any character in the next place. The remaining elements will be guided by the previous filled symbol.
For "triply"/"binary"-search (i-th pos, where i>0):
min_k=oldMax+1 //oldMax-see "min" above (binary-search)
max_k=oldMax+2^(n-i) //if k<max_k then max_k increase more by **+2^(n-i)** for 2nd avaliable letter condition pass
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. You can count the total number of lucky rows. -->
- Space complexity: $$O(n)$$(answer) or $$O(1)$$ for additional space
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```kotlin []
class Solution {
fun getHappyString(n: Int, k: Int): String {
val res = CharArray(n+1){'_'}
val latters = "abc"
var min_k = 0
var max_k = 0
for (pos in 1..n){
for (ch in 0..2){
if (latters[ch] != res[pos-1]){
min_k = max_k + 1
max_k += (2.0).pow(n-pos).toInt()
if (min_k <= k && k <= max_k){
max_k = min_k - 1
res[pos] = latters[ch]
break
}
}
}
if (res[pos] == '_') { return "" }
}
return String(res).substring(1)
}
}
```
```java []
class Solution {
public String getHappyString(int n, int k) {
char[] res = new char[n+1];
Arrays.fill(res,'_');
char[] latters = "abc".toCharArray();
int min_k = 0;
int max_k = 0;
for (int pos = 1; pos<=n; pos++){
for(int ch = 0; ch<=2; ch++){
if( latters[ch] != res[pos-1] ){
min_k = max_k + 1;
max_k += Math.pow(2,n-pos);
if (min_k <= k && k <= max_k){
max_k = min_k - 1;
res[pos] = latters[ch];
break;
}
}
}
if (res[pos] == '_') { return ""; }
}
return new String(res).substring(1);
}
}
```
```python3 []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
res = ['_' for _ in range(n + 1)]
latters = ('a', 'b', 'c')
min_k, max_k = 0, 0
for pos in range(1, n + 1):
for l in latters:
if l != res[pos - 1]:
min_k = max_k + 1
max_k += 2**(n - pos)
if min_k <= k and k <= max_k:
max_k = min_k - 1
res[pos] = l
break
if res[pos] == '_':
return ''
return ''.join(res[1:])
``` | 3 | 0 | ['Math', 'String', 'Java', 'Python3', 'Kotlin'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simple and Easy Approach by using Recursion (Easy to Understand) | simple-and-easy-approach-by-using-recurs-ynic | IntuitionThe problem requires generating "happy strings" of length n using the characters {a, b, c} such that no two consecutive characters are the same. We nee | hariomsharma70 | NORMAL | 2025-02-19T08:18:23.038967+00:00 | 2025-02-19T08:18:23.038967+00:00 | 7 | false | # Intuition
The problem requires generating "happy strings" of length n using the characters {a, b, c} such that no two consecutive characters are the same. We need to return the k-th lexicographically smallest happy string.
A brute-force approach would be generating all possible valid strings and then returning the k-th smallest one. Since the constraints are small (n ≤ 10), this approach is feasible.
# Approach
Generate all valid happy strings
1:-Use a recursive function (generate) to build strings of length n.
Ensure that no two consecutive characters are the same.
Store the valid strings in a list (ls).
Retrieve the k-th happy string
2:-Since the strings are generated in lexicographical order (abc first, then acb, etc.), the k-th string is simply the (k-1)-th element in the list.
If k is greater than the number of generated strings, return "" (an empty string).
# Complexity
- Time complexity:
The recursive function generates all possible valid strings. The number of valid happy strings for a given n is approximately 2 * 3^(n-1).
Sorting is not needed since strings are generated in lexicographical order.
Overall, the time complexity is O(3^n) in the worst case.
- Space complexity:
The recursion depth is O(n).
The list ls stores all valid strings, which is O(3^n) in the worst case.
Thus, the total space complexity is O(3^n).
# Code
```java []
class Solution {
public String getHappyString(int n, int k) {
ArrayList<String> ls=new ArrayList<>();
generate(n,"",ls);
if(k>ls.size())return "";
return ls.get(k-1);
}
public static void generate(int n,String s,ArrayList<String> ls){
if(n==s.length()){
ls.add(s);
return;
}
String st="abc";
for(char i:st.toCharArray()){
if(s.length()==0 || s.charAt(s.length()-1)!=i)
generate(n,s+i,ls);
}
return;
}
}
``` | 3 | 0 | ['Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Backtracking approach. Beats 100% | backtracking-approach-beats-100-by-nnzl4-xyhu | IntuitionThe problem requires generating lexicographically sorted happy strings of lengthnand returning thek-th string. Since happy strings are built with const | nnzl48NW9N | NORMAL | 2025-02-19T05:29:31.263094+00:00 | 2025-02-19T05:29:31.263094+00:00 | 57 | false | # Intuition
The problem requires generating lexicographically sorted happy strings of length `n` and returning the `k`-th string. Since happy strings are built with constraints, a backtracking approach is suitable for generating valid strings while counting them.

# Approach
1. Backtracking to Generate Happy Strings:
- Recursively build the happy string character by character.
- Ensure that no two consecutive characters are the same.
- Use a decrementing `k` counter to find the `k`-th string.
2. Base Case:
- If the generated string reaches length `n`, decrement `k`.
- If `k` becomes `0`, return `true` to stop further recursion.
3. Recursive Character Selection:
- Iterate over the set `{ 'a', 'b', 'c' }`.
- Append the character only if it is different from the last character.
- If recursion finds the `k`-th string, return early.
- Backtrack by removing the last appended character.
# Complexity
- Time complexity: O(3^n)
as there are three choices for each of `n` positions.
- Space complexity: O(n)
for storing the recursion stack and the resulting string.
# Code
```cpp []
class Solution {
private:
bool f(string& happy, int& n, int& k){
// base case
if(happy.size() == n){
return --k == 0 ;
}
for(char ch = 'a'; ch <= 'c'; ch++){
if(!happy.empty() && happy.back() == ch) continue;
happy.push_back(ch);
if(f(happy, n, k)) return true;
happy.pop_back();
}
return false;
}
public:
string getHappyString(int n, int k) {
string happy = "";
if(f(happy, n, k)) return happy;
return "";
}
};
```

| 3 | 0 | ['String', 'Backtracking', 'String Matching', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✅✅Beats 100%🔥C++🔥Python|| 🚀🚀Super Simple and Efficient Solution🚀🚀||🔥Python🔥C++✅✅ | beats-100cpython-super-simple-and-effici-eztl | Complexity
Time complexity:O(3n)
Space complexity:O(3n)
⬆️👇⬆️UPVOTE it⬆️👇⬆️Code⬆️👇⬆️UPVOTE it⬆️👇⬆️ | shobhit_yadav | NORMAL | 2025-02-19T04:00:45.767872+00:00 | 2025-02-19T04:00:45.767872+00:00 | 184 | false | # Complexity
- Time complexity: $$O(3^n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(3^n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
⬆️👇⬆️UPVOTE it⬆️👇⬆️
# Code
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
const unordered_map<char, string> nextLetters{
{'a', "bc"}, {'b', "ac"}, {'c', "ab"}};
queue<string> q{{{"a", "b", "c"}}};
while (q.front().length() != n) {
const string u = q.front();
q.pop();
for (const char nextLetter : nextLetters.at(u.back()))
q.push(u + nextLetter);
}
if (q.size() < k)
return "";
for (int i = 0; i < k - 1; ++i)
q.pop();
return q.front();
}
};
```
```python []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
nextLetters = {'a': 'bc', 'b': 'ac', 'c': 'ab'}
q = collections.deque(['a', 'b', 'c'])
while len(q[0]) != n:
u = q.popleft()
for nextLetter in nextLetters[u[-1]]:
q.append(u + nextLetter)
return '' if len(q) < k else q[k - 1]
```
⬆️👇⬆️UPVOTE it⬆️👇⬆️
| 3 | 0 | ['String', 'Backtracking', 'C++', 'Python3'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simple & Easy C++ Solution || Backtracking | simple-easy-c-solution-backtracking-by-s-kuwn | if it's help, please up ⬆ vote! ❤️Code | shishirRsiam | NORMAL | 2025-02-19T02:52:05.853405+00:00 | 2025-02-19T02:52:05.853405+00:00 | 313 | false |
# if it's help, please up ⬆ vote! ❤️
# Code
```cpp []
class Solution {
public:
string s = "abc", ans;
void backtrack(string cur, int &n, int &k, int &count)
{
if(count == k) return;
if(cur.size() == n)
{
ans = cur, count += 1;
return;
}
for(auto ch : s)
{
if(cur.size() and ch == cur.back()) continue;
backtrack(cur + ch, n, k, count);
}
}
string getHappyString(int n, int k)
{
int count = 0;
backtrack("", n, k, count);
return count == k ? ans : "";
}
};
``` | 3 | 0 | ['String', 'Backtracking', 'Greedy', 'Recursion', 'C++'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Basic loop and Most easiest and intuitve solution you can find. Beats 100% | basic-loop-and-most-easiest-and-intuitve-bh4b | IntuitionMy basic intuition is based on simple number of combinations. By simple law of counting(Permuatations), the total number of strings possible are 3*(2^( | avinoor19460 | NORMAL | 2025-02-19T01:00:13.511333+00:00 | 2025-02-19T01:00:13.511333+00:00 | 106 | false | # Intuition
My basic intuition is based on simple number of combinations. By simple law of counting(Permuatations), the total number of strings possible are 3*(2^(n - 1)) where n is length of string. Now if we fix one character position at a time we can determine number of permutations from there on, and can subtract the number of possibilities.
# Approach
Now first total number of possibilities per starting letter = 2^(n-1). Hence we iterate through each character and see if it fits the count of K. if not we move to next character. as it is dealt with the number of possibilities are reduced. Then we can assign character for that position and also check whether previous character is same or not
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n*3) ~ O(n)
- Space complexity:
O(n)
# Code
```cpp []
class Solution {
public:
string getHappyString(int n, int k) {
int i = 0;
string s = "";
string possible = "abc";
int total = pow(2, n - 1);
char prev = '*';
while(i < n){
for(char ch : possible){
if(ch == prev) continue;
if(k > total)
k -= total;
else{
// cout<<"s";
s += ch;
prev = ch;
break;
}
}
total /= 2;
i++;
}
if(s.length() != n) return "";
return s;
}
};
``` | 3 | 0 | ['C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Binary Partitioning Trick to Find the k-th Lexicographical Happy String in O(n) Time | binary-partitioning-trick-to-find-the-k-30h9w | IntuitionThe problem requires generating a lexicographically sorted list of "happy" strings of lengthnand returning thek-th one.A happy string is a string where | alperensumeroglu | NORMAL | 2025-02-19T00:50:34.404536+00:00 | 2025-02-19T00:50:34.404536+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem requires generating a lexicographically sorted list of "happy" strings of length `n` and returning the `k`-th one.
A happy string is a string where no two adjacent characters are the same and only consists of 'a', 'b', and 'c'.
Instead of generating all possible strings, we use a structured approach to find the k-th string efficiently.
# Approach
<!-- Describe your approach to solving the problem. -->
1. Each position in the happy string can be determined by dividing the possibilities into partitions.
2. We first compute the number of happy strings of length `n-1` to determine partition sizes.
3. The first character is chosen by dividing `k` by the number of partitions per character.
4. Using a loop, we progressively determine each character by selecting a different one than the last chosen.
5. We update `k` accordingly and continue until the full string is constructed.
# Complexity
- Time complexity: **O(n)**
Since we construct the happy string character by character in `O(n)`, our approach is efficient compared to generating all possible strings.
- Space complexity: **O(1)**
We only store a few variables and the output string, so our space usage is constant.
# Code
```python3 []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
"""
Find the k-th lexicographical happy string of length n.
A happy string consists of characters 'a', 'b', 'c' where no two adjacent characters are the same.
"""
# Compute the number of happy strings of length `n-1`
partition_size = 2 ** (n - 1)
# If k is greater than the total possible happy strings, return an empty string
if k > 3 * partition_size:
return ""
# Determine the first character of the happy string
index = (k - 1) // partition_size
result = ['a', 'b', 'c'][index]
# Construct the rest of the happy string
while partition_size > 1:
k = (k - 1) % partition_size + 1 # Update k within the new partition
partition_size //= 2 # Reduce partition size
# Choose the next character that is different from the last character
if result[-1] == 'a':
next_char = ['b', 'c'][(k - 1) // partition_size]
elif result[-1] == 'b':
next_char = ['a', 'c'][(k - 1) // partition_size]
else:
next_char = ['a', 'b'][(k - 1) // partition_size]
result += next_char # Append chosen character to result
return result
``` | 0 | 0 | ['Python3'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | TOO MUCH AURA OVERLOAD!!! Beats 99% Java DFS Solution ULTIMATE RIZZZZZZZZZZZZZZZZZZZZZZZZZZZZ | beats-99-java-dfs-solution-by-ishaan_p-5pd9 | Just create the strings in lexicographic order using DFS, so we can avoid the sorting step altogether. Stop when we reach the kth string.Code | Ishaan_P | NORMAL | 2025-02-19T00:44:56.365073+00:00 | 2025-02-19T04:31:20.798338+00:00 | 582 | false | Just create the strings in lexicographic order using DFS, so we can avoid the sorting step altogether. Stop when we reach the kth string.
# Code
```java []
class Solution {
String result= "";
int count = 0;
public String getHappyString(int n, int k) {
buildHappyStrings(n,k,new StringBuilder());
return result;
}
public void buildHappyStrings(int n, int k, StringBuilder sb){
if(sb.length() == n){
count++;
if(count == k){
result = sb.toString();
return;
}
}
int sbLen = sb.length();
if(sbLen < n && count < k){
for(char c = 'a'; c <='c'; c++){
if(sbLen == 0 || sb.charAt(sbLen-1) != c){
sb.append(c);
buildHappyStrings(n,k,sb);
sb.deleteCharAt(sbLen);
}
}
}
}
}
``` | 3 | 0 | ['Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | C# - Fast - 0ms - binary/trinary radix math | c-fast-0ms-binarytrinary-radix-math-by-h-220s | IntuitionThis is mostly just a conversion of a number to binary since most (all but the first) letter can only be one of two values since the previous letter ma | hafthor | NORMAL | 2025-02-19T00:29:42.721311+00:00 | 2025-02-19T16:07:02.257617+00:00 | 247 | false | # Intuition
This is mostly just a conversion of a number to binary since most (all but the first) letter can only be one of two values since the previous letter makes one choice of three forbidden. If the bit is 0, we pick the lowest available letter. If the bit is 1, we pick the highest available letter. The first letter is special since it can be any of the three. We convert the number `k` into binary and plug the bits in starting at the end going up to the first letter position, which is trinary. We then sweep the char array forward, setting the actual letters instead of the bits.
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: $$O(n)$$
- Space complexity: $$O(n)$$ - only because we build the result in a char array before converting that to a string
# Code
```csharp []
public class Solution {
public string GetHappyString(int n, int k) {
char[] ca=new char[n];
k--; // adjust down since k=1 is the first possibility
// all except the first character can be one of two possibilities
// set from least significant bit
for(int i=n-1; i>0; i--, k>>=1) { // backwards
ca[i]=(char)(k&1); // write bit
}
// if first not 0-2, we are out of range
if(k>2) return "";
// set first letter
char prev=ca[0]=(char)('a'+k);
// set remaining letters
for(int i=1; i<n; i++) {
// prev=a:next=b,c - prev=b:next=a,c - prev=c:next=a,b
prev=ca[i]="bcacab"[((prev-'a')<<1)+ca[i]];
}
return new string(ca);
}
}
```
# Bonus : Alternate Solution
Here's a solution I came up with that uses StringBuilder on a single pass.
```csharp []
public class Solution {
public string GetHappyString(int n, int k) {
k--; // decrement k since we want k to be 0-based, not 1-based
int shr=n; // number of bits to shift right
int trit=k>>--shr; // read highest "bit" out of k (but allowed to be 2)
if(trit>2) return ""; // return "" if trit was > 2
StringBuilder s=new(n);
for(;;) {
s.Append((char)('a'+trit)); // write out letter
if(shr==0) return s.ToString(); // return result
int bit=(k>>--shr)&1; // read bit out of k
// convert bit to trit
bit+=1-((trit+1)>>1); // increment if trit was 0 (a) - a,b becomes b,c
bit<<=trit&1; // b becomes c if trit was 1 (b) - a,b becomes a,c
// leave alone if trit was 2 (c) - a,b left as a,b
trit=bit; // save for next loop
}
}
}
```
# Bonus : Code Golf
```csharp []
public class Solution {
public string GetHappyString(int n, int k) { // 103 characters
var s="";for(int t=--k>>--n;;t=((k>>n)%2<<t++%2)+1-t/2){s+=(char)(97+t);if(--n<0||t>2)return t>2?"":s;}
}
}
``` | 3 | 0 | ['Math', 'C#'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 🚀 Easy | Backtracking | JavaScript Solution | easy-backtracking-javascript-solution-by-zquc | Approach / Intuition
Backtracking Approach: We generate all possible happy strings of lengthnusing backtracking, ensuring that no two adjacent characters are th | dharmaraj_rathinavel | NORMAL | 2025-02-19T00:29:18.375873+00:00 | 2025-02-20T03:05:00.627532+00:00 | 106 | false | ## **Approach / Intuition**
- **Backtracking Approach**: We generate all possible happy strings of length `n` using backtracking, ensuring that no two adjacent characters are the same.
- **Recursive Exploration**: At each step, we append characters `'a'`, `'b'`, or `'c'` to the current string, skipping characters that match the last appended character.
- **Tracking the k-th Happy String**: We maintain a counter (`happyStringsCount`) to count valid happy strings as we generate them. Once we reach the `k`-th happy string, we store it and stop further recursion.
- **Pruning Unnecessary Computation**: As soon as the `k`-th happy string is found, we terminate further recursive calls early to optimize performance.
- **Edge Case Handling**: If there are fewer than `k` valid happy strings, we return an empty string (`""`).
⬆️ Upvote, if you understand the approach.
## Complexity
- Time complexity: O(2ⁿ) (Worst case, generating all possible happy strings)
- Space complexity: O(n) (Recursion stack depth)
## Code
```javascript []
/**
* @param {number} n
* @param {number} k
* @return {string}
*/
var getHappyString = function (n, k) {
let happyStringsCount = 0,
characters = ['a', 'b', 'c'],
happyString = "";
const backtrack = function (str) {
// Base case: happy string of length 'n' is formed
if (str.length == n) {
if (happyStringsCount == k - 1) {
happyString = str;
return true; // Stop further recursion
}
happyStringsCount++;
return false;
}
const prevChar = str.at(-1);
for (const char of characters) {
if (char == prevChar) continue;
if (backtrack(str + char)) return true;
}
return false;
}
backtrack("");
return happyString;
};
``` | 3 | 0 | ['String', 'Backtracking', 'JavaScript'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Simple, intuitive solution with no backtracking in C++. | simple-intuitive-solution-with-no-backtr-h3xa | Approach\nWe have just mapped the string "abc" and traverse through every position so that to place appropriate letter at given word.\n\nWe can observe the patt | k_patil092 | NORMAL | 2023-08-03T04:42:24.887401+00:00 | 2023-08-03T04:42:24.887436+00:00 | 136 | false | # Approach\nWe have just mapped the string "abc" and traverse through every position so that to place appropriate letter at given word.\n\nWe can observe the pattern we will get after arranging in lexicographically order. For example n = 4:\n\n<"abab", "abac", "abca", "abcb">, <"acab", "acac", "acba", "acbc">,\n<"baba", "babc", "baca", "bacb">, <"bcab", "bcac", "bcba", "bcbc">,\n<"caba", "cabc", "caca", "cacb">, <"cbab", "cbac", "cbca", "cbcb">\n\nWe can observw the pattern changing at 2\'s power.\n\nWe are trying to get the index of the mapping which we could easily get by modulus of remainder with 2^(position) and if previously the letter has already taken then we will add one to answer to get next letter.\n\n# Complexity\n- Time complexity: O(n)\n- Space complexity:O(1)\n\n# Code\n```\nclass Solution {\npublic:\n string getHappyString(int n, int k) {\n\n // Out of bound condition\n if(k>3*pow(2,n-1)) return "";\n string s = "";\n int prev = 4;\n string mapping = "abc";\n\n int m = n - 1, i = k - 1;\n while(m >= 0){\n int power = pow(2, m);\n int q = i / power;\n i %= power;\n m -= 1;\n\n if(prev <= q) q += 1;\n s += mapping[q];\n prev = q;\n }\n return s;\n }\n};\n```\n\n## !!! PLEASE UPVOTE !!!\n\n\n\n\n | 3 | 0 | ['String', 'Brainteaser', 'Ordered Map', 'Suffix Array', 'Combinatorics', 'Interactive', 'Hash Function', 'C++'] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | ✅C++ || Same as Cobination sum-1 || Backtracking | c-same-as-cobination-sum-1-backtracking-e07ux | \n\nThis Que is same as Leetcode Combination sum-1\n\nT->O(2^n) && S->O(n) [Recursion Stack Space]\n\n\tclass Solution {\n\tpublic:\n\t\tvector v;\n\t\tvoid f(i | abhinav_0107 | NORMAL | 2022-08-20T06:33:26.928054+00:00 | 2022-08-20T06:33:26.928103+00:00 | 460 | false | \n\n***This Que is same as Leetcode Combination sum-1***\n\n**T->O(2^n) && S->O(n) [Recursion Stack Space]**\n\n\tclass Solution {\n\tpublic:\n\t\tvector<string> v;\n\t\tvoid f(int i,string& s,int n){\n\t\t\tif(i==n){\n\t\t\t\tv.push_back(s);\n\t\t\t\treturn ;\n\t\t\t}\n\t\t\tfor(char j=\'a\';j!=\'d\';j++){\n\t\t\t\tif(i>0 && j==s[i-1]) continue;\n\t\t\t\ts.push_back(j);\n\t\t\t\tf(i+1,s,n);\n\t\t\t\ts.pop_back();\n\t\t\t}\n\t\t}\n\n\t\tstring getHappyString(int n, int k) {\n\t\t\tstring s="";\n\t\t\tf(0,s,n);\n\t\t\tsort(v.begin(),v.end());\n\t\t\tif(k>v.size()) return "";\n\t\t\treturn v[k-1];\n\t\t}\n\t}; | 3 | 0 | ['Backtracking', 'Recursion', 'C', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Python] Bruteforce and optimized solution | python-bruteforce-and-optimized-solution-occn | Brute force solution by generating all possible combinations and selecting the kth entry. O(2^n) [580ms]\n\nclass Solution(object):\n def getHappyString(self | johnnydu | NORMAL | 2020-04-20T01:17:19.872409+00:00 | 2020-04-20T01:23:32.065255+00:00 | 278 | false | **Brute force solution by generating all possible combinations and selecting the kth entry. O(2^n) [580ms]**\n```\nclass Solution(object):\n def getHappyString(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: str\n """\n result = self.listCombinations(n, \'\')\n if k > len(result):\n return \'\'\n return \'\'.join(result[k-1])\n \n def listCombinations(self, n, ignoreLetter):\n if n == 0:\n return [[]]\n \n allLetters = \'abc\'\n result = []\n for letter in allLetters:\n if letter == ignoreLetter:\n continue\n result.extend(map(lambda x: [letter] + x, self.listCombinations(n-1, letter)))\n return result\n```\n\n**Instead of generating all combinations we figure out the next letter one by one. O(n) [20ms]**\n```\nimport math\n\nclass Solution(object):\n def getHappyString(self, n, k):\n """\n :type n: int\n :type k: int\n :rtype: str\n """\n letters = [\'a\', \'b\', \'c\']\n \n result = \'\'\n prevLetter = None\n while n > 0:\n nextLetters = filter(lambda x: x != prevLetter, letters)\n selection = int(math.ceil((k-1) / (2**(n-1))))\n if selection >= len(nextLetters):\n return \'\'\n \n result += nextLetters[selection]\n prevLetter = nextLetters[selection]\n k = k - (selection * 2**(n-1))\n n -= 1\n return result | 3 | 0 | [] | 2 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Java] Simple backtracking | java-simple-backtracking-by-rajeshtomar-vfkh | Just backtrack to generate all the strings and store them in a list. Return the appropriate element from list.\n\nclass Solution {\n \n List<String> list | rajeshtomar | NORMAL | 2020-04-18T17:01:08.591599+00:00 | 2020-04-18T17:01:08.591652+00:00 | 428 | false | Just backtrack to generate all the strings and store them in a list. Return the appropriate element from list.\n```\nclass Solution {\n \n List<String> list = new ArrayList<>();\n \n void rec(int n, StringBuilder sb) {\n if (n == 0) {\n list.add(sb.toString());\n return;\n }\n \n char c = sb.charAt(sb.length()-1);\n if (c == \'a\') {\n sb.append(\'b\');\n rec(n-1, sb);\n sb.setLength(sb.length() - 1);\n sb.append(\'c\');\n rec(n-1, sb);\n sb.setLength(sb.length() - 1);\n }\n \n if (c == \'b\') {\n sb.append(\'a\');\n rec(n-1, sb);\n sb.setLength(sb.length() - 1);\n sb.append(\'c\');\n rec(n-1, sb);\n sb.setLength(sb.length() - 1);\n }\n \n if (c == \'c\') {\n sb.append(\'a\');\n rec(n-1, sb);\n sb.setLength(sb.length() - 1);\n sb.append(\'b\');\n rec(n-1, sb);\n sb.setLength(sb.length() - 1);\n }\n }\n \n public String getHappyString(int n, int k) {\n \n StringBuilder sb = new StringBuilder();\n sb.append(\'a\');\n rec(n-1, sb);\n sb.setLength(sb.length() - 1);\n \n sb.append(\'b\');\n rec(n-1, sb);\n sb.setLength(sb.length() - 1);\n \n sb.append(\'c\'); \n rec(n-1, sb);\n sb.setLength(sb.length() - 1);\n return k > list.size() ? "" : list.get(k-1);\n }\n}\n``` | 3 | 0 | [] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Java O(n) solution | java-on-solution-by-s_tsat-jida | The solution is based on the fact that there are 3 choices for the first character and 2 for each subsequent one.\nOn each step, I append the corresponding char | s_tsat | NORMAL | 2020-04-18T16:31:30.996011+00:00 | 2020-06-29T22:29:50.400933+00:00 | 338 | false | The solution is based on the fact that there are 3 choices for the first character and 2 for each subsequent one.\nOn each step, I append the corresponding character based on k.\n\n```\n public String getHappyString(int n, int k) {\n \n k--; // this is to make arithmetic a bit easier\n int power = 1 << (n-1);\n \n\t\t// the total number of happy strings is 3*2^(n-1), so the first character is:\n\t\t// \'a\' if k < 2^(n-1)\n\t\t// \'b\' if 2^(n-1) <= k < 2*2^(n-1)\n\t\t// \'c\' if 2*2^(n-1) <= k < 3*2^(n-1)\n\t\t\n char current = (char)(k/power + \'a\');\n if (current > \'c\') return "";\n StringBuilder ans = new StringBuilder();\n ans.append(current); \n\n for (int i = 1; i <= n - 1; i++){\n k = k % power;\n power = power >> 1;\n \n\t\t\t// there are two possibilities for the next character\n // if the current k is >= than the 2^(n-i-1), append the greater possible character\n // otherwise append the smaller one\n\t\t\t\n char newChar = \'a\';\n if (current == \'a\') newChar++;\n if (k >= power) newChar++;\n if (current == newChar) newChar++; \n ans.append(newChar);\n \n current = newChar;\n }\n \n return ans.toString(); \n } | 3 | 0 | ['Java'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [Python] Fast solution using divmod - No DFS (100% / 100%) | python-fast-solution-using-divmod-no-dfs-8wuu | The idea of this solution comes from 60. Permutation Sequence. \n\n\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n # now k star | alanlzl | NORMAL | 2020-04-18T16:21:43.147779+00:00 | 2020-04-30T04:11:48.530872+00:00 | 283 | false | The idea of this solution comes from [60. Permutation Sequence](https://leetcode.com/problems/permutation-sequence/). \n\n```\nclass Solution:\n def getHappyString(self, n: int, k: int) -> str:\n # now k starting from index 0\n k -= 1\n \n bucket_size = (2 ** (n - 1))\n bucket_index, k = divmod(k, bucket_size)\n \n # edge case\n if bucket_index >= 3:\n return \'\'\n \n self.mapping = {\'a\': \'bc\', \'b\': \'ac\', \'c\': \'ab\'}\n return self.get_happy_string_recu(n - 1, k, bucket_size, chr(ord(\'a\') + bucket_index))\n \n \n def get_happy_string_recu(self, n, k, bucket_size, s):\n # base\n if n == 0:\n return s\n \n bucket_size = bucket_size // 2\n bucket, index = divmod(k, bucket_size)\n \n curr_char = self.mapping[s[-1]][bucket]\n return self.get_happy_string_recu(n - 1, index, bucket_size, s + curr_char)\n``` | 3 | 0 | [] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | [C++] Simple search for k-th string O(n) | c-simple-search-for-k-th-string-on-by-ni-palo | Here we always keep a count of strings starting with a, b, and c .i.e. ca, cb, cc respectively.\nWe maintain these counts and for every index we see what charac | nicmit | NORMAL | 2020-04-18T16:02:52.221470+00:00 | 2020-04-18T16:04:25.227195+00:00 | 293 | false | Here we always keep a count of strings starting with a, b, and c .i.e. `ca, cb, cc` respectively.\nWe maintain these counts and for every index we see what character needs to come here. This is similar to dictionary idea.\n```\nclass Solution {\npublic:\n int f(int n)\n {\n if(n == 0)\n return 0;\n if(n == 1)\n return 3;\n return 3 * pow(2, n - 1);\n }\n string getHappyString(int n, int k) {\n int c = f(n);\n if(c < k)\n return "";\n string s;\n int ca = pow(2, n - 1);\n int cb = 2*ca, cc = 3*ca;\n while(n--)\n {\n // cout << k << " ";\n if(k <= ca)\n {\n s.push_back(\'a\');\n }\n else if(k <= cb)\n {\n if(s.empty())\n k -= ca;\n else\n {\n if(s.back() == \'a\')\n {}\n else\n k -= ca;\n }\n s.push_back(\'b\');\n }\n else if(k <= cc)\n {\n if(s.empty())\n k -= cb;\n else\n {\n if(s.back() == \'b\')\n k -= ca;\n else\n k -= cb;\n }\n s.push_back(\'c\');\n }\n if(s.back() == \'a\')\n {\n ca = 0;\n cb = pow(2, n - 1);\n cc = 2*cb;\n }\n else if(s.back() == \'c\')\n {\n ca = pow(2, n - 1);\n cb = 2*ca;\n cc = 0; \n }\n else if(s.back() == \'b\')\n {\n ca = pow(2, n - 1);\n cc = 2*ca;\n cb = 0; \n }\n }\n return s;\n }\n};\n``` | 3 | 1 | [] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Beats 100% || step by step clearly Explained | beats-100-clearly-explained-by-aadithya1-ep7t | IntuitionKnow which character will be our next character and simply add it.ApproachWe have only 3 characters we can use.So, the valid words of n = 1 will be:a,b | aadithya18 | NORMAL | 2025-02-19T17:53:22.951120+00:00 | 2025-02-19T20:46:46.168855+00:00 | 9 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Know which character will be our next character and simply add it.
# Approach
<!-- Describe your approach to solving the problem. -->
We have only 3 characters we can use.
So, the valid words of n = 1 will be: `a,b,c`. in the same order.
For n = 2 will be `ab, ac, ba, bc, ca, cb` in the order.
For n = 3 will be `aba, abc, aca, acb, bab, bac, bca, bcb, cab, cac, cba, cbc` in the same order.
The order is important because we need lexicographically increasing order.
Now, if you try to observe a pattern,
1. we have initially 3. Then as we shouldn't have 2 same consecutive characters, we add other 2 characters for each of them.
2. i.e., we add `a` for `b,c` to get `ab, ac`. `b` for `a,c` to get `ba, bc`. `c` for `a,b` to get `ca, cb`.
3. In the same way, we when we need to add one more character in the set, for `a` we consider the 4 strings which starts with `b, c` and so on.
Hence, the pattern is clear here, we always add other two characters to one character.
Also, the order will be clear if we look at the examples above.
The smallest always starts with `a`, the next set starts with `b` and then `c`.
So, in this way for `1` we have `3` options.
For n = 2, we will have `2 x 3 = 6` options.
For n = 3, we will have `2 x 6 = 12` options. and so on.
If we try to get 9th string for n = 3.
We will have a total of 12 combinations. We know we will have 3 different sets based on the starting character with 4 different combinations each.
As we want the 9th one, it is will fall under 3rd set (4 of a, 4 of b, and 4 of c) So, we know the 1st character will be `c`. Now, we know the next character cannot be `c` but `a` or `b`. Now, if you observe the result once, `cab, cac, cba, cbc`, you will see 2 `a`s and 2 `b`s. So, as they also come in that order (lexicographically, a < b) we can calculate which next set we need to look into. That is, in the set of `c`, the 9th one will become 1st one of 4 (Mathematically, 9%4 = 1). Hence, we now do the same calculation we did before but we have 2 sets now, with 2 elements each. Hence, as we need the 1st string it will fall under 1st set. So, our next letter will be `a`. String formed until now is `ca`. Now, in the first set, we again will have 2 sets. In them, as we need the 1st one, it will fall under the 1st set again. This the set will have only `b,c` and 1st set means `b`. So next letter is `b`. String formed is `cab`.
In this way, without actually forming all the strings, we can exactly form the string we need.
That's it guys. Hope you understood and could follow it.
If you have any questions or suggestions please leave a comment below.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n)$$ -- As we are only traversing n times to find n characters.
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(1) -- Only constant extra space is used.
Thank you for travelling through this roller coaster journey of coding with me.
Please \ **UPVOTE**\ if you enjoyed the ride.
# Code
```cpp []
class Solution {
public:
int fact(int n){
if(n == 1) return 3;
return 2*fact(n-1);
}
string getHappyString(int n, int k) {
int fa = fact(n);
if(fa < k) return "";
string s="";
k--;
int a = 1<<(n-1);
vector<char> v{'a', 'b', 'c'};
unordered_map<char, vector<char>> map;
map['a'] = {'b','c'};
map['b'] = {'a','c'};
map['c'] = {'a','b'};
while(a){
int r = (k)/a;
s+=v[r];
k = k%a;
a/=2;
v = map[v[r]];
}
return s;
}
};
```
Thank you,
aadithya18. | 2 | 0 | ['String', 'Backtracking', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Combinatorics Trick [Python] | Obligatory Beats 100% | combinatorics-trick-by-shirsho12-ctgr | IntuitionNotice that in this question, we have 3 choices for the first character, and 2 for each of the subsequent ones. In fact, as the result is ordered, we n | shirsho12 | NORMAL | 2025-02-19T17:33:14.639725+00:00 | 2025-02-19T17:35:26.285712+00:00 | 16 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Notice that in this question, we have 3 choices for the first character, and 2 for each of the subsequent ones. In fact, as the result is ordered, we notice that `0` -> smaller character, `1` -> larger character.
# Approach
<!-- Describe your approach to solving the problem. -->
In the given example
`n = 3`, `k = 9`
`["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]`
For `k=1` to `k=4`
Character 1 = `a`
For `k=5` to `k=8`
Character 1 = `b`
For `k=9` to `k=12`
Character 1 = `c`
For `k=1` to `k=2`
Character 2 = `b`
For `k=3` to `k=4`
Character 2 = `c`
For `k=5` to `k=6`
Character 2 = `a`
...
At this point the pattern becomes clear. So the trick is to take $$k$$ $$mod$$ $$2^{n - 1}$$ and convert it to binary. The first character will be $$k$$ $$div$$ $$2^{n - 1}$$.
The only thing to note is when the previous character is `a`, the binary `0` will now point to `b` and `1` to `c`.
# Complexity
For a string of length $$n$$:
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def getHappyString(self, n: int, k: int) -> str:
# The first char is in base 3, the rest in base 2
base = 2 ** (n - 1)
num_strings = 3 * base
if k > num_strings:
return ''
chars = ['a', 'b', 'c']
if n == 1:
return chars[k - 1]
k -= 1
v = k // base
res = chars[v]
k = k % base
# convert k to binary
z = bin(k)[2:]
z = '0' * (n - 1 - len(z)) + z
prev_char = res
for pos in z:
v = int(pos)
if prev_char == 'a':
v += 1 # add 1 to shift assignment
c = chars[v]
if prev_char == c:
c = chars[(v + 1) % 3]
res += c
prev_char = c
return res
``` | 2 | 0 | ['String', 'Combinatorics', 'Python3'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | beats 100% || very simple logic | beats-100-very-simple-logic-by-shashwat1-d2rd | Code | shashwat1915 | NORMAL | 2025-02-19T16:18:24.332408+00:00 | 2025-02-19T16:18:24.332408+00:00 | 23 | false | # Code
```cpp []
class Solution {
public:
string ans="";
void get_ans(int n,int &k,string &ans1,vector<char>&arr){
if(!ans.empty()) return;
if(ans1.length()>n) return;
if(k==0 && ans1.length()==n){
ans=ans1;
return;
}
int x=-1;
if(!ans1.empty()){
if(ans1.back()=='a') x=0;
if(ans1.back()=='b') x=1;
if(ans1.back()=='c') x=2;
}
for(int i=0;i<3;i++){
if(i==x) continue;
ans1+=arr[i];
if(ans1.size()==n) k--;
get_ans(n,k,ans1,arr);
// if(ans1.size()==n) k++;
ans1.pop_back();
}
}
string getHappyString(int n, int k) {
vector<char>arr={'a','b','c'};
string ans1="";
get_ans(n,k,ans1,arr);
return ans;
}
};
``` | 2 | 0 | ['String', 'Backtracking', 'C++'] | 0 |
the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | Easy Solution || Simple Approach || C++ || Backtracking | easy-solution-simple-approach-c-backtrac-u256 | IntuitionWe need to generate all "happy strings" of length n, where a happy string is one that does not have two identical consecutive characters. Instead of tr | Santhosh_TechWriter | NORMAL | 2025-02-19T15:19:27.428599+00:00 | 2025-02-19T15:19:27.428599+00:00 | 29 | false | # Intuition
We need to generate all "happy strings" of length n, where a happy string is one that does not have two identical consecutive characters. Instead of trying to generate all strings and then filtering out the invalid ones, we can build each string character by character while ensuring we never add the same character twice in a row. By following a lexicographical order (choosing 'a', then 'b', then 'c'), we naturally generate the happy strings in order.
# Approach
<ul>
<li>Start with empty string <code>temp</code>.</li>
<li>At each step append character <code>a or b or c</code>to the <code>temp</code>string.</li>
<li>Check if the <code>temp</code> string has 2 equal consecutive characters. If yes, then avoid that string.</li>
<li>Add the happy string <code>temp</code> to the list <code>happy</code>.</li>
<li>Return the k-th lexicographical happy string <code>happy[k-1].</code></li>
</ul>
# Complexity
- Time complexity:
$$O(3^n)$$
- Space complexity:
$$O(3^n)$$
# Code
```cpp []
class Solution
{
public:
void generate(int ind,int n,string temp,vector<string>& happy)
{
int m=temp.size();
if(m>1 && temp[m-1]==temp[m-2])
return;
if(ind==n)
{
happy.push_back(temp);
return;
}
generate(ind+1,n,temp+'a',happy);
generate(ind+1,n,temp+'b',happy);
generate(ind+1,n,temp+'c',happy);
return;
}
string getHappyString(int n, int k)
{
vector<string>happy;
generate(0,n,"",happy);
int m=happy.size();
return (k<=m)?happy[k-1]:"";
}
};
``` | 2 | 0 | ['Backtracking', 'C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.