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
find-the-count-of-monotonic-pairs-i
Using 3D Dp
using-3d-dp-by-venkatarohit_p-4rue
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
venkatarohit_p
NORMAL
2024-08-12T03:53:21.158234+00:00
2024-08-12T03:53:21.158258+00:00
13
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 // static int count;\n public int solve(int[] nums,int idx,int prev,int prev1,int[][][] dp){\n if(idx==nums.length){\n // count++;\n return 1;\n }\n if(dp[idx][prev][prev1]!=-1){\n return dp[idx][prev][prev1];\n }\n int ans=0;\n for(int i=prev;i<=nums[idx];i++){\n if(prev<=i && nums[idx]-i<=prev1){\n ans=(ans+ solve(nums,idx+1,i,nums[idx]-i,dp))%(1000000007);\n }\n }\n dp[idx][prev][prev1]=ans;\n\n return dp[idx][prev][prev1];\n\n \n \n }\n public int countOfPairs(int[] nums) {\n int idx=0;\n int prev=0;\n int prev1=50;\n int k=0;\n // count=0;\n int[][][] dp=new int[nums.length][51][51];\n for(int i=0;i<nums.length;i++){\n for(int j=0;j<51;j++){\n for(int k1=0;k1<51;k1++){\n dp[i][j][k1]=-1;\n }\n }\n }\n return solve(nums,idx,prev,prev1,dp);\n \n // return count;\n }\n}\n```
0
0
['Java']
0
find-the-count-of-monotonic-pairs-i
[python3] simple dp
python3-simple-dp-by-vl4deee11-1daw
\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n @cache\n def dp(la,i):\n if i>=len(nums):return 1\n
vl4deee11
NORMAL
2024-08-12T03:21:25.618567+00:00
2024-08-12T03:26:39.297491+00:00
1
false
```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n @cache\n def dp(la,i):\n if i>=len(nums):return 1\n a=0\n lb=nums[i-1]-la if la!=-1 else -1\n for na in range(la if la!=-1 else 0,nums[i]+1):\n nb=nums[i]-na\n if nb>lb and lb!=-1:continue\n a+=dp(na,i+1)%1000000007\n return a%1000000007;\n return dp(-1,0)\n```
0
0
[]
0
find-the-count-of-monotonic-pairs-i
trivial dp solution
trivial-dp-solution-by-sovlynn-j87b
Intuition\nThis is a typical dp problem. Let $dp_i[n]$ be the solution which the increasing ends with $n$ and the decreasing ends with $num[i]-n$, we have.\n\nd
sovlynn
NORMAL
2024-08-12T02:07:47.065694+00:00
2024-08-12T08:25:34.555646+00:00
13
false
# Intuition\nThis is a typical dp problem. Let $dp_i[n]$ be the solution which the increasing ends with $n$ and the decreasing ends with $num[i]-n$, we have.\n\n$$dp_i[n]=\\sum_j^{j\\leq n &&nums[i-1]-j\\geq nums[i]-i}dp_{i-1}[j]$$\n\nThat is, for all prev pairs $(j, nums[i-1]-j)$, it should fullfill the increasing or decreasing condition.\n\nUse prefix sum to accelerate.\n\n# Complexity\n\n- Time complexity:\n$$O(\\sum nums)$$\n\n- Space complexity:\n$$O(\\textit{MAX}(nums))$$\n\n# Code\n```\nimpl Solution {\n pub fn count_of_pairs(nums: Vec<i32>) -> i32 {\n let MOD=1000000007usize;\n let mut prev=nums[0] as usize;\n let mut dp=vec![1; prev+1];\n for &n in &nums[1..]{\n let n=n as usize;\n for i in 1..dp.len(){\n dp[i]+=dp[i-1];\n dp[i]%=MOD;\n }\n let mut cur=vec![0; n+1];\n if prev>=n{\n cur.clone_from_slice(&dp[..=n]);\n }else{\n cur[n-prev..=n].clone_from_slice(&dp);\n }\n\n prev=n;\n dp=cur;\n }\n let mut res=0;\n for n in dp{\n res+=n;\n res%=MOD;\n }\n res as i32\n }\n}\n```
0
0
['Dynamic Programming', 'Prefix Sum', 'Rust']
0
find-the-count-of-monotonic-pairs-i
[C++] 2D-DP problem, consider every sub-problems
c-2d-dp-problem-consider-every-sub-probl-gxq2
Intuition\n Describe your first thoughts on how to solve this problem. \nFor every arr1[i], take one number from [1,50] and caclulate the rest\n\n# Approach\n D
tony2037
NORMAL
2024-08-11T22:48:33.151253+00:00
2024-08-11T22:48:33.151314+00:00
14
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor every `arr1[i]`, take one number from `[1,50]` and caclulate the rest\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n`dp[i][s]`: the number of pairs for `nums[i:]` when `arr1[i-1] == s`\ngiven a choice `x` (from `[1,50]`) we evaluate the conditions:\n1. `s <= x`\n2. `y = nums[i]-x`\n3. `prev_y >= y`\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe number of the sub-problems = $$O(n*50)$$ = $$O(n)$$\nto solve each sub-problem we will have to look up at most 50 calculations\nSo the overall TC = $$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(50 * n)$$\n\n# Code\n```\nclass Solution {\npublic:\n static constexpr long long MOD = 1e9 + 7;\n int helper(vector<vector<long long>> &dp, vector<int> &nums, int i, int prev) {\n const int n = nums.size();\n if (i >= n) return 1;\n if (dp[i][prev] != -1) return dp[i][prev];\n long long ans = 0;\n int cur = nums[i];\n\n for (int x = 0; x <= 50; x++) {\n if (x > cur) continue;\n if (x < prev) continue;\n int y = cur - x;\n int prev_y = i > 0 ? nums[i-1] - prev : INT_MAX;\n if (y > prev_y) continue;\n ans += helper(dp, nums, i+1, x);\n ans %= MOD;\n }\n return dp[i][prev] = ans;\n }\n\n int countOfPairs(vector<int>& nums) {\n const int n = nums.size();\n vector<vector<long long>> dp(n, vector<long long>(52, -1));\n return helper(dp, nums, 0, 0);\n }\n};\n```
0
0
['C++']
0
find-the-count-of-monotonic-pairs-i
Java 2D DP
java-2d-dp-by-sarvesh412-lx8j
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
sarvesh412
NORMAL
2024-08-11T22:19:02.241087+00:00
2024-08-11T22:19:02.241119+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 int count=0;\n public int countOfPairs(int[] nums) {\n int[][] dp = new int[nums.length][52];\n for(int[] i:dp){Arrays.fill(i,-1);}\n return move(0,nums,51,dp);\n }\n public int move(int index, int[] nums, int prev1,int[][] dp){\n int ans=0;\n if(index==nums.length){\n return 1;\n }\n if(dp[index][prev1]!=-1){return dp[index][prev1];}\n for(int j=0;j<=nums[index];j++){\n int arr1 = j;\n int arr2 = nums[index]-j;\n int prev2 = index>0?nums[index-1]-prev1:51;\n if(index>0 && (arr1<prev1 || arr2>prev2)){continue;}\n else ans=(ans+move(index+1,nums,arr1,dp))%1000000007;\n }\n return dp[index][prev1]=ans;\n }\n}\n```
0
0
['Java']
0
find-the-count-of-monotonic-pairs-i
Java 3D DP
java-3d-dp-by-robertskonieczny-q30x
There are more elegant solutions, but this is mine.\n\njava\nclass Solution {\n private int[][][] memo;\n public int countOfPairs(int[] nums) {\n t
robertskonieczny
NORMAL
2024-08-11T21:15:55.898794+00:00
2024-08-11T21:15:55.898824+00:00
9
false
There are more elegant solutions, but this is mine.\n\n```java\nclass Solution {\n private int[][][] memo;\n public int countOfPairs(int[] nums) {\n this.memo = new int[nums.length][51][51];\n for (int[][] rowrow : memo) for (int[] row : rowrow) Arrays.fill(row, -1);\n return dp(nums, 0, 0, nums[0]);\n }\n\n private int dp(int[] nums, int i, int min, int max) {\n if (i >= nums.length) {\n return 1;\n }\n\n if (memo[i][min][max] != -1) {\n return memo[i][min][max];\n }\n\n int res = 0;\n int startMin = min;\n int startMax = max;\n\n // arr2 should be the max\n // arr1 should be the min\n\n while (max >= 0 && min <= nums[i]) {\n if (min + max == nums[i]) {\n res += dp(nums, i + 1, min, max);\n res %= 1000000007;\n min++;\n max--;\n } else if (min + max > nums[i]) {\n max--;\n } else {\n min++;\n }\n }\n\n return memo[i][startMin][startMax] = res;\n }\n}\n```
0
0
['Java']
0
find-the-count-of-monotonic-pairs-i
[C++] Top-down DP Solution
c-top-down-dp-solution-by-samuel3shin-b7rt
Code\n\nclass Solution {\npublic:\n int N;\n const int MOD = 1e9 + 7;\n unordered_map<int, int> memo;\n\n int getKey(int idx, int prev1, int prev2)
Samuel3Shin
NORMAL
2024-08-11T20:09:56.243445+00:00
2024-08-11T20:09:56.243465+00:00
9
false
# Code\n```\nclass Solution {\npublic:\n int N;\n const int MOD = 1e9 + 7;\n unordered_map<int, int> memo;\n\n int getKey(int idx, int prev1, int prev2) {\n return idx*50*50 + prev1*50 + prev2;\n }\n\n int helper(vector<int>& nums, int idx, int prev1, int prev2) {\n if(idx==N) return 1;\n int key = getKey(idx, prev1, prev2);\n if(memo.count(key))return memo[key];\n\n int res = 0;\n for(int x=prev1; x<=nums[idx]; x++) {\n int y = nums[idx] - x;\n if(y <= prev2) {\n res = (res + helper(nums, idx+1, x, y)) % MOD;\n }\n }\n\n return memo[key] = res;\n }\n\n int countOfPairs(vector<int>& nums) {\n N = nums.size();\n return helper(nums, 0, 0, nums[0]);\n }\n};\n```
0
0
['C++']
0
find-the-count-of-monotonic-pairs-i
Dynamic Programming Easy Solution
dynamic-programming-easy-solution-by-san-sse1
Approach\nDynamic Programming\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity: O(N3)\n Add your time complexity here, e.g.
SandeepPatel0605
NORMAL
2024-08-11T19:45:20.248131+00:00
2024-08-11T19:45:20.248157+00:00
6
false
# Approach\nDynamic Programming\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N**3)\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\n int countMonotonicPairs(int i, int prevArr1, int prevArr2, const vector<int>& nums, vector<vector<vector<int>>>& dp) {\n const int MOD = 1e9 + 7;\n int n = nums.size();\n\n if (i == n)\n return 1;\n\n if (dp[i][prevArr1][prevArr2] != -1)\n return dp[i][prevArr1][prevArr2];\n\n int totalCount = 0;\n\n for (int arr1_i = prevArr1; arr1_i <= nums[i]; ++arr1_i) {\n int arr2_i = nums[i] - arr1_i;\n\n if (arr2_i <= prevArr2) {\n totalCount =\n (totalCount +\n countMonotonicPairs(i + 1, arr1_i, arr2_i, nums, dp)) %\n MOD;\n }\n }\n\n return dp[i][prevArr1][prevArr2] = totalCount;\n }\n\n int countOfPairs(vector<int>& nums) {\n ios::sync_with_stdio(false);\n\n int n = nums.size();\n\n vector<vector<vector<int>>> dp(\n n, vector<vector<int>>(51, vector<int>(51, -1)));\n\n return countMonotonicPairs(0, 0, 50, nums, dp);\n }\n};\n```
0
0
['C++']
0
find-the-count-of-monotonic-pairs-i
Simple DP C++
simple-dp-c-by-gps_357-bmda
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
gps_357
NORMAL
2024-08-11T19:39:58.759717+00:00
2024-08-11T19:39:58.759738+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(2500*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(50*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n\n int n,mod = 1e9+7;\n vector<int> a,b,nums;\n int dp[2001][51];\n int rec(int index ,int previ ,int prevj){\n if(index == n){\n return 1;\n }\n //cout<<previ<<" "<<prevj<<endl;\n\n if(dp[index][previ] != -1) return dp[index][previ];\n int ans = 0;\n for(int i=previ;i<=nums[index];i++){\n if( (nums[index] - i)<=prevj){\n ans = (ans+(rec(index+1,i,nums[index] - i))%mod)%mod;\n }\n }\n\n return dp[index][previ] = ans;\n }\n\n int countOfPairs(vector<int>& num) {\n nums = num;\n n = num.size();\n memset(dp,-1,sizeof(dp));\n return rec(0,0,51);\n\n }\n};\n```
0
0
['C++']
0
find-the-count-of-monotonic-pairs-i
Easy | Most intuitive approach
easy-most-intuitive-approach-by-gaurav_5-8ddj
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
gaurav_592
NORMAL
2024-08-11T18:59:36.660718+00:00
2024-08-11T18:59:36.660753+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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```\n\nclass Solution {\npublic:\n int MOD = 1e9 + 7;\n\n int solve(vector<vector<vector<long>>>& dp, const vector<int>& nums, int n, int a, int b, int i) {\n if (i >= n) return 1;\n if (dp[i][a][b] != -1) return dp[i][a][b];\n\n int cnt = 0;\n\n for (int k = a; k <= nums[i]; k++) {\n int b_new = nums[i] - k;\n if (b_new <= b) {\n cnt = (cnt + solve(dp, nums, n, k, b_new, i + 1)) % MOD;\n }\n }\n\n return dp[i][a][b] = cnt;\n }\n\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n vector<vector<vector<long>>> dp(n, vector<vector<long>>(51, vector<long>(51, -1)));\n return solve(dp, nums, n, 0, nums[0], 0);\n }\n};\n```
0
0
['C++']
0
find-the-count-of-monotonic-pairs-i
✅Simple recursive solution
simple-recursive-solution-by-akash_sonar-8h4l
Intuition\nIf a + b = c , then if we choose a = x then b = c-x. We just simply brute force all possiblities recursively and check if we can form c. To avoid TLE
Akash_Sonar
NORMAL
2024-08-11T18:36:27.066817+00:00
2024-08-11T18:36:27.066859+00:00
14
false
# Intuition\nIf `a + b = c` , then if we choose `a = x` then `b = c-x `. We just simply brute force all possiblities recursively and check if we can form `c`. To avoid **TLE** we use memoization.\n\n\n# Complexity\n- Time complexity:\nO(2000 * 50)\n\n- Space complexity:\nO(n * 50 * 50)\n\n# Code\n```\nclass Solution {\n private final int M = 1000000007;\n\n public int countOfPairs(int[] nums) {\n int dp[][][] = new int[nums.length][51][51];\n for (int i = 0; i < dp.length; i++) {\n for (int j = 0; j < 51; j++) {\n for (int k = 0; k < 51; k++) {\n dp[i][j][k] = -1;\n }\n }\n }\n return rec(nums, 0, 0, 50, dp);\n }\n\n public int rec(int nums[], int idx, int start, int prevY, int dp[][][]) {\n if (idx == nums.length)\n return 1;\n\n if (dp[idx][start][prevY] != -1)\n return dp[idx][start][prevY];\n\n int target = nums[idx], res = 0;\n for (int i = start; i <= target; i++) {\n if (target - i <= prevY) {\n res = (res + rec(nums, idx + 1, i, target - i, dp)) % M;\n }\n }\n dp[idx][start][prevY] = res;\n return res;\n }\n}\n```
0
0
['Memoization', 'Java']
0
find-the-count-of-monotonic-pairs-i
Go, concise
go-concise-by-gvnpl-y9oa
\nvar h map[int]map[int]int\n\nfunc solve(nums []int, i int, prevInc int) int {\n if i == len(nums) {\n return 1\n }\n if m, ok := h[i]; ok {\n
gvnpl
NORMAL
2024-08-11T16:52:03.560680+00:00
2024-08-11T16:52:03.560710+00:00
1
false
```\nvar h map[int]map[int]int\n\nfunc solve(nums []int, i int, prevInc int) int {\n if i == len(nums) {\n return 1\n }\n if m, ok := h[i]; ok {\n if v, ok := m[prevInc]; ok {\n return v\n }\n } else {\n h[i] = map[int]int{}\n }\n ans := 0\n \n for inc := prevInc; inc <= nums[i]; inc++ {\n dec := nums[i] - inc\n if i == 0 || dec <= nums[i - 1] - prevInc {\n ans = (ans + solve(nums, i + 1, inc)) % 1000000007\n }\n }\n h[i][prevInc] = ans\n return ans\n}\n\nfunc countOfPairs(nums []int) int {\n h = map[int]map[int]int{}\n ans := solve(nums, 0, 0)\n //fmt.Println(h)\n return ans\n}\n```
0
0
['Dynamic Programming', 'Go']
0
find-the-count-of-monotonic-pairs-i
[Backtracking-> DP] Python Beats 100% on time | Interview Though Process
backtracking-dp-python-beats-100-on-time-hsoq
Intuition\n\nThe most brute force way ( also backtracking solution) is to try every possible combination of numebrs on each index, from left to right and once
satyamsaini97
NORMAL
2024-08-11T16:02:54.370600+00:00
2024-08-11T16:02:54.370630+00:00
41
false
# Intuition\n\nThe most brute force way ( also backtracking solution) is to try every possible combination of numebrs on each index, from left to right and once you have filled the array, +1 the count. \n\n\n# Code - Backtracking ( TLE)\n```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n MOD=10**9+7\n n = len(nums)\n count = 0\n\n # Iterate over all possible pairs (arr1, arr2)\n def dfs(i, prev1, prev2):\n nonlocal count\n if i == n:\n count = (count + 1) % MOD\n return\n\n for arr1_i in range(prev1, nums[i] + 1):\n arr2_i = nums[i] - arr1_i\n if arr2_i <= prev2:\n dfs(i + 1, arr1_i, arr2_i)\n\n dfs(0, 0, nums[0])\n return count\n\n\n```\n\n\nFor the DP part, you visualize that there may be an overlap down the line when you changed ith index in arr_1. So you memoise.\n\n\n# Complexity\nConsidering n to be the number in the array and m to be values each can take, n <2000 and m < 50\n\nThis is for the DP solution:\n\n- Time complexity: $$O(m*n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ for the recursion and $$O(m*m*n)$$ for the storage .\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code ( DP With Memoization) - TC\n\nAll I did extra here was to use @lru_cache(None) line and it now memoizes the solution, making it DP.\n\n```\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n MOD=10**9+7\n n = len(nums)\n\n @lru_cache(None)\n def dfs(i, prev1, prev2):\n if i == n:\n return 1\n total_count = 0\n for arr1_i in range(prev1, nums[i] + 1):\n arr2_i = nums[i] - arr1_i\n if arr2_i <= prev2:\n total_count += dfs(i + 1, arr1_i, arr2_i)\n total_count %= MOD\n return total_count\n ## fist index is the current index You are working on , 2nd thing is the curr value for arr1 aand 3rd thing is the curr value for arr2\n return dfs(0, 0, nums[0])\n```
0
0
['Dynamic Programming', 'Memoization', 'Python3']
0
find-the-count-of-monotonic-pairs-i
Math for DP Problem
math-for-dp-problem-by-yanganyi-n2fe
Intuition\n Describe your first thoughts on how to solve this problem. \nthis should be dynamic programming!\n\n# Approach\n Describe your approach to solving t
yanganyi
NORMAL
2024-08-11T15:47:04.033293+00:00
2024-08-11T15:47:04.033350+00:00
34
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthis should be dynamic programming!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nmathmathmathmathmath\n\nwe first get the values in arr2 by finding `b = i - a` where `a = max(a, i - b)`\n\nwe then perform combi on `min(arr2) + len(arr2)` and `len(arr2)`\nmod as the question asks and we achieve the ultimate #proofbyAC with math!\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nfrom math import comb\n\nclass Solution:\n def countOfPairs(self, nums: List[int]) -> int:\n MOD = 10**9 + 7\n a = 0; b = nums[0]\n arr1 = [a]; arr2 = [b]\n\n for i in nums[1:]:\n a = max(a, i - b); b = i - a\n arr1.append(a)\n arr2.append(b)\n \n t = min(arr2)\n \n if t < 0: return 0\n\n n = len(arr2)\n \n return comb(t + n, n) % MOD\n```
0
0
['Python3']
0
find-the-count-of-monotonic-pairs-i
Easy Memoization Approach
easy-memoization-approach-by-shaanpatel9-f9fu
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
shaanpatel9889
NORMAL
2024-08-11T15:38:04.742940+00:00
2024-08-11T15:38:04.742973+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 int mod=1e9+7;\n int fun(int ind,int prev1,int prev2,int n,vector<int>&nums,vector<vector<vector<int>>>&dp)\n {\n if(ind==n-1)\n {\n int count=0;\n for(int i=0;i<=nums[ind];i++)\n {\n if(i>=prev1 && (nums[ind]-i)<=prev2)\n {\n count=(count+1)%mod;\n }\n }\n return count;\n }\n\n if(dp[ind][prev1][prev2]!=-1)\n {\n return dp[ind][prev1][prev2];\n }\n\n int ways=0;\n for(int i=0;i<=nums[ind];i++)\n {\n if(i>=prev1 && (nums[ind]-i)<=prev2)\n {\n ways = (ways + fun(ind+1,i,nums[ind]-i,n,nums,dp))%mod;\n }\n }\n return dp[ind][prev1][prev2]=ways;\n } \npublic:\n int countOfPairs(vector<int>& nums) {\n int n=nums.size();\n vector<vector<vector<int>>>dp(n,vector<vector<int>>(52,vector<int>(52,-1)));\n return fun(0,0,51,n,nums,dp);\n }\n};\n```
0
0
['C++']
0
find-the-count-of-monotonic-pairs-i
Easy DP with Loop || Full Explanation || NSUT Pro coder
easy-dp-with-loop-full-explanation-nsut-i14la
Intuition & Approach\nWhen Question asked to find all possible sub arrays it means we have to ry every combination which basically means DP.\n\nNow when you ana
beastgm10
NORMAL
2024-08-11T14:48:40.589190+00:00
2024-08-11T14:48:40.589235+00:00
10
false
# Intuition & Approach\nWhen Question asked to find all possible sub arrays it means we have to ry every combination which basically means DP.\n\nNow when you analyse the conditions given, we can figure out that loop is required in this case to check all cases.\n\nFor ease first write the recurrsive code then memoize it using 3D dp then convert it to 2D dp by slight modification.\n\n# Complexity\n- Time complexity:\nO(n^2))\n\n- Space complexity:\nO(n) + O(2000n) ~ O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int MOD = 1e9 + 7;\n\n int solve(int i, vector<int>& nums, int prev1, vector<vector<int>>& dp) {\n if (i == nums.size()) return 1;\n\n if (dp[i][prev1+1]!= -1) return dp[i][prev1+1];\n\n int val = nums[i];\n int cnt = 0;\n int k;\n\n if(prev1 == -1)k=0;\n else k=prev1;\n\n for (; k <= val; k++) {\n if (prev1==-1 || prev1 <= k && nums[i-1]-prev1 >= val - k) {\n cnt = (cnt + solve(i + 1, nums, k, dp)) % MOD;\n }\n }\n\n return dp[i][prev1+1]= cnt;\n }\n\n int countOfPairs(vector<int>& nums) {\n int n = nums.size();\n vector<vector<int>> dp(n, vector<int>(2001, -1));\n\n return solve(0, nums, -1, dp); \n }\n};\n\n```
0
0
['Dynamic Programming', 'C++']
0
find-the-count-of-monotonic-pairs-i
Golang solution
golang-solution-by-comp1exo-86oj
Intuition\n Describe your first thoughts on how to solve this problem. \ni referred this video as i have problem framing solution while attempting in contest \n
comp1exo
NORMAL
2024-08-11T14:29:01.310877+00:00
2024-08-11T14:29:01.310918+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ni referred this video as i have problem framing solution while attempting in contest \nvideo link : https://www.youtube.com/watch?v=2VkxY6a8z8g\n# Approach\n<!-- Describe your approach to solving the problem. -->\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```\nfunc countOfPairs(nums []int) int {\n n := len(nums)\n mod := 1000_000_000+7\n memo := make([][]int, n)\n for i := range memo {\n memo[i] = make([]int, 52)\n for j := range memo[i] {\n memo[i][j] = -1\n }\n }\n return recursion(0,memo, 0, nums, mod )\n}\n\nfunc recursion(idx int, memo [][]int, pv1 int, nums []int, mod int) int {\n if idx == len(nums) {\n return 1\n }\n if memo[idx][pv1] != -1 {\n return memo[idx][pv1]\n }\n sum := 0\n\n for i := pv1; i <= nums[idx]; i++ {\n v2 := nums[idx]-i\n if idx == 0 || v2 <= nums[idx-1]-pv1 {\n sum = (sum + recursion(idx+1, memo, i, nums, mod)) % mod\n } \n }\n memo[idx][pv1] = sum % mod\n return sum % mod\n\n}\n```
0
0
['Go']
0
find-the-count-of-monotonic-pairs-i
Java Memorization using 2D array| Beasts 100% Runtime
java-memorization-using-2d-array-beasts-359x2
Intuition\n Describe your first thoughts on how to solve this problem. \n\n\n# Approach\n- left+right=nums[i];\n- so, if we keep on iteration left and to valida
harish_hk
NORMAL
2024-08-11T12:23:47.169929+00:00
2024-08-11T12:23:47.169952+00:00
16
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n- left+right=nums[i];\n- so, if we keep on iteration left and to validated right is decreasing\nget prevRight by ( nums[i-1]-leftPrev)\n\n- left=PrevLeft;\n- i=newLeft;\n- so new Right should be lesser than prevRight\n```\nif(nums[ind-1]-left>=nums[ind]-i){\n//then use that i value \n}\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 int mod=1000000007;\n public int helper(int left, int ind, int[] nums,int dp[][]){\n if(ind>=nums.length) return 1;\n \n if(left>50) return 0;\n if(dp[left][ind]!=-1) return dp[left][ind];\n int count=0;\n for(int i=left;i<=nums[ind];i++){ \n if(ind>0){\n if(nums[ind-1]-left>=nums[ind]-i){\n count+= ( helper(i, ind+1,nums,dp) );\n count%=mod;\n }\n }\n else{\n count+= ( helper(i, ind+1,nums,dp) );\n count%=mod;\n }\n }\n return dp[left][ind]=count;\n }\n public int countOfPairs(int[] nums) {\n int start=nums[0];\n int dp[][]=new int[51][nums.length];\n for(int[]arr:dp){\n Arrays.fill(arr,-1);\n }\n return helper(0,0,nums,dp);\n \n }\n}\n```
0
0
['Java']
0
find-the-count-of-monotonic-pairs-i
DP
dp-by-aman_mangukiya-262b
Intuition : Dp\n Describe your first thoughts on how to solve this problem. \n\n\n# Complexity\n- Time complexity: ~O(n^3)\n Add your time complexity here, e.g.
Aman_mangukiya
NORMAL
2024-08-11T12:09:49.340161+00:00
2024-08-11T12:09:49.340192+00:00
3
false
# Intuition : Dp\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Complexity\n- Time complexity: ~O(n^3)\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```\n#define mod 1000000007\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n vector<vector<int>>dp(nums.size()+1,vector<int>(60,0));\n\n for(int i=0;i<=nums[0];i++) dp[0][i]++;\n\n\n for(int i=1;i<nums.size();i++){\n \n for(int j=0;j<=nums[i];j++){\n \n for(int p=0;p<=nums[i-1];p++){\n \n int a1=p,a2=nums[i-1]-p;\n\n if( a1<=j && a2>=nums[i]-j){\n dp[i][j] = (dp[i][j] + dp[i-1][p])%mod;\n }\n\n\n }\n\n\n\n }\n\n }\n\nint ans=0;\n \n for(int j=0;j<dp[0].size();j++){\n ans=(ans +dp[nums.size()-1][j])%mod;\n }\n\n \n \n\n return ans;\n }\n};\n```
0
0
['C++']
0
find-the-count-of-monotonic-pairs-i
beginner friendly memoization using 2d dp
beginner-friendly-memoization-using-2d-d-mc4r
class Solution {\n public int mod = (int)1e9+7;\n public int countOfPairs(int[] nums) {\n int maxi = 0 ; \nfor(int i = 0 ; i< nums.length ; i++)
shivanshuagrawal
NORMAL
2024-08-11T12:05:50.679339+00:00
2024-08-11T12:05:50.679370+00:00
9
false
class Solution {\n public int mod = (int)1e9+7;\n public int countOfPairs(int[] nums) {\n int maxi = 0 ; \nfor(int i = 0 ; i< nums.length ; i++){\nmaxi = Math.max(maxi,nums[i]);\n}\nint dp[][] = new int[nums.length+1][maxi+1];\nfor(int x[] : dp) Arrays.fill(x,-1);\nreturn memoization(nums,dp,0,0 ,50);\n\n }\n int memoization(int nums[] , int dp[][] ,int idx, int prev1, int prev2){\n\nif(idx == nums.length){\n return 1; \n}\n\nif(dp[idx][prev1] != -1) return dp[idx][prev1];\nlong count = 0 ; \nfor(int i = 0;i<=nums[idx]; i++){\n if( i >= prev1 && nums[idx]-i<= prev2){\n count = count%mod + (memoization(nums,dp,idx+1,i,nums[idx]-i))%mod;\n }\n}\nreturn dp[idx][prev1] = (int)count ; \n\n }\n}\n \n``
0
0
['Array', 'Java']
0
find-the-count-of-monotonic-pairs-i
2d memoization dp || O(n*51*51) || c++
2d-memoization-dp-on5151-c-by-sarthakrau-po0f
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
sarthakrautelanew
NORMAL
2024-08-11T11:16:23.026106+00:00
2024-08-11T11:16:23.026137+00:00
12
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\no(n*51*51)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n*51)\n# Code\n```\nclass Solution {\npublic:\n using ll =long long;\n ll mod=1e9+7;\n ll solve(int idx,vector<int>&nums,int lst1,vector<vector<int>>&dp){\n if(idx==nums.size())\n return 1;\n \n if(dp[idx][lst1]!=-1)\n return dp[idx][lst1];\n\n int lst2=idx>0 ? nums[idx-1]-lst1 : 50;\n ll ans=0;\n for(int curr=lst1;curr<=nums[idx];curr++){\n int x=nums[idx]-curr;\n if(x<=lst2){\n ans+=solve(idx+1,nums,curr,dp);\n ans%=mod;\n }\n }\n return dp[idx][lst1]=ans;\n }\n int countOfPairs(vector<int>& nums) {\n vector<vector<int>>dp(nums.size(),vector<int>(51,-1));\n return solve(0,nums,0,dp); \n }\n};\n```
0
0
['Dynamic Programming', 'Memoization', 'C++']
0
find-the-count-of-monotonic-pairs-i
C++ | DP solution
c-dp-solution-by-mihirb77-v7fz
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
mihirb77
NORMAL
2024-08-11T11:12:52.880175+00:00
2024-08-11T11:12:52.880204+00:00
10
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 {\npublic:\n int countOfPairs(vector<int>& nums) {\n int n = nums.size(); \n vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(51, vector<int>(51, 0))); \n\n int num = nums[0];\n for (int k = 0; k <= num; k++) { \n int l = abs(num - k);\n dp[0][k][l] = 1;\n }\n\n for (int i = 1; i < n; i++) { \n int num = nums[i-1]; \n for (int j = 0; j <= num; j++) {\n int k = num - j;\n int curr=nums[i];\n for (int l = 0; l <= curr; l++) { \n int x=abs(curr-l);\n if(l>=j && x<=k){\n dp[i][l][x] = (dp[i][l][x] + dp[i-1][j][k]) % 1000000007 ;\n }\n }\n }\n }\n\n int ans = 0;\n for (int i = 0; i <= 50; i++) { \n for (int j = 0; j <= 50; j++) { \n ans = (ans + dp[n-1][i][j]) % 1000000007;\n }\n }\n return ans;\n }\n};\n\n```
0
0
['C++']
0
find-the-count-of-monotonic-pairs-i
Contest 410 || DP
contest-410-dp-by-sajaltiwari007-0dec
Approach and Intuition\n\nThe problem appears to be related to counting valid sequences or pairs based on certain constraints. The approach used is dynamic prog
sajaltiwari007
NORMAL
2024-08-11T11:07:08.366103+00:00
2024-08-11T11:07:08.366136+00:00
8
false
### Approach and Intuition\n\nThe problem appears to be related to counting valid sequences or pairs based on certain constraints. The approach used is dynamic programming (DP) to solve the problem.\n\n#### Intuition:\n1. **Dynamic Programming Table (`dp`)**: \n - The `dp` array is a 3D table where `dp[i][a][b]` represents the number of valid ways to process the subarray `nums[i...n-1]` given that the last chosen numbers in the sequence were `a` and `b`.\n - `a` and `b` are adjusted by `+1` to handle the index correctly, as `a` can be `-1`, representing no prior selection.\n\n2. **Recursive Helper Function**:\n - The function `helper(nums, ind, a, b, dp)` recursively tries to form valid pairs `(x, y)` from the current element `nums[ind]` by iterating from `0` to `nums[ind]`.\n - For each split `(x, y)`, where `x + y = nums[ind]`, it checks if the split is valid by comparing `x` with `a` and `y` with `b`.\n - If valid, it adds the result of the recursive call for the next index (`ind + 1`) to the current count.\n\n3. **Base Case**:\n - The base case (`ind == nums.length`) returns `1`, indicating that a valid sequence has been formed.\n\n4. **Memoization**:\n - The results of subproblems are stored in the `dp` array to avoid recomputation and reduce time complexity.\n\n5. **Modulo Operation**:\n - Since the number of ways can be large, the result is taken modulo `1000000007` to avoid overflow.\n\n### Time and Space Complexity:\n\n- **Time Complexity**:\n - The time complexity is approximately `O(n * 52 * 52 * m)`, where `n` is the length of the array `nums` and `m` is the maximum value in `nums`.\n - The loop runs `m` times for each recursive call, and there are up to `52 * 52` states for `a` and `b` at each step.\n\n- **Space Complexity**:\n - The space complexity is `O(n * 52 * 52)` due to the DP array `dp`, which stores intermediate results.\n - Additional space is used for the recursion stack, which can go up to `O(n)`.\n\nOverall, this approach is efficient given the constraints and ensures that the problem is solved within acceptable time limits using dynamic programming and memoization techniques.\n\n# Code\n```\nclass Solution {\n private static final int MOD = 1_000_000_007;\n\n public int countOfPairs(int[] nums) {\n int[][][] dp = new int[nums.length + 1][52][52];\n for (int i = 0; i < nums.length + 1; i++) {\n for (int j = 0; j < 52; j++) {\n for (int k = 0; k < 52; k++) {\n dp[i][j][k] = -1;\n }\n }\n }\n return helper(nums, 0, 51, 51, dp); \n }\n\n int helper(int[] nums, int ind, int a, int b, int[][][] dp) {\n if (ind == nums.length) return 1;\n\n if (dp[ind][a][b] != -1) return dp[ind][a][b];\n\n int take = 0;\n for (int i = 0; i <= nums[ind]; i++) {\n int x = i;\n int y = nums[ind] - i;\n if ((a == 51 || a <= x) && (b == 51 || b >= y)) {\n take += helper(nums, ind + 1, x, y, dp);\n take %= MOD;\n }\n }\n\n return dp[ind][a][b] = take;\n }\n}\n\n```
0
0
['Dynamic Programming', 'Memoization', 'Java']
0
find-the-count-of-monotonic-pairs-i
🔥2D DP | C++| Tabulation | intutive | EASY | 100%Beats 🔥🚩🔥🚩
2d-dp-c-tabulation-intutive-easy-100beat-vc4t
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
aryan_0510
NORMAL
2024-08-11T10:52:21.714853+00:00
2024-08-11T10:52:21.714880+00:00
10
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(50*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(50*N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countOfPairs(vector<int>& nums) {\n int n=nums.size(),mod=1e9+7;\n vector<vector<int>> dp(n,vector<int>(51,-1));\n for(int i=0;i<=nums[0];i++){\n dp[0][i]=i+1;\n }\n for(int i=1;i<n;i++){\n for(int j=0;j<=nums[i];j++){\n dp[i][j]=0;\n int k=j;\n while(k>=0 && (dp[i-1][k]==-1 || (nums[i-1]-k)<(nums[i]-j))){\n k--;\n }\n if(k>=0){\n dp[i][j]=dp[i-1][k];\n }\n if(j>0){\n dp[i][j]=(dp[i][j]+dp[i][j-1])%mod;\n }\n }\n }\n return dp[n-1][nums[n-1]];\n }\n};\n```
0
0
['Dynamic Programming', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
✅ Beginner friendly easy solution ( Image explanation)
beginner-friendly-easy-solution-image-ex-l2xm
Important: If you want to learn and understand the patterns in problems and want to solve them using a single template you should definitely check my youtube ch
rishi800900
NORMAL
2023-10-14T16:04:33.897551+00:00
2023-10-14T20:08:05.956973+00:00
2,396
false
#### **Important:** If you want to learn and understand the patterns in problems and want to solve them using a single template you should definitely check my youtube channel by clicking my leetcode profile or search "**coding samurai**" on youtube. Template taught: sweepline, sliding window, backtracting and many more coming.......![image](https://assets.leetcode.com/users/images/7e2ba9a4-be57-4498-bc39-8d85f29062d0_1697301399.0947742.png)\n\n### **Update: You may watch the video solution now on my channel for this problem.**\n\n![image](https://assets.leetcode.com/users/images/5f76d60a-6469-4488-8f8c-8fdb1330d1d3_1697306059.4602497.png)\n![image](https://assets.leetcode.com/users/images/7a95a67e-d37e-4810-87d7-01ccb9d6ee5b_1697306818.0160432.png)\n![image](https://assets.leetcode.com/users/images/a71a194a-6cbe-464e-8241-eb0d5ff364b5_1697307793.0674558.png)\n![image](https://assets.leetcode.com/users/images/a305b5fa-ac80-4968-a35e-e9c4cdc346a5_1697308574.03936.png)\n\n\n\n```\nclass Solution {\npublic:\n \n int calculate_ham_dist(string w1, string w2){\n int hamdist= 0;\n \n for (int k = 0; k < w1.size(); k++)\n {\n\n if (w1[k] != w2[k])\n {\n hamdist++;\n if (hamdist > 1) break;\n }\n }\n return hamdist;\n }\n \n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<vector<string>> dp(n); // dp[i] stores the longest subsequence ending at index i\n\n for (int i = 0; i < n; i++) {\n dp[i].push_back(words[i]);\n }\n\n int maxLength = 1; // Initialize with the minimum length\n\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < i; j++) {\n \n if (groups[j] != groups[i] && words[j].size() == words[i].size()) { // checking the condition given in problem\n \n int hamDist = calculate_ham_dist(words[i], words[j]);\n \n if (hamDist == 1) // if all condition satisfied\n { \n if (dp[j].size() + 1 > dp[i].size()) // and check whether from this index you are getting max length subsequence\n { \n dp[i] = dp[j]; // Copy the longest subsequence found so far \n dp[i].push_back(words[i]);\n maxLength = max(maxLength, int(dp[i].size()));\n }\n }\n }\n }\n }\n\n vector<string> longestSubsequence;\n for (int i = 0; i < n; i++) \n {\n if (dp[i].size() == maxLength) \n { \n longestSubsequence = dp[i];\n break; // Break when the first longest subsequence is found\n }\n }\n\n return longestSubsequence;\n }\n};\n```
27
1
['Dynamic Programming', 'C']
6
longest-unequal-adjacent-groups-subsequence-ii
LIS + Parent (Greedy Fail 🔥) || (Easy Video Solution with all scenarios) 🔥 || C++ || JAVA
lis-parent-greedy-fail-easy-video-soluti-tag6
Intuition\n Describe your first thoughts on how to solve this problem. \nI recommend breaking down the problem into smaller parts and, with small examples, visu
ayushnemmaniwar12
NORMAL
2023-10-14T18:11:20.718737+00:00
2023-10-14T18:11:20.718761+00:00
1,156
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI* recommend breaking down the problem into smaller parts and, with small examples, visually simulate the different scenarios. Consider various ways to solve the problem, and eventually, you\'ll find a solution that works.*\n\n# ***Detailed and easy Video Solution***\n\nhttps://youtu.be/84Y4BDsl8d8\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo find the longest subsequence of words with one edit, I use dynamic programming to store the length and previous index of the longest subsequence ending at each index. Then, I backtrack through the previous index vector to reconstruct the subsequence.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N*N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n\n```C++ []\nclass Solution {\npublic:\n bool check(string &a,string &b)\n {\n int n=a.size()-1,m=b.size()-1;\n if(n!=m)\n return 0;\n int c=0;\n while(n>=0)\n {\n if(a[n]!=b[n])\n c++;\n n--;\n }\n return c==1;\n }\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<int>dp(n+1,1);\n vector<int>prev(n+1,-1);\n int maxdp=1,maxprev=0;\n for(int i=0;i<n;i++)\n { \n for(int j=i-1;j>=0;j--)\n {\n string a=words[i],b=words[j];\n if(groups[j]!=groups[i])\n {\n bool k=check(a,b);\n if(k)\n { \n if(1+dp[j]>dp[i])\n {\n dp[i]=1+dp[j];\n prev[i]=j;\n if(dp[i]>maxdp)\n {\n maxdp=dp[i];\n maxprev=i;\n }\n }\n }\n }\n }\n }\n vector<string>res;\n res.push_back(words[maxprev]);\n while(prev[maxprev]!=-1)\n {\n res.push_back(words[prev[maxprev]]);\n maxprev=prev[maxprev];\n }\n reverse(res.begin(),res.end());\n return res;\n \n }\n};\n```\n```Python []\nclass Solution:\n def check(self, a, b):\n n = len(a) - 1\n m = len(b) - 1\n if n != m:\n return 0\n c = 0\n while n >= 0:\n if a[n] != b[n]:\n c += 1\n n -= 1\n return c == 1\n\n def getWordsInLongestSubsequence(self, n, words, groups):\n dp = [1] * (n + 1)\n prev = [-1] * (n + 1)\n maxdp = 1\n maxprev = 0\n for i in range(n):\n for j in range(i - 1, -1, -1):\n if groups[j] != groups[i]:\n k = self.check(words[i], words[j])\n if k:\n if 1 + dp[j] > dp[i]:\n dp[i] = 1 + dp[j]\n prev[i] = j\n if dp[i] > maxdp:\n maxdp = dp[i]\n maxprev = i\n res = []\n res.append(words[maxprev])\n while prev[maxprev] != -1:\n res.append(words[prev[maxprev]])\n maxprev = prev[maxprev]\n res.reverse()\n return res\n\n\n```\n```Java []\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Solution {\n public boolean check(String a, String b) {\n int n = a.length() - 1;\n int m = b.length() - 1;\n if (n != m)\n return false;\n int c = 0;\n while (n >= 0) {\n if (a.charAt(n) != b.charAt(n))\n c++;\n n--;\n }\n return c == 1;\n }\n\n public List<String> getWordsInLongestSubsequence(int n, List<String> words, List<Integer> groups) {\n List<Integer> dp = new ArrayList<>();\n List<Integer> prev = new ArrayList<>();\n for (int i = 0; i <= n; i++) {\n dp.add(1);\n prev.add(-1);\n }\n int maxdp = 1;\n int maxprev = 0;\n\n for (int i = 0; i < n; i++) {\n for (int j = i - 1; j >= 0; j--) {\n String a = words.get(i);\n String b = words.get(j);\n if (!groups.get(j).equals(groups.get(i))) {\n boolean k = check(a, b);\n if (k) {\n if (1 + dp.get(j) > dp.get(i)) {\n dp.set(i, 1 + dp.get(j));\n prev.set(i, j);\n if (dp.get(i) > maxdp) {\n maxdp = dp.get(i);\n maxprev = i;\n }\n }\n }\n }\n }\n }\n\n List<String> res = new ArrayList<>();\n res.add(words.get(maxprev));\n while (prev.get(maxprev) != -1) {\n res.add(words.get(prev.get(maxprev)));\n maxprev = prev.get(maxprev);\n }\n Collections.reverse(res);\n return res;\n }\n}\n```\n\n# ***If you like the solution Please Upvote and subscribe to my youtube channel***\n***It Motivates me to record more videos***\n\n*Thank you* \uD83D\uDE00\n
18
1
['Dynamic Programming', 'Greedy', 'Python', 'C++', 'Java']
1
longest-unequal-adjacent-groups-subsequence-ii
✅☑[C++/C/Java/Python/JavaScript] || DP || EXPLAINED🔥
ccjavapythonjavascript-dp-explained-by-m-rn9f
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n(Also explained in the code)\n\n1. The code defines a C++ class named Solution that contains a public funct
MarkSPhilip31
NORMAL
2023-10-14T16:21:13.802137+00:00
2023-10-14T16:21:13.802167+00:00
1,262
false
# *PLEASE UPVOTE IF IT HELPED*\n\n---\n\n\n# Approaches\n***(Also explained in the code)***\n\n1. The code defines a C++ class named `Solution` that contains a public function `getWordsInLongestSubsequence`.\n1. This function takes three arguments: `n`, an integer, `words`, a vector of strings, and `groups`, a vector of integers.\n1. It initializes two vectors, `dp` and `pv`, to keep track of the maximum subsequence length and the previous word index in the longest subsequence, respectively.\n1. The code iterates through the words and groups to find the longest subsequence.\n1. It uses a nested loop to compare each word with all previous words to check for specific conditions:\n - It skips comparing words with the same group (`groups[i] == groups[j]`).\n - It skips comparing words with different lengths (`words[i].size() != words[j].size()`).\n - It calculates the "difference" between words by counting the number of differing characters.\n - If the difference is not exactly 1, it skips the comparison (`diff != 1`).\n1. If the current word can be part of a longer subsequence (`dp[j] + 1 > dp[i]`), it updates the subsequence length and the previous word index.\n1. The code then identifies the index of the maximum subsequence length in the `dp` vector.\n1. It constructs the longest subsequence of words by backtracking through the `pv` vector.\n1. The resulting subsequence is added to the `ans` vector in reverse order to maintain the original order.\n1. Finally, the `ans` vector is reversed to provide the correct order and is returned as the output.\n\n\n# Complexity\n- **Time complexity:**\n $$O(n^2 * m)$$\n \n\n- **Space complexity:**\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<int> dp(groups.size(), 1); // Create a vector to store the maximum subsequence length for each word.\n vector<int> pv(groups.size(), -1); // Create a vector to store the previous word index in the longest subsequence.\n\n // Iterate through the words and groups to find the longest subsequence.\n for (int i = 1; i < groups.size(); i++) {\n for (int j = 0; j < i; j++) {\n if (groups[i] == groups[j]) continue; // If the groups are the same, skip.\n if (words[i].size() != words[j].size()) continue; // If word lengths are different, skip.\n\n int diff = 0;\n for (int k = 0; k < words[i].size(); k++) {\n diff += (words[i][k] != words[j][k]); // Calculate the difference in characters.\n }\n\n if (diff != 1) continue; // If there\'s more or less than one character difference, skip.\n\n if (dp[j] + 1 > dp[i]) {\n dp[i] = dp[j] + 1; // Update the subsequence length if it\'s longer.\n pv[i] = j; // Update the previous word index.\n }\n }\n }\n\n int wi = (max_element(dp.begin(), dp.end()) - dp.begin()); // Find the index of the maximum subsequence length.\n vector<string> ans;\n\n while (wi != -1) {\n ans.push_back(words[wi]); // Add words to the answer in reverse order to get the longest subsequence.\n wi = pv[wi]; // Move to the previous word in the subsequence.\n }\n\n reverse(ans.begin(), ans.end()); // Reverse the answer to get the correct order.\n return ans;\n }\n};\n\n\n\n```\n```C []\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nstruct Solution {\n int* dp;\n int* pv;\n};\n\nstruct Solution getWordsInLongestSubsequence(int n, char** words, int* groups) {\n struct Solution solution;\n solution.dp = (int*)malloc(n * sizeof(int));\n solution.pv = (int*)malloc(n * sizeof(int));\n \n for (int i = 0; i < n; i++) {\n solution.dp[i] = 1; // Initialize the maximum subsequence length for each word.\n solution.pv[i] = -1; // Initialize the previous word index in the longest subsequence.\n }\n\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < i; j++) {\n if (groups[i] == groups[j]) continue; // If the groups are the same, skip.\n if (strlen(words[i]) != strlen(words[j])) continue; // If word lengths are different, skip.\n\n int diff = 0;\n for (int k = 0; k < strlen(words[i]); k++) {\n if (words[i][k] != words[j][k]) diff++; // Calculate the difference in characters.\n }\n\n if (diff != 1) continue; // If there\'s more or less than one character difference, skip.\n\n if (solution.dp[j] + 1 > solution.dp[i]) {\n solution.dp[i] = solution.dp[j] + 1; // Update the subsequence length if it\'s longer.\n solution.pv[i] = j; // Update the previous word index.\n }\n }\n }\n\n int wi = 0;\n for (int i = 1; i < n; i++) {\n if (solution.dp[i] > solution.dp[wi]) {\n wi = i; // Find the index of the maximum subsequence length.\n }\n }\n\n char** ans = (char**)malloc(solution.dp[wi] * sizeof(char*));\n for (int i = 0; i < solution.dp[wi]; i++) {\n ans[i] = (char*)malloc(strlen(words[wi]) + 1);\n strcpy(ans[i], words[wi]); // Copy words to the answer.\n wi = solution.pv[wi]; // Move to the previous word in the subsequence.\n }\n\n // Reverse the answer to get the correct order.\n for (int i = 0; i < solution.dp[wi] / 2; i++) {\n char* temp = ans[i];\n ans[i] = ans[solution.dp[wi] - i - 1];\n ans[solution.dp[wi] - i - 1] = temp;\n }\n\n solution.dp = ans;\n return solution;\n}\n\n\n\n```\n```Java []\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Solution {\n public List<String> getWordsInLongestSubsequence(int n, List<String> words, List<Integer> groups) {\n List<Integer> dp = new ArrayList<>(groups.size());\n List<Integer> pv = new ArrayList<>(groups.size());\n \n for (int i = 0; i < groups.size(); i++) {\n dp.add(1); // Initialize the maximum subsequence length for each word.\n pv.add(-1); // Initialize the previous word index in the longest subsequence.\n }\n\n // Iterate through the words and groups to find the longest subsequence.\n for (int i = 1; i < groups.size(); i++) {\n for (int j = 0; j < i; j++) {\n if (groups.get(i).equals(groups.get(j))) continue; // If the groups are the same, skip.\n if (words.get(i).length() != words.get(j).length()) continue; // If word lengths are different, skip.\n\n int diff = 0;\n for (int k = 0; k < words.get(i).length(); k++) {\n diff += (words.get(i).charAt(k) != words.get(j).charAt(k)) ? 1 : 0; // Calculate the difference in characters.\n }\n\n if (diff != 1) continue; // If there\'s more or less than one character difference, skip.\n\n if (dp.get(j) + 1 > dp.get(i)) {\n dp.set(i, dp.get(j) + 1); // Update the subsequence length if it\'s longer.\n pv.set(i, j); // Update the previous word index.\n }\n }\n }\n\n int wi = dp.indexOf(dp.stream().max(Integer::compareTo).get()); // Find the index of the maximum subsequence length.\n List<String> ans = new ArrayList<>();\n\n while (wi != -1) {\n ans.add(words.get(wi)); // Add words to the answer in reverse order to get the longest subsequence.\n wi = pv.get(wi); // Move to the previous word in the subsequence.\n }\n\n Collections.reverse(ans); // Reverse the answer to get the correct order.\n return ans;\n }\n}\n\n\n```\n```python3 []\n\nclass Solution:\n def getWordsInLongestSubsequence(self, n, words, groups):\n dp = [1] * len(groups)\n pv = [-1] * len(groups)\n\n for i in range(1, len(groups)):\n for j in range(i):\n if groups[i] == groups[j]:\n continue\n if len(words[i]) != len(words[j]):\n continue\n\n diff = sum(1 for k in range(len(words[i])) if words[i][k] != words[j][k])\n\n if diff != 1:\n continue\n\n if dp[j] + 1 > dp[i]:\n dp[i] = dp[j] + 1\n pv[i] = j\n\n wi = dp.index(max(dp))\n ans = []\n\n while wi != -1:\n ans.append(words[wi])\n wi = pv[wi]\n\n ans.reverse()\n return ans\n\n\n```\n```javascript []\n\nclass Solution {\n getWordsInLongestSubsequence(n, words, groups) {\n const dp = new Array(groups.length).fill(1);\n const pv = new Array(groups.length).fill(-1);\n\n for (let i = 1; i < groups.length; i++) {\n for (let j = 0; j < i; j++) {\n if (groups[i] === groups[j]) continue;\n if (words[i].length !== words[j].length) continue;\n\n let diff = 0;\n for (let k = 0; k < words[i].length; k++) {\n if (words[i][k] !== words[j][k]) diff++;\n }\n\n if (diff !== 1) continue;\n\n if (dp[j] + 1 > dp[i]) {\n dp[i] = dp[j] + 1;\n pv[i] = j;\n }\n }\n }\n\n let wi = dp.indexOf(Math.max(...dp));\n const ans = [];\n\n while (wi !== -1) {\n ans.push(words[wi]);\n wi = pv[wi];\n }\n\n ans.reverse();\n return ans;\n }\n}\n\n\n```\n---\n\n\n\n# *PLEASE UPVOTE IF IT HELPED*\n\n---\n---\n\n\n---\n\n
14
0
['String', 'Dynamic Programming', 'C', 'C++', 'Java', 'Python3', 'JavaScript']
4
longest-unequal-adjacent-groups-subsequence-ii
Both recursive & iterative approach || Very simple and easy to understand solution
both-recursive-iterative-approach-very-s-bw8v
\n# Approach 1 : (Recursive)\n- Need to check all possible cases\n- While doing so, do memorise the next possible best index from each index. Best idex is the o
kreakEmp
NORMAL
2023-10-14T17:46:45.723023+00:00
2023-10-14T19:46:13.208947+00:00
1,657
false
\n# Approach 1 : (Recursive)\n- Need to check all possible cases\n- While doing so, do memorise the next possible best index from each index. Best idex is the one - when moved to that position we end up in moving to longest length\n- During traversing to a index check if already visited. If yes then add the next indext to temp answer and then directly move to that index without evaluating further.\n\n### Code\n```\nclass Solution {\npublic:\n vector<int> dp, ans;\n \n //check basically verify if we can move to lastIndex to ith index or not\n bool check(vector<string>& words, vector<int>& groups, int i, int lastInd){\n if(groups[i] == groups[lastInd] || words[i].size() != words[lastInd].size()) return false;\n int diff = 0;\n for(int j = 0; j < words[i].size(); ++j ){\n if(words[i][j] != words[lastInd][j]) diff++;\n }\n return diff == 1;\n }\n \n int solve(int n, vector<string>& words, vector<int>& groups, int i, vector<int>& temp){\n if(i >= n) return 0;\n int len = 0, nextInd = -1;\n \n if(i != -1 && dp[i] != -1) { //Check in memory & back track to collect the result \n temp.push_back(dp[i]);\n len = 1 + solve(n, words, groups, dp[i], temp);\n temp.pop_back();\n return len;\n }\n \n for( int t = i+1; t < n; ++t){ //check with each of the next possible item and move to it if possible\n if(i < 0 || check(words, groups, t, i)){ // i < 0 condition is used to handel base condition - when we are picking the first element\n temp.push_back(t);\n int l = 1 + solve(n, words, groups, t, temp);\n temp.pop_back();\n if(l > len){ len = l; nextInd = t; }\n }\n }\n \n if(temp.size() > ans.size()) { //collect max len temp in ans\n ans.resize(0);\n copy(temp.begin(), temp.end(), back_inserter(ans)); \n }\n \n if(i != -1) dp[i] = nextInd;\n return len;\n }\n \n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n dp.resize(1001, -1);\n vector<int> temp;\n vector<string> res;\n solve(n, words, groups, -1, temp);\n for(auto e: ans) res.push_back(words[e]);\n return res;\n }\n};\n```\n\n# Approach 2 : (Iterative)\n\n\n### Code\n```\nclass Solution {\npublic:\n bool check(vector<string>& words, vector<int>& groups, int i, int lastInd){\n if(groups[i] == groups[lastInd] || words[i].size() != words[lastInd].size()) return false;\n int diff = 0;\n for(int j = 0; j < words[i].size(); ++j ){\n if(words[i][j] != words[lastInd][j]) diff++;\n }\n return diff == 1;\n }\n \n void solve(int n, vector<string>& words, vector<int>& groups, vector<string>& res){\n vector<int> len(1001, 1), next(1001, -1); //len will store the max len from that point & // next will store the index which is the best to traverse to get max len\n int startNodeWithMaxLen = -1, maxLen = 0;\n for(int i = n-1; i >= 0; --i){ //iterate from the backward\n for( int t = i+1; t < n; ++t){ //find next best index from i to move\n if(len[i] < len[t]+1 && check(words, groups, i, t)){\n len[i] = len[t]+1; next[i] = t;\n }\n }\n if(maxLen < len[i]){ maxLen = len[i]; startNodeWithMaxLen = i; }\n }\n int p = startNodeWithMaxLen;\n while(p != -1){ //iterate from start point and collect the words\n res.push_back(words[p]);\n p = next[p];\n }\n }\n \n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<string> res;\n solve(n, words, groups, res);\n return res;\n }\n};\n```\n\n\n----\n\n<b>Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted\n\n---
10
3
['Dynamic Programming', 'Recursion', 'C++']
4
longest-unequal-adjacent-groups-subsequence-ii
Video Explanation (Brute force to DP)
video-explanation-brute-force-to-dp-by-c-w3nt
Explanation\n\nClick here for the video\n\n# Code\n\nclass Solution {\n\n vector<vector<int>> possible_nxt;\n vector<int> dp;\n vector<int> best_nxt;\n
codingmohan
NORMAL
2023-10-14T17:17:21.143386+00:00
2023-10-14T17:17:21.143408+00:00
239
false
# Explanation\n\n[Click here for the video](https://youtu.be/xhIg9JNUgjA)\n\n# Code\n```\nclass Solution {\n\n vector<vector<int>> possible_nxt;\n vector<int> dp;\n vector<int> best_nxt;\n int n; \n\n int LongestSubsequence (int ind) {\n if (ind == n) return 0;\n \n int& ans = dp[ind];\n if (ans != -1) return ans;\n \n int& best_ind = best_nxt[ind];\n \n ans = 1;\n best_ind = n;\n \n for (auto nxt: possible_nxt[ind]) {\n int val = LongestSubsequence(nxt) + 1;\n if (val > ans) {\n ans = val;\n best_ind = nxt;\n }\n }\n return ans;\n }\n \npublic:\n vector<string> getWordsInLongestSubsequence(int _n, vector<string>& words, vector<int>& groups) {\n n = _n;\n dp.clear(), best_nxt.clear(), possible_nxt.clear();\n dp.resize(n, -1), best_nxt.resize(n, n), possible_nxt.resize(n);\n \n for (int j = 0; j < n; j ++) {\n for (int nxt = j+1; nxt < n; nxt ++) {\n if (groups[j] == groups[nxt]) continue;\n if (words[j].length() != words[nxt].length()) continue;\n \n int dist = 0;\n for (int i = 0; i < words[j].length(); i ++) \n if (words[j][i] != words[nxt][i]) dist ++;\n if (dist != 1) continue;\n \n possible_nxt[j].push_back(nxt);\n }\n }\n \n int longest = 0;\n int ind = -1;\n \n for (int j = 0; j < n; j ++) {\n int len = LongestSubsequence(j);\n if (len > longest) {\n longest = len;\n ind = j;\n }\n }\n \n vector<string> result;\n while (ind != n) {\n result.push_back(words[ind]);\n ind = best_nxt[ind];\n }\n return result;\n }\n};\n```
10
0
['C++']
1
longest-unequal-adjacent-groups-subsequence-ii
[Python 3] Top-Down DP
python-3-top-down-dp-by-abhishek_nub-vius
\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n \n @lru_cache(None)\n
abhishek_nub
NORMAL
2023-10-14T16:08:49.686931+00:00
2023-10-14T16:09:05.670889+00:00
575
false
```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n \n @lru_cache(None)\n def dp(i):\n pik = []\n \n for j in range(i, n):\n if groups[i] != groups[j] and len(words[i]) == len(words[j]) and sum(a != b for a, b in zip(words[i], words[j])) == 1:\n pik = max(pik, dp(j), key = len)\n \n return [words[i]] + pik\n \n return max([dp(i) for i in range(n)], key = len)\n```
9
0
['Dynamic Programming', 'Python', 'Python3']
4
longest-unequal-adjacent-groups-subsequence-ii
😎C++ ||✅ Easy to Understand ||✅ Dynamic Programming ||✅ LIS Variants ||✅ Parent marking
c-easy-to-understand-dynamic-programming-irfp
----------------------------------------------------------------------\n# Please Do upvote if you like this solution\n------------------------------------------
mannchandarana
NORMAL
2023-10-14T18:13:10.767232+00:00
2023-10-14T18:13:10.767266+00:00
406
false
----------------------------------------------------------------------\n# Please Do upvote if you like this solution\n----------------------------------------------------------------------\n# Let\'s Connect on :- [LinkedIn](https://www.linkedin.com/in/mann-chandarana-115255230/)\n----------------------------------------------------------------------\n# Approach\nLongest increasing subsequence variant with parent marking.\n\n----------------------------------------------------------------------\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(N)\n\n----------------------------------------------------------------------\n\n# Code\n```\n#define ll long long\n#define all(v) v.begin(), v.end()\n\ntypedef vector<int> vi;\ntypedef vector<string> vs;\n\nbool validate(string a, string b)\n{\n int n = a.length(), m = b.length();\n\n if (n != m)\n return false;\n\n int count = 0;\n\n for (int i = 0; i < n; i++)\n {\n if (a[i] != b[i])\n count++;\n }\n return count == 1;\n}\n\nvector<string> getWordsInLongestSubsequence(int n,vector<string> &words, vector<int> &groups)\n{\n vector<int> count(n, 1), parent(n);\n\n for (int i = 0; i < n; i++)\n parent[i] = i;\n\n for (int i = 1; i < n; i++)\n {\n for (int j = 0; j < i; j++)\n {\n if (groups[i] != groups[j])\n {\n if (validate(words[j], words[i]))\n {\n if (count[j] + 1 > count[i])\n count[i] = count[j]+1, parent[i] = j;\n }\n }\n }\n }\n\n int maxi = INT_MIN, index;\n\n for (int i = 0; i < n; i++)\n {\n if (count[i] > maxi)\n maxi = count[i], index = i;\n }\n\n vector<string> answer;\n\n while (parent[index] != index)\n answer.push_back(words[index]), index = parent[index];\n\n answer.push_back(words[index]);\n reverse(all(answer));\n\n return answer;\n}\n```\n----------------------------------------------------------------------\n![image.png](https://assets.leetcode.com/users/images/2df1134d-2775-41ea-946b-ef2d06f60a2c_1697307156.8687575.png)\n
6
1
['Dynamic Programming', 'Recursion', 'Memoization', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
Directed Graph + DFS
directed-graph-dfs-by-aman_8055-2g6v
Intuition\nConstruct a directed graph connecting indices that meet the described criteria.\nThis graph may not be fully connected but will always be acyclic.Nex
aman_8055
NORMAL
2023-10-14T16:01:40.496050+00:00
2023-10-14T16:02:51.829438+00:00
291
false
# Intuition\nConstruct a directed graph connecting indices that meet the described criteria.\nThis graph may not be fully connected but will always be acyclic.Next, from the root of each connected component, we must find a path to the deepest node.\nMaintain a global list to record the longest solution for each component.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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```\n\n// Construct a directed graph connecting indices that meet the described criteria.\n// This graph may not be fully connected but will always be acyclic.\n// Next, from the root of each connected component, we must find a path to the deepest node.\n// Maintain a global list to record the longest solution for each component.\n\n\nclass Solution {\npublic:\n vector<string> res;\n \n void dfs(int i, int level, vector<vector<int>> &adj, vector<int> &vis, vector<string> &curr, vector<string>& words){\n \n if(vis[i] >= level){\n return;\n }\n \n vis[i] = level;\n \n curr.push_back(words[i]);\n\n \n \n if(adj[i].size() == 0 && res.size() < curr.size()){\n res = curr;\n }\n \n for(int k : adj[i]){\n dfs(k, level + 1, adj, vis, curr, words);\n }\n \n curr.pop_back(); \n }\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n \n vector<vector<int>> adj(n);\n \n for(int i = 0 ; i < n ; i++){\n for(int j = i + 1 ; j < n ; j++){\n if(words[i].size() == words[j].size() && groups[i] != groups[j]){\n int c = 0;\n for(int k = 0 ; k < words[j].size() ; k++){\n if(words[i][k] != words[j][k])\n c++;\n }\n if(c == 1)\n adj[i].push_back(j);\n }\n }\n }\n \n vector<int> vis(n, -1);\n \n for(int i = 0 ; i < n ; i++){\n if(vis[i] == -1){\n vector<string> curr;\n dfs(i, 0, adj, vis, curr, words);\n }\n }\n \n return res;\n }\n};\n// Construct a directed graph connecting indices that meet the described criteria.\n// This graph may not be fully connected but will always be acyclic.\n// Next, from the root of each connected component, we must find a path to the deepest node.\n// Maintain a global list to record the longest solution for each component.\n\n\nclass Solution {\npublic:\n vector<string> res;\n \n void dfs(int i, int level, vector<vector<int>> &adj, vector<int> &vis, vector<string> &curr, vector<string>& words){\n \n if(vis[i] >= level){\n return;\n }\n \n vis[i] = level;\n \n curr.push_back(words[i]);\n\n \n \n if(adj[i].size() == 0 && res.size() < curr.size()){\n res = curr;\n }\n \n for(int k : adj[i]){\n dfs(k, level + 1, adj, vis, curr, words);\n }\n \n curr.pop_back(); \n }\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n \n vector<vector<int>> adj(n);\n \n for(int i = 0 ; i < n ; i++){\n for(int j = i + 1 ; j < n ; j++){\n if(words[i].size() == words[j].size() && groups[i] != groups[j]){\n int c = 0;\n for(int k = 0 ; k < words[j].size() ; k++){\n if(words[i][k] != words[j][k])\n c++;\n }\n if(c == 1)\n adj[i].push_back(j);\n }\n }\n }\n \n vector<int> vis(n, -1);\n \n for(int i = 0 ; i < n ; i++){\n if(vis[i] == -1){\n vector<string> curr;\n dfs(i, 0, adj, vis, curr, words);\n }\n }\n \n return res;\n }\n};\n```
5
0
['C++']
2
longest-unequal-adjacent-groups-subsequence-ii
🎨 The ART of Dynamic Programming
the-art-of-dynamic-programming-by-clayto-povv
\uD83C\uDFA8 The ART of Dynamic Programming: similar to Kadane\'s algorithm, let dp[i] denote the "best path ending here" at each ith index, initialized with ea
claytonjwong
NORMAL
2023-10-18T21:56:53.375145+00:00
2023-11-10T01:25:16.992625+00:00
114
false
[\uD83C\uDFA8 The ART of Dynamic Programming:](https://leetcode.com/discuss/general-discussion/712010/The-ART-of-Dynamic-Programming-An-Intuitive-Approach%3A-from-Apprentice-to-Master) similar to Kadane\'s algorithm, let `dp[i]` denote the *"best path ending here"* at each `i`<sup>th</sup> index, initialized with each `i`<sup>th</sup> `word` of the input `words`. Then formulate each optimal **current** `j`<sup>th</sup> *"best path ending here"* from each optimal **previous** `i`<sup>th</sup> *"best path ending here"*, ie. we append `words[j]` onto the previous `best` ending at `words[i]` where `i < j`; thus formulating the optimal future `j` from the optimal past `i`.\n\n* **\uD83D\uDED1 Base Case:** `dp[i] = [words[i]]`\n\t* *"best path ending here"* is intially each `word` itself as a path of length `1`\n* **\uD83E\uDD14 Recurrence Relation:** `dp[j] = dp[i] + [words[j]]`\n\t* append `words[j]` onto the previous *"best path ending"* at `i`\n\n**Example:** this is what I "see" \uD83D\uDC40 via the quadratic runtime of this algorithm\'s for-loops\n```\n j\n ij\n iij\n iiij\nprevious i \uD83D\uDC49 iiiij \uD83D\uDC48 current j\n(past) 012345 (future)\n ...\n ... etc\n ...\n```\n\n* \u2B50\uFE0F **Note:** this problem is fundamentally a variant of [300. Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)\n\n---\n\n*Kotlin*\n```\nclass Solution {\n fun getWordsInLongestSubsequence(N: Int, words: Array<String>, groups: IntArray): List<String> {\n var dp = words.map{ mutableListOf<String>(it) }.toTypedArray() // \uD83D\uDED1 base case: "best path ending here" is initially each word itself as a path of length 1\n var ok = { i: Int, j: Int -> words[i].length == words[j].length && groups[i] != groups[j] && 1 == (words[i] zip words[j]).filter{ (a, b) -> a != b }.size && dp[j].size < dp[i].size + 1 }\n for (j in 0 until N)\n for (i in 0 until j)\n if (ok(i, j)) // \uD83D\uDEAB constraints per the problem statement\n { dp[j] = dp[i].toMutableList(); dp[j].add(words[j]) } // \uD83E\uDD14 append words[j] onto previous best path ending at i\n var hi = dp.map{ it.size }.max()!! // \uD83E\uDD47 maximum length candidate(s)\n var best = dp.filter{ hi == it.size } // \uD83C\uDFAF optimal solution(s)\n return best[0] // \uD83C\uDFB2 arbitrary choice\n }\n}\n```\n\n*Javascript*\n```\nlet getWordsInLongestSubsequence = (N, words, groups) => {\n let dp = words.map(word => [word]); // \uD83D\uDED1 base case: "best path ending here" is initially each word itself as a path of length 1\n let ok = (i, j) => words[i].length == words[j].length && groups[i] != groups[j] && 1 == _.zip(words[i].split(\'\'), words[j].split(\'\')).filter(([a, b]) => a != b).length && dp[j].length < dp[i].length + 1;\n for (let j = 0; j < N; ++j)\n for (let i = 0; i < j; ++i)\n if (ok(i, j)) // \uD83D\uDEAB constraints per the problem statement\n dp[j] = [...dp[i], words[j]]; // \uD83E\uDD14 append words[j] onto previous best path ending at i\n let hi = Math.max(...dp.map(cand => cand.length)); // \uD83E\uDD47 maximum length candidate(s)\n let best = [...dp.filter(cand => hi == cand.length)]; // \uD83C\uDFAF optimal solution(s)\n return best[0]; // \uD83C\uDFB2 arbitrary choice\n};\n```\n\n*Python3*\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, N: int, words: List[str], groups: List[int]) -> List[str]:\n dp = [[word] for word in words] # \uD83D\uDED1 base case: "best path ending here" is initially each word itself as a path of length 1\n ok = lambda i, j: len(words[i]) == len(words[j]) and groups[i] != groups[j] and 1 == len([a for a, b in zip(words[i], words[j]) if a != b]) and len(dp[j]) < len(dp[i]) + 1\n for j in range(N):\n for i in range(j):\n if ok(i, j): # \uD83D\uDEAB constraints per the problem statement\n dp[j] = dp[i] + [words[j]] # \uD83E\uDD14 append words[j] onto previous best path ending at i\n hi = max(len(cand) for cand in dp) # \uD83E\uDD47 maximum length candidate(s)\n best = [cand for cand in dp if hi == len(cand)] # \uD83C\uDFAF optimal solution(s)\n return best[0] # \uD83C\uDFB2 arbitrary choice\n```\n\n*Rust*\n```\ntype VI = Vec<i32>;\ntype VS = Vec<String>;\ntype VVS = Vec<VS>;\nimpl Solution {\n pub fn get_words_in_longest_subsequence(N: i32, words: VS, groups: VI) -> VS {\n let mut dp = words.iter().map(|word| Vec::from([word.clone()])).collect::<VVS>(); // \uD83D\uDED1 base case: "best path ending here" is initially each word itself as a path of length 1\n let ok = (|i: usize, j: usize| words[i].len() == words[j].len() && groups[i] != groups[j] && 1 == words[i].chars().zip(words[j].chars()).filter(|(a, b)| a != b).collect::<Vec<(char,char)>>().len());\n for j in 0..N as usize {\n for i in 0..j {\n if ok(i, j) && dp[j].len() < dp[i].len() + 1 { // \uD83D\uDEAB constraints per the problem statement\n dp[j] = dp[i].clone(); dp[j].push(words[j].clone()); // \uD83E\uDD14 append words[j] onto previous best path ending at i\n }\n }\n }\n let hi = dp.iter().map(|word| word.len()).max().unwrap(); // \uD83E\uDD47 maximum length candidate(s)\n let best = dp.into_iter().filter(|word| hi == word.len()).collect::<VVS>(); // \uD83C\uDFAF optimal solution(s)\n (*best[0]).to_vec() // \uD83C\uDFB2 arbitrary choice\n }\n}\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using VI = vector<int>;\n using VS = vector<string>;\n using VVS = vector<VS>;\n VS getWordsInLongestSubsequence(int N, VS& words, VI& groups, VVS dp = {}, VVS best = {}) {\n auto ok = [&](auto i, auto j) { return words[i].size() == words[j].size() && groups[i] != groups[j] && 1 == count_if(words[i].begin(), words[i].end(), [i, j, k = -1, &words](auto _) mutable { ++k; return words[i][k] != words[j][k]; }) && dp[j].size() < dp[i].size() + 1; };\n transform(words.begin(), words.end(), back_inserter(dp), [](auto& word) { return VS{word}; }); // \uD83D\uDED1 base case: "best path ending here" is initially each word itself as a path of length 1\n for (auto j{ 0 }; j < N; ++j)\n for (auto i{ 0 }; i < j; ++i)\n if (ok(i, j)) // \uD83D\uDEAB constraints per the problem statement\n dp[j] = dp[i], dp[j].push_back(words[j]); // \uD83E\uDD14 append words[j] onto previous best path ending at i\n auto hi = *max_element(dp.begin(), dp.end(), [](auto& a, auto& b) { return a.size() < b.size(); }); // \uD83E\uDD47 maximum length candidate(s)\n copy_if(dp.begin(), dp.end(), back_inserter(best), [&](auto& cand) { return hi.size() == cand.size(); }); // \uD83C\uDFAF optimal solution(s)\n return best[0]; // \uD83C\uDFB2 arbitrary choice\n }\n};\n```
4
0
[]
0
longest-unequal-adjacent-groups-subsequence-ii
C++ || ✅🧭Beats 90 % || LIS variation + Parent marking
c-beats-90-lis-variation-parent-marking-9ihdj
Intuition\nWording of problem was that in subsequence, for the consecutive element, groups[j] != groups[j+1] and match the size of words + hamming distance == 1
Monstid
NORMAL
2023-10-14T16:06:32.259823+00:00
2023-10-14T16:17:57.740773+00:00
692
false
# Intuition\nWording of problem was that in subsequence, for the consecutive element, groups[j] != groups[j+1] and match the size of words + hamming distance == 1\n\nDo the normal LIS + parent array to backtrack the resulting array of strings\n\nIt would be great to understand with a visual cue, take help of example\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 {\npublic:\n\n bool isGood(string &s1, string &s2)\n {\n int diff = 0;\n for(int i=0; s1[i]; i++)\n {\n if(s1[i] != s2[i])\n {\n if(diff)\n return false;\n diff++;\n } \n }\n return true;\n }\n\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<string> res;\n vector<int> lis(n, 1), parent(n);\n int mx_index = 0;\n \n for(int i=0; i<n; i++)\n {\n parent[i] = i;\n int sz = words[i].size();\n for(int j=i-1; j>=0; j--)\n {\n if(groups[j] != groups[i] && sz == (int)words[j].size() && isGood(words[i], words[j]) )\n {\n if(lis[j] + 1 > lis[i])\n {\n lis[i] = lis[j] + 1;\n parent[i] = j;\n }\n }\n }\n if(lis[i] > lis[mx_index])\n mx_index = i;\n \n //cout << lis[i] <<" ";\n }\n //cout << endl;\n \n int cur = mx_index;\n while(parent[cur] != cur)\n {\n res.push_back(words[cur]);\n cur = parent[cur];\n }\n res.push_back(words[cur]);\n\n reverse(res.begin(), res.end());\n return res;\n }\n};\n```
3
0
['Dynamic Programming', 'Backtracking', 'C++']
3
longest-unequal-adjacent-groups-subsequence-ii
LIS Solution
lis-solution-by-tlecodes-dxga
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
tlecodes
NORMAL
2024-10-10T15:31:15.609654+00:00
2024-10-10T15:31:15.609684+00:00
22
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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```cpp []\nclass Solution {\nprivate:\n bool validHammingDistance(string &word1, string &word2) {\n int size = word1.size(), cnt = 0;\n for (int i = 0; i < size; i++) {\n if (word1[i] != word2[i]) {\n cnt++;\n if (cnt > 1) {\n return false;\n }\n }\n }\n return true;\n }\npublic:\n vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {\n int n = words.size(), maxLen = 0, lastIndex = -1;\n vector<int> dp(n, 1), prevIndex(n, -1);\n vector<string> ans;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < i; j++) {\n if (groups[j] != groups[i] && words[j].size() == words[i].size() && validHammingDistance(words[i], words[j]) && dp[j] + 1 > dp[i]) {\n dp[i] = 1 + dp[j];\n prevIndex[i] = j;\n }\n }\n if (dp[i] > maxLen) {\n maxLen = dp[i];\n lastIndex = i;\n }\n }\n while (lastIndex != -1) {\n ans.push_back(words[lastIndex]);\n lastIndex = prevIndex[lastIndex];\n }\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n```
2
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
Java DP solution beats 95% with detailed explanation
java-dp-solution-beats-95-with-detailed-wu5qo
\n# Approach\n Describe your approach to solving the problem. \nWe use dynamic programming to solve this problem. We have a check array and each index represent
kevinyyh
NORMAL
2023-10-24T08:25:57.637037+00:00
2023-10-24T08:25:57.637054+00:00
80
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe use dynamic programming to solve this problem. We have a ```check``` array and each index represents the longest subsequence up til this index and this index is included in this longest subsequence. For every element in ```words```, we check all the words before it and update ```check``` accordingly. We use ```index``` to keep track of where the longest subsequence ends and ```max``` to keep track of the length of the longest subsequence. The ```before``` array is used to know for the current index, what is the index of the previous element in its subsequence so we can reconstruct the array easily.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2 * k) where k is the max length of a word. Since k is less than 10, we can say time complexity is O(N^2).\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\nclass Solution {\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n int[] check = new int[groups.length];\n int[] before = new int[groups.length];\n Arrays.fill(check, 1);\n Arrays.fill(before, -1);\n int index = 0;\n int max = 1;\n for (int i = 1; i < words.length; i++) {\n for (int j = i-1; j >= 0; j--) {\n if (groups[i] != groups[j] && ham(words[i], words[j])) {\n if (check[j] + 1 > check[i]) {\n check[i] = check[j] + 1;\n before[i] = j;\n if (check[i] > max) {\n max = check[i];\n index = i;\n }\n }\n }\n }\n }\n List<String> ans = new ArrayList<>();\n while (index >= 0) {\n ans.add(words[index]);\n index = before[index];\n }\n Collections.reverse(ans);\n return ans;\n }\n\n private boolean ham(String s1, String s2) {\n if (s1.length() != s2.length()) {\n return false;\n }\n int count = 0;\n for (int i = 0; i < s1.length(); i++) {\n if (s1.charAt(i) != s2.charAt(i)) {\n count++;\n }\n if (count > 1) {\n return false;\n }\n }\n return count == 1;\n }\n}\n```
2
0
['Java']
0
longest-unequal-adjacent-groups-subsequence-ii
[C++] Dynamic Programmin with the longest subsequence indices
c-dynamic-programmin-with-the-longest-su-tbjv
Intuition\n Describe your first thoughts on how to solve this problem. \nFor each words[i], we can append or not append it to a subsequence ended with words[j],
pepe-the-frog
NORMAL
2023-10-18T12:54:28.086765+00:00
2023-10-18T12:54:28.086790+00:00
491
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each `words[i]`, we can append or not append it to a subsequence ended with `words[j], where j = [0, i)`(if `words[i]` and `words[j]` meet the conditions)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- `dp[i]` means the longest subsequence indices ended with `words[i]`\n- initialize `dp[i]` with `words[i]`\n- try to append `words[i]` to the subsequence ended with `words[j]`\n- convert word indices to an array of words\n\n# Complexity\n- Time complexity: $$O(n^2)$$\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 // time/space: O(n^2)/O(n^2)\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n // `dp[i]` means the longest subsequence indices ended with `words[i]`\n vector<vector<int>> dp(n);\n // initialize `dp[i]` with `words[i]`\n for (int i = 0; i < n; i++) dp[i].push_back(i);\n\n // try to append `words[i]` to the subsequence ended with `words[j]`\n int longest_length = 1;\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < i; j++) {\n // skip `words[j]` if the conditions do not meet\n if (groups[i] == groups[j]) continue;\n if (words[i].size() != words[j].size()) continue;\n if (getHammingDistance(words[i], words[j]) != 1) continue;\n\n // `dp[j].size()` means the length of the subsequence ended with words[j]\n // `dp[j].size() + 1` means appending `words[i]`\n // `dp[i].size()` means the length of the subsequence ended with words[i]\n if ((dp[j].size() + 1) > dp[i].size()) {\n // update `dp[i]` if we find a longer subsequence\n dp[i] = dp[j];\n dp[i].push_back(i);\n longest_length = max(longest_length, int(dp[i].size()));\n }\n }\n }\n\n // convert word indices to an array of words\n vector<string> result;\n for (int i = 0; i < n; i++) {\n if (dp[i].size() == longest_length) {\n for (const int& x : dp[i]) result.push_back(words[x]);\n break;\n }\n }\n return result;\n }\nprivate:\n int getHammingDistance(const string& s, const string& t) {\n int dist = 0;\n int k = s.size();\n for (int i = 0; i < k; i++) {\n if (s[i] != t[i]) dist++;\n }\n return dist;\n }\n};\n```
2
0
['Array', 'String', 'Dynamic Programming', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
✅🔥 Java Easy Solution ✅🔥
java-easy-solution-by-vishesht27-9t4h
Intuition\nThe problem requires us to find the longest subsequence of words such that the conditions regarding group inequality and hamming distance are satisfi
vishesht27
NORMAL
2023-10-16T05:25:54.758899+00:00
2023-10-16T05:25:54.758927+00:00
87
false
# Intuition\nThe problem requires us to find the longest subsequence of words such that the conditions regarding group inequality and hamming distance are satisfied. One way to approach this is to make a decision at every index: either to include the current word in our subsequence or skip it. This gives us a hint that the problem can be approached using recursion, with a choice at each step. The problem also involves overlapping subproblems, which suggests the use of memoization.\n\n# Approach\n1. **Memoization:** The map is used to store results of overlapping subproblems. The key is a combination of the current index ind and the previous index prev which is used to represent the state. If the solution for a particular state is already computed, it is fetched from the map.\n\n2. **Recursive Function:** The function function is the main recursive function that makes the decision to either take the current word or skip it.\n\n* If the current word satisfies the conditions (i.e., group inequality, same length, and hamming distance of 1 with the previous word), then a recursive call is made by considering the current word as the prev word. The result of this call is the list obtained by including the current word.\n* Another recursive call is made to see the result of skipping the current word.\n3. **Decision Making:** After getting the result from both recursive calls (taking or skipping the current word), we decide which list to consider based on their sizes. The longer list is stored in the map for the current state.\n\n4. **Hamming Distance Calculation:** The function hammingDist is a simple utility function that calculates the hamming distance between two strings.\n\n# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution {\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n HashMap<String,List<String>> map = new HashMap<>();\n List<String> ans = function(0,-1,words,groups,map);\n return ans;\n }\n\n public List<String> function(int ind,int prev,String[] words,int[] groups,HashMap<String,List<String>> map){\n\n if(ind>=words.length) return new ArrayList<>();\n\n String key = ind + " " + prev;\n\n if(map.containsKey(key)) return map.get(key);\n\n List<String> takeCurrent = new ArrayList<>();\n if(prev==-1 || ((groups[prev]!=groups[ind]) && (words[prev].length()==words[ind].length()) && (hammingDist(words[prev],words[ind])==1) )){\n takeCurrent = new ArrayList<>(function(ind+1,ind,words,groups,map));\n takeCurrent.add(0,words[ind]);\n }\n\n List<String> skipCurrent = function(ind+1,prev,words,groups,map);\n \n if(skipCurrent.size()>takeCurrent.size()){\n map.put(key,skipCurrent);\n }else{\n map.put(key,takeCurrent);\n }\n\n return map.get(key);\n }\n \n static int hammingDist(String str1, String str2) \n { \n int i = 0, count = 0; \n while (i < str1.length()) { \n if (str1.charAt(i) != str2.charAt(i)) \n count++; \n i++; \n } \n return count; \n } \n \n \n}\n```\n\n![dalle.png](https://assets.leetcode.com/users/images/d5449cf6-2b09-49e2-b5f9-6cdb911ff6ba_1697433941.8374805.png)\n\n\n
2
0
['Array', 'Hash Table', 'Math', 'String', 'Recursion', 'Memoization', 'Hash Function', 'Java']
1
longest-unequal-adjacent-groups-subsequence-ii
Beats 100%(63ms) || C++ || Dynamic Programming
beats-10063ms-c-dynamic-programming-by-h-di73
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. \n\n\n\n\n\n\n\n\n \n\n# Code\n\nclass Solution {\npublic:\n bool ham(string &
Harshal_Holkar
NORMAL
2023-10-15T14:10:01.780886+00:00
2023-10-15T14:10:01.780918+00:00
75
false
<!-- # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n<!-- # Complexity -->\n<!-- - Time complexity: -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity:\nAdd your space complexity here, e.g. $$O(n)$$ --> \n\n# Code\n```\nclass Solution {\npublic:\n bool ham(string &s, string &t){\n int n = s.length(), m = t.length();\n if(n != m)\n return false;\n bool diff = 0;\n\n for(int i = 0; i < n; i++){\n if(s[i] != t[i]){\n if(diff)\n return false;\n diff = 1;\n }\n }\n \n return true;\n }\n\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& group) {\n int idx = 0;\n vector<string> ans;\n vector<int> dp(n, 1);\n \n for(int i = 0; i < n; i++){ \n int prev = 0; \n for(int j = 0; j < i; j++){\n if(group[i] != group[j] && ham(words[i], words[j]))\n prev = max(dp[j], prev);\n }\n dp[i] += prev;\n if(dp[idx] <= dp[i])\n idx = i;\n }\n\n ans.push_back(words[idx]);\n\n for(int i = idx; i >= 0; i--){\n if(dp[idx]-1 == dp[i] && ham(words[i], words[idx]) && group[idx] != group[i]){\n ans.push_back(words[i]);\n idx = i;\n }\n }\n\n reverse(ans.begin(), ans.end());\n\n return ans;\n }\n};\n```
2
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
LIS approach | O(N^2) solution | Java
lis-approach-on2-solution-java-by-bishal-7pv0
Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem is a slight variation of the famous LIS (Longest Increasing Subsequence) p
bishalkundu17
NORMAL
2023-10-14T16:52:02.287684+00:00
2023-10-14T16:59:12.142763+00:00
156
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is a slight variation of the famous LIS (Longest Increasing Subsequence) problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn LIS we used to store the length of the LIS starting from index 0 ... i in dp[i]. Here we are gonna use the same approach but rather than storing the length we are gonna store the possible ans (List of String) in each dp[i].\n\n# Complexity\n- Time complexity: O(N^2)\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 {\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n List<List<String>> dp = new ArrayList<>();\n int maxLen = 1;\n for(int i = 0; i < n; ++i) {\n List<String> curAns = new ArrayList<>();\n curAns.add(words[i]);\n dp.add(curAns);\n for(int j = 0; j < i; ++j) {\n if(groups[i] != groups[j] && check(words[i], words[j])) {\n if(1 + dp.get(j).size() > dp.get(i).size()) {\n dp.set(i, new ArrayList<>(dp.get(j)));\n dp.get(i).add(words[i]);\n maxLen = Math.max(maxLen, dp.get(i).size());\n }\n } \n }\n }\n\n List<String> res = new ArrayList<>();\n for(List<String> it : dp) {\n if(it.size() == maxLen) {\n res.addAll(it);\n break;\n }\n }\n return res;\n }\n \n private boolean check(String a, String b) {\n int len1 = a.length();\n int len2 = b.length();\n if(len1 != len2) return false;\n \n int hamDist = 0;\n for(int i=0; i<len1; ++i) {\n if(a.charAt(i) != b.charAt(i)) hamDist++;\n if(hamDist > 1) return false;\n }\n return hamDist == 1;\n }\n}\n```
2
0
['Dynamic Programming', 'Java']
0
longest-unequal-adjacent-groups-subsequence-ii
LSI VARIANT TOP DOWN DP
lsi-variant-top-down-dp-by-sai_govind_20-bsre
\n\nclass Solution {\n List<String> longestSubsequence = new ArrayList<>();\n Map<String, List<String>> memo = new HashMap<>();\n\n boolean isHammingDi
Sai_Govind_2024
NORMAL
2023-10-14T16:09:44.868057+00:00
2023-10-19T17:03:48.996741+00:00
268
false
```\n\nclass Solution {\n List<String> longestSubsequence = new ArrayList<>();\n Map<String, List<String>> memo = new HashMap<>();\n\n boolean isHammingDistanceOne(String str1, String str2) {\n if (str1.length() != str2.length()) {\n return false;\n }\n int diffCount = 0;\n for (int i = 0; i < str1.length(); i++) {\n if (str1.charAt(i) != str2.charAt(i)) {\n diffCount++;\n if (diffCount > 1) {\n return false;\n }\n }\n }\n return diffCount == 1;\n }\n\n List<String> backtrack(int ind, int prev, String[] words, int[] groups) {\n if (ind >= words.length) {\n return new ArrayList<>();\n }\n\n String memoKey = ind + "-" + prev;\n if (memo.containsKey(memoKey)) {\n return memo.get(memoKey);\n }\n\n List<String> takeCurrent = new ArrayList<>();\n if (prev == -1 || (groups[prev] != groups[ind] && isHammingDistanceOne(words[ind], words[prev]))) {\n takeCurrent = new ArrayList<>(backtrack(ind + 1, ind, words, groups));\n takeCurrent.add(0, words[ind]);\n\n }\n\n List<String> skipCurrent = backtrack(ind + 1, prev, words, groups);\n\n if (takeCurrent.size() > skipCurrent.size()) {\n memo.put(memoKey, takeCurrent);\n } else {\n memo.put(memoKey, skipCurrent);\n }\n\n return memo.get(memoKey);\n }\n\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n List<String> result = backtrack(0, -1, words, groups);\n return result;\n }\n}\n```\n
2
0
['Dynamic Programming', 'Memoization', 'Java']
2
longest-unequal-adjacent-groups-subsequence-ii
LIS DP solution
lis-dp-solution-by-ujjwal-zmyd
Intuition\nWe can relate this problem to the longest increasing subsequence as we have to find the longest subsequence with a given condition which needs to be
ujjwal___
NORMAL
2023-10-14T16:02:21.613579+00:00
2023-10-14T16:02:21.613607+00:00
239
false
# Intuition\nWe can relate this problem to the longest increasing subsequence as we have to find the longest subsequence with a given condition which needs to be checked before considering it to subsequence. In LIS it\'s current number should be greater than previous and here it is that groups should be different from previous and hamming distance should be equal to 1.\n\n# Approach\nNow If somehow we can keep track of which previous index is updating the current index and we have an ultimate maximum index which is where maximum length subsequence ends then we can backtrack from that index by storing parent for each index and finally we can reverse our answer and return it. we can calculate parent for each index whenever its dp[index] value is updated. Here dp[index] value represents maximum length subsequence ending at index.\n\nRelated problem- https://leetcode.com/problems/longest-string-chain/\n\n# Complexity\n- Time complexity:O(N*N)\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n int dp[1001];\n int get(string s,string t){\n if(s.size()!=t.size()) return 2;\n \n int ct=0;\n for(int i=0;i<s.size();i++){\n if(s[i]!=t[i]) ct++;\n }\n \n if(ct!=1) return 2;\n return 1;\n }\n \n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n memset(dp,0,sizeof(dp));\n \n vector<int>par(n+1);\n \n for(int i=0;i<n;i++){\n dp[i]=1;\n par[i]=i;\n }\n \n \n int last=0;\n int maxi=0;\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n int hamming=get(words[i],words[j]);\n if(hamming==1 && groups[i]!=groups[j]) {\n if(dp[i]+1>dp[j]){\n dp[j]=dp[i]+1;\n par[j]=i;\n \n }\n }\n }\n if(maxi<dp[i]){\n maxi=dp[i];\n last=i;\n }\n }\n \n \n vector<string>ans;\n while(par[last]!=last){\n ans.push_back(words[last]);\n last=par[last];\n }\n ans.push_back(words[last]);\n \n reverse(ans.begin(),ans.end());\n \n return ans;\n \n }\n};\n
2
1
['C++']
1
longest-unequal-adjacent-groups-subsequence-ii
Intuition | Optimized Solution | With Universal LIS template
intuition-optimized-solution-with-univer-z7mz
IntuitionThe question demands length of longest increasing subsequence based on certain condition, hence it is a LIS variantApproachBelow is Universal Template
RadhaKrishnaaaa
NORMAL
2025-01-04T01:23:16.312851+00:00
2025-01-04T01:26:16.754676+00:00
48
false
# Intuition The question demands length of longest increasing subsequence based on certain condition, hence it is a LIS variant # Approach **Below is Universal Template for all LIS questions**: *NOTE: IT IS LIS VARIANT* 1) ***How to idetify LIS variant?*** Any question which asks for longest subsequence based on certain conditions like LIS[i+1] > LIS[i] or LIS[i+1]%LIS[i] == 0 or any other condition (LIS check condition), then it can be a LIS variant 2) ***Basic template*** ``` int LIS(vector<string>& words, vector<int>& groups) { int n = words.size(); vector<int>dp(n, 1); int maxLen = 1; int lastIdx = 0; vector<int>prevIdx(n, -1); for(int i=0; i<n; i++){ ----> dp[i] = Lenght of LIS ending at index 'i' for(int j = 0; j<i; j++){ if(groups[i] != groups[j] && hamming(words[i], words[j]) == 1){ ----> LIS check condition (depends on ques) if(dp[j] + 1 > dp[i]){ dp[i] = dp[j]+1; prevIdx[i] = j; } } } if(dp[i] > maxLen){ lastIdx= i; maxLen = dp[i]; } } return maxLen; ----> or you can print the LIS using prevIdx and lastIdx } ``` # Complexity - Time complexity: O(n^2) - Space complexity: O(n) # Code ```cpp [] class Solution { public: int hamming(string &s1, string &s2){ int m = s1.length(); int i = 0; int hd = 0; while(i < m){ if(s1[i] != s2[i]) hd++; i++; } return hd; } vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) { int n = words.size(); vector<int>dp(n, 1); int maxLen = 1; int lastIdx = 0; vector<int>prevIdx(n, -1); for(int i=0; i<n; i++){ for(int j = 0; j<i; j++){ if(groups[i] != groups[j] && words[i].length() == words[j].length() && hamming(words[i], words[j]) == 1){ if(dp[j] + 1 > dp[i]){ dp[i] = dp[j]+1; prevIdx[i] = j; } } } if(dp[i] > maxLen){ lastIdx= i; maxLen = dp[i]; } } vector<string>ans; for(int i = lastIdx; i != -1; i = prevIdx[i]){ ans.push_back(words[i]); } reverse(ans.begin(), ans.end()); return ans; } }; ```
1
0
['Dynamic Programming', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
DFS Python solution
dfs-python-solution-by-programcoder99-pvai
Intuition\nBased on the same DFS solution given here in C++, but this is a Python3 version\n\n# Approach\nDo a DFS walk from each node that has not been visited
ProgramCoder99
NORMAL
2023-11-03T16:59:12.686800+00:00
2023-11-03T16:59:12.686824+00:00
37
false
# Intuition\nBased on the same DFS solution given here in C++, but this is a Python3 version\n\n# Approach\nDo a DFS walk from each node that has not been visited yet. At each step if the adjacent node is visited and its level `visit_level` is GTE to the current node, stop further exploration. This is because it means the adjacent node has already been part of a longer DFS walk and solution, so we need not explore the current node further.\n\n# Complexity\n- Time complexity: O(len(words) + edges)\n\n- Space complexity: O(len(words) * max word length)\n\n# Code\n```\nclass Solution:\n def __init__(self):\n self.result = []\n\n\n def dfs(self, words, i, level, adjacency_list, visit_level, curr_dfs):\n if visit_level[i] >= level:\n return\n\n visit_level[i] = level\n curr_dfs.append(words[i])\n\n if len(adjacency_list[i]) == 0 and len(self.result) < len(curr_dfs):\n self.result = curr_dfs[:]\n\n for nbr in adjacency_list[i]:\n self.dfs(words, nbr, level+1, adjacency_list, visit_level, curr_dfs)\n\n curr_dfs.pop()\n\n\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n adjacency_list = [[] for _ in range(n)]\n\n for i in range(len(words)):\n for j in range(i+1, len(words)):\n if len(words[i]) != len(words[j]):\n continue\n \n if groups[i] == groups[j]:\n continue\n\n cnt_diff = sum([1 if words[i][k] != words[j][k] else 0 for k in range(len(words[i]))])\n\n if cnt_diff > 1:\n continue\n\n adjacency_list[i].append(j)\n\n visit_level = [-1 for _ in range(n)]\n \n for i in range(n):\n if visit_level[i] > -1:\n continue\n self.dfs(words, i, 0, adjacency_list, visit_level, [])\n \n return self.result\n \n```
1
0
['Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
Straightforward Python DP Solution
straightforward-python-dp-solution-by-se-ipbb
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
sekerez
NORMAL
2023-10-17T04:11:54.992439+00:00
2023-10-17T04:11:54.992464+00:00
27
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\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:\n def getWordsInLongestSubsequence(self, l: int, words: List[str], groups: List[int]) -> List[str]:\n dp = [[word] for word in words]\n for i in range(1, l):\n for j in range(i, -1, -1):\n cur, prv = words[i], words[j]\n if (\n groups[i] != groups[j] \n and len(dp[j]) >= len(dp[i])\n and len(cur) == len(prv) \n and sum(bool(cc != pc) for cc, pc in zip(cur, prv)) == 1\n ):\n dp[i] = dp[j] + [cur]\n return max(dp, key=lambda s: len(s))\n \n \n \n \n \n```
1
0
['Python3']
1
longest-unequal-adjacent-groups-subsequence-ii
Fastest Python Solution (Faster than 100 %) with graph and DP solution
fastest-python-solution-faster-than-100-4way9
Intuition\n Describe your first thoughts on how to solve this problem. \nJust a small request i.e don\'t look the length of solution and just go away once see m
praneeth_nellut1
NORMAL
2023-10-15T17:23:55.645874+00:00
2023-10-15T17:23:55.645898+00:00
38
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust a small request i.e don\'t look the length of solution and just go away once see my intution and see each and every code snippet as a block then you will also get my approch.\n\nThe basic intution behind this solution is given in problem we just need to find the longest subsequence with the hamming distance of 1 and 2 continuous words group value in the chain should not be equal.\n\nJust find the longest chain from each word such that no two consecutive words should be of same group.\n\nYou just need to realize and visulaize the problem as a directed graph where there are different words as different components and the adjacent nodes are the ones with hamming distance of 1.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInorder to find the words of hamming distance with distance 1 let us, create a graph such that from each word we select other words of hamming distance of 1.\n```\ngraph = collections.defaultdict(list)\nfor i in range(n):\n for j in range(i + 1, n):\n if hammingDistance(words[i], words[j]) <= 1 and groups[i] != groups[j]:\n graph[words[i]].append(words[j])\n\n```\nIn this way we can get all possible adjacent words from each words. From here the problem just simplifies to finding the deepest node from each word.\n\nwe can do that exactly with the following dfs function.\n```\ndef dfs(word):\n if word not in graph:\n return [word]\n\n # memoization\n if word in dp:\n return dp[word]\n\n # storing the longest word out of all 1 distance hamming words\n maxlen = 0\n res = []\n\n # iterating through all the possible 1 hamming distance words\n for w in graph[word]:\n temp = dfs(w)\n l = len(temp)\n if l > maxlen:\n res = temp\n maxlen = l\n\n # storing in dp\n dp[word] = [word] + res\n return dp[word]\n```\nThis function not only find the deepest node but also returns the words in that route. We just need to look up all the nodes and find the longest route and return it.\n\nwe can do memoization inorder to store the repeating subProblems since a word can occur multiple times as we are calling from the function and also from the below for loop.\n\nwe can find the hammming distance between 2 words in this way:\n```\ndef hammingDistance(word1, word2):\n if len(word1) != len(word2):\n return 2\n dist = 0\n for i in range(len(word1)):\n if word1[i] != word2[i]:\n dist += 1\n return dist\n```\n\nBy combining all these individual pieces we can get over overall solution which is faster than 100% in python.\n\n\n# Complexity\n- Time complexity: Overall $$O(n ^ 2)$$\n\n---> For building the graph $$O(n^2)$$\n---> For finding the Hamming distnace $$O(len(word))$$\n---> For dfs with memoization $$O(n)$$\n\n- Space complexity: Overall $$O(n ^ 2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n---> For graph $$O(n ^ 2)$$\n---> For memoization $$O(n)$$\n# Code\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n # Function for finding the hamming distance between 2 words\n def hammingDistance(word1, word2):\n if len(word1) != len(word2):\n return 2\n dist = 0\n for i in range(len(word1)):\n if word1[i] != word2[i]:\n dist += 1\n return dist\n\n\n\n # Creating the graph that is directed and from one word to other only if their groups are not same \n graph = collections.defaultdict(list)\n for i in range(n):\n for j in range(i + 1, n):\n if hammingDistance(words[i], words[j]) <= 1 and groups[i] != groups[j]:\n graph[words[i]].append(words[j])\n\n\n\n # little trick to handle edge cases\n if not graph:\n return [words[0]]\n\n # dp dfs solution\n dp = {}\n\n def dfs(word):\n if word not in graph:\n return [word]\n\n # memoization\n if word in dp:\n return dp[word]\n \n # storing the longest word out of all 1 distance hamming words\n maxlen = 0\n res = []\n\n # iterating through all the possible 1 hamming distance words\n for w in graph[word]:\n temp = dfs(w)\n l = len(temp)\n if l > maxlen:\n res = temp\n maxlen = l\n\n # storing in dp\n dp[word] = [word] + res\n return dp[word]\n\n\n # finding solution for all keys\n maxl = 0\n ans = []\n for word in graph.keys():\n t = dfs(word)\n le = len(t)\n\n if le > maxl:\n ans = t\n maxl = le\n\n\n # final result\n return ans\n```
1
0
['Dynamic Programming', 'Depth-First Search', 'Graph', 'Recursion', 'Memoization', 'Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
[Python 3] 15x speedup over the current fastest solutions (0.115 ms vs 1.728 s)
python-3-15x-speedup-over-the-current-fa-rb8e
Intuition\nThe graph is a DAG, after building the graph you can use DP to compute the longest path.\n\n# Approach\nAfter building the graph you can traverse the
nan-do
NORMAL
2023-10-15T13:26:46.818688+00:00
2023-10-15T13:34:42.797395+00:00
54
false
# Intuition\nThe graph is a DAG, after building the graph you can use DP to compute the longest path.\n\n# Approach\nAfter building the graph you can traverse the graph from the highest to the lowest index caching the intermediate results, having a couple of auxiliary arrays to keep track of the succesor and the length to a given node.\n\n# Complexity\n- Time complexity:\nBuilding the graph is the highest cost it takes O(n^2)\n\n- Space complexity:\nIt depends on the constraints to build the graph at least O(n)\n\n# Code\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n succs, lens = [-1] * n, [0] * n\n\n def DFS(graph, node):\n nonlocal succs, lens\n\n if lens[node] > 0:\n return lens[node]\n\n suc, max_len = -1, 0\n for child in graph[node]:\n d = DFS(graph, child)\n if d > max_len:\n max_len = d\n suc = child\n\n succs[node] = suc\n lens[node] = max_len + 1\n\n return max_len\n\n graph = collections.defaultdict(list)\n swords = collections.defaultdict(list)\n\n # Build the graph\n for i in range(n):\n word = words[i]\n #print(f"Index {i} Word {word}")\n for p in range(len(word)):\n sword = word[:p] + \'*\' + word[p+1:]\n #print(f"From {word} to {sword}")\n for j in swords[sword]:\n if groups[i] != groups[j]:\n graph[j].append(i)\n swords[sword].append(i)\n\n \n # Populate the paths\n for node in range(n-1, -1, -1):\n DFS(graph, node)\n\n # Rebuild the best path\n index, max_len = -1, 0\n for i in range(n):\n if lens[i] > max_len:\n index = i\n max_len = lens[i]\n\n ans = []\n while succs[index] != -1:\n ans.append(words[index])\n index = succs[index]\n\n ans.append(words[index])\n\n return ans\n```
1
0
['Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
[Python] ✅ Easy beginner solution - O(n^2) || Beats 100%
python-easy-beginner-solution-on2-beats-ecbc2
\n\n\n## Explanation\n Describe your approach to solving the problem. \nStep 1. Precompute the hamming distance between any two words and store the precomputed
lshamsschaal
NORMAL
2023-10-14T22:59:55.919964+00:00
2023-10-17T05:03:53.185417+00:00
180
false
![Screenshot 2023-10-14 at 3.39.43 PM.png](https://assets.leetcode.com/users/images/0e989c2b-dc95-4c3f-ba02-382939923f19_1697323357.2658832.png)\n\n\n## Explanation\n<!-- Describe your approach to solving the problem. -->\nStep 1. Precompute the hamming distance between any two words and store the precomputed distances in an n x n matrix.\n\nStep 2. For every word in words compute the longest subsequence, checking against all subsequences that end before it. \n- For example if we had the sequence ["a", "b", "c"], we would go over each word and the longest subsequence for that word would be the longest subsequence for any word before it + 1.\n\nStep 3. After finding the length of longest subsequence work backwards to reconstruct the longest subsequence.\n\n\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n # Precompute the hamming distance between any two words - O(n^2)\n # Stored in a grid where hamming[i][j] = hamming(words[i], words[j])\n # Put -1 in place of unequal length words\n hamming = [[0] * n for i in range(n)] # n x n grid of zeros\n\n for i, word1 in enumerate(words):\n for j, word2 in enumerate(words[i + 1:], start=i + 1):\n if len(word1) != len(word2):\n hamming[i][j] = -1\n continue\n\n # Compute hamming distance\n hamming_dist = 0\n for char1, char2 in zip(word1, word2):\n hamming_dist += char1 != char2\n if hamming_dist > 1:\n break\n hamming[i][j] = hamming[j][i] = hamming_dist\n\n dp = [1] * n # dp[i] is the longest subsequence possible ending at words[i]\n prev = [-1] * n # Keep track of the sequence of words\n\n for word_idx in range(n):\n for prev_word_idx in range(word_idx):\n if hamming[word_idx][prev_word_idx] != 1:\n continue\n if groups[word_idx] == groups[prev_word_idx]:\n continue\n\n # If the longest subseqence ending at words[i] is greater than\n # the subsequence we\'re looking at, use the one ending at words[i]\n # and add 1 for the current word\n if dp[word_idx] <= dp[prev_word_idx]:\n dp[word_idx] = dp[prev_word_idx] + 1\n prev[word_idx] = prev_word_idx\n \n # Compute argmax of dp\n _, argmax = max((dp[i], i) for i in range(n))\n\n # Starting at argmax step backwards through prev to reconstruct the sequence\n longest_sub = []\n while argmax != -1:\n longest_sub.append(words[argmax])\n argmax = prev[argmax]\n\n return reversed(longest_sub)\n```\n\n## Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$ - For the hamming distance matrix\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1
0
['Dynamic Programming', 'Python3']
1
longest-unequal-adjacent-groups-subsequence-ii
simple LIS Solution
simple-lis-solution-by-priyanshucoding-8wje
\n\nclass Solution {\npublic:\n \n \n int get(string s,string t){\n if(s.size()!=t.size()) return 2;\n \n int ct=0;\n for(i
priyanshucoding
NORMAL
2023-10-14T18:15:56.063055+00:00
2023-10-14T18:15:56.063074+00:00
141
false
```\n\nclass Solution {\npublic:\n \n \n int get(string s,string t){\n if(s.size()!=t.size()) return 2;\n \n int ct=0;\n for(int i=0;i<s.size();i++){\n if(s[i]!=t[i]) ct++;\n }\n \n if(ct!=1) return 2;\n return 1;\n }\n \n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n // int n=words.size();\n vector<int> dp(n,1);\n vector<int> hash(n,1);\n for(int i=0;i<n;i++){\n hash[i]=i;\n for(int j=0;j<=i-1;j++){\n if(groups[i]!=groups[j] && words[i].size()==words[j].size() && get(words[i],words[j])==1){\n if(dp[i]<dp[j]+1){ dp[i]=1+dp[j];\n hash[i]=j;}\n }\n }\n }\n int ans = -1;\n int lastIndex =-1;\n \n for(int i=0; i<=n-1; i++){\n if(dp[i]> ans){\n ans = dp[i];\n lastIndex = i;\n }\n }\n vector<string> temp;\n temp.push_back(words[lastIndex]);\n \n while(hash[lastIndex] != lastIndex){ \n lastIndex = hash[lastIndex];\n temp.push_back(words[lastIndex]); \n }\n reverse(temp.begin(),temp.end());\n return temp;\n }};\n\t```
1
0
['Dynamic Programming', 'C']
0
longest-unequal-adjacent-groups-subsequence-ii
Easy solution || C++ || DP
easy-solution-c-dp-by-ankit6378yadav-wj1o
Code\n\nclass Solution {\npublic:\n bool cmp(string a, string b){\n if(a.size()!=b.size()) return false;\n int cnt=0;\n for(int i=0;i<a.
ankit6378yadav
NORMAL
2023-10-14T17:13:43.721801+00:00
2023-10-14T17:13:43.721825+00:00
272
false
# Code\n```\nclass Solution {\npublic:\n bool cmp(string a, string b){\n if(a.size()!=b.size()) return false;\n int cnt=0;\n for(int i=0;i<a.size();i++){\n if(a[i]!=b[i]){\n cnt++;\n if(cnt>1) return false;\n }\n }\n return cnt==1?true:false;\n }\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<vector<string>> dp(n);\n for (int i = 0; i < n; i++) {\n dp[i].push_back(words[i]);\n }\n int len=1;\n for (int i = 0; i < n; i++) {\n for (int j = i - 1; j >= 0; j--) {\n if (groups[i] != groups[j] && cmp(words[j], words[i])) {\n if (dp[j].size() + 1 > dp[i].size()) {\n dp[i] = dp[j];\n dp[i].push_back(words[i]);\n len = max(len,int(dp[i].size()));\n }\n }\n }\n }\n\n vector<string> ans;\n for (int i = 0; i < n; i++) {\n if (dp[i].size() == len) {\n result = dp[i];\n break;\n }\n }\n return ans;\n }\n};\n```
1
0
['Dynamic Programming', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
C++ || LIS || Standard DP ||
c-lis-standard-dp-by-neon772-glt9
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
neon772
NORMAL
2023-10-14T17:02:42.402012+00:00
2023-10-14T17:02:42.402038+00:00
37
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 {\npublic:\n bool hamming(string &a, string &b) {\n int cnt = 0;\n for (int i = 0; i < a.size(); ++i) {\n if (a[i] != b[i]) \n cnt++;\n }\n return cnt == 1;\n }\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<int> dp(n, 0); // length dp\n vector<int> parent(n, -1);\n\n for (int i = 0; i < n; i++) {\n dp[i]=1;\n // parent[i]=-1;\n for (int j = 0; j < i; j++) {\n if (groups[i] != groups[j] and words[i].size() == words[j].size() and hamming(words[i], words[j])) {\n if (dp[j] + 1 > dp[i]) {\n dp[i] = dp[j] + 1;\n parent[i] = j;\n }else{\n dp[j]=dp[j];\n }\n }\n }\n }\n // for(auto i=0;i<n;i++){\n // cout<<words[i]<<" "<<dp[i]<<" "<<past[i]<<" "<<endl;\n // }\n int idx = max_element(dp.begin(), dp.end()) - dp.begin();\n vector<string> ans;\n while (idx != -1) {\n ans.push_back(words[idx]);\n idx = parent[idx];\n }\n\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n\n\n```
1
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
[Python] Bottom-up, LIS, Process string length separately
python-bottom-up-lis-process-string-leng-6qck
Approach\n- Handle each string length separately\n- Return the maximum of the longest subsequence for each length\n- Use a parents array to get the subsequence
liivan256
NORMAL
2023-10-14T16:44:02.012062+00:00
2023-10-14T16:44:02.012085+00:00
19
false
# Approach\n- Handle each string length separately\n- Return the maximum of the longest subsequence for each length\n- Use a parents array to get the subsequence (otherwise we only have the length)\n\n# Complexity\n- Time complexity: $$O(n^2)$$\nWorst case is when all strings have equal length.\n\n- Space complexity: $$O(n)$$\nDP array takes O(n) space.\n\n# Code\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n def hdist(s, t):\n return sum(i != j for i, j in zip(s, t))\n\n wl = [[] for _ in range(11)] # (word, index)\n for i, w in enumerate(words):\n wl[len(w)].append((w, i))\n\n res = []\n for length in range(1, 11):\n if not wl[length]:\n continue\n\n arr = wl[length]\n dp = [1] * len(arr)\n parent = [-1] * len(arr)\n\n for i in range(1, len(arr)): # fill in dp table\n for j in range(i):\n if groups[arr[i][1]] != groups[arr[j][1]] and hdist(arr[i][0], arr[j][0]) == 1 and dp[i] < dp[j] + 1:\n dp[i] = dp[j] + 1\n parent[i] = j\n\n trace = dp.index(max(dp)) # trace back to starting element\n sub_seq = []\n\n while trace != -1: # root element is guaranteed to not have parent\n sub_seq.append(arr[trace][1])\n trace = parent[trace]\n\n res.append([words[i] for i in reversed(sub_seq)])\n\n return max(res, key=len)\n```
1
0
['Dynamic Programming', 'Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
LIS variation 💉 | Brute force 😱 | Easy to implement 💯
lis-variation-brute-force-easy-to-implem-d3d0
Code\n\nclass Solution {\npublic:\n bool hamming_distance_1(string &s, string &t) {\n int c=0;\n if((s.size()!=t.size()) || (s==t)) return 0;\n
naveen-chokkapu
NORMAL
2023-10-14T16:33:03.196132+00:00
2023-10-14T16:52:02.620129+00:00
94
false
# Code\n```\nclass Solution {\npublic:\n bool hamming_distance_1(string &s, string &t) {\n int c=0;\n if((s.size()!=t.size()) || (s==t)) return 0;\n for(int i=0;i<s.size();i++) {\n if(s[i]!=t[i]) c++;\n if(c>1) return 0;\n }\n return c==1;\n }\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& w, vector<int>& g) {\n unordered_map<int,vector<string>> m;\n // m[i] - maximum groups at index i\n\n int k=INT_MIN,t;\n for(int i=0;i<n;i++) {\n int p=i, c=INT_MIN;\n for(int j=i-1;j>=0;j--) {\n if(g[i]!=g[j] && hamming_distance_1(w[i],w[j])) {\n int x=m[j].size();\n if(x>c) {\n c=x; p=j;\n // getting maximum groups until i-th index from [0 .. i-1]\n }\n } \n }\n for(auto j:m[p])\n m[i].push_back(j);\n m[i].push_back(w[i]);\n // appending all those groups at index i\n \n int x=m[i].size();\n if(x>k) {\n k=x; t=i;\n // from all groups, finally we need maximum one \n }\n }\n return m[t];\n }\n};\n```\n# Time - O(N^3), Space - O(N^2)\n\nI haven\'t considered space complexity in contests; I\'m determined to solve it at all costs !!\n\n```\nUpvote \uD83D\uDE4F\uD83D\uDE4F\n```
1
0
['Dynamic Programming', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
[JAVA] Bottom Up DP O(n^2) Simple, 41ms
java-bottom-up-dp-on2-simple-41ms-by-frv-dde2
Problem 3 of the Biweekly Contest 115\n# Intuition\n Describe your first thoughts on how to solve this problem. \nDP is commonly used in subsequence problems so
frvnk
NORMAL
2023-10-14T16:21:32.318084+00:00
2023-10-14T19:02:19.657888+00:00
118
false
Problem 3 of the Biweekly Contest 115\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDP is commonly used in subsequence problems so I went with that. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe want to have a DP array where DP[i] stores the length of the longest subsequence of the first $$i$$ words that includes words[i] and the index to a previous word in one of the longest subsequences for backtracking and finding the longest later. We will also have a variable keeping track of the length of the longest subsequences we have seen (max) as well as the index to the last character for one of them (maxIndex).\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n^2m)$$ where $$m$$ is the length of each word in words.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ for the DP array\n# Code\n```\nclass Solution {\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) { \n //DP? O(n^2)\n int max = 0;\n int maxIndex = -1;\n int DP[][] = new int[n][2]; //Stores the max length and prev index (-1) means no previous index\n for(int i = 0; i<n; i++){\n int currMax = 1;\n int currMaxIndex = -1;\n for(int j = 0; j< i; j++){\n //Check if group different, words are valid\n if(groups[i]!=groups[j]&&hammingDist(words[i],words[j])){\n if(DP[j][0]> currMax){\n currMax = DP[j][0];\n currMaxIndex = j;\n } \n }\n }\n DP[i][0] = currMax+1;\n DP[i][1] = currMaxIndex;\n if(DP[i][0]>max){\n max = DP[i][0];\n maxIndex = i;\n }\n }\n \n List<String> res = new ArrayList<>();\n \n while(maxIndex > -1){\n //System.out.println(maxIndex);\n res.add(words[maxIndex]);\n maxIndex = DP[maxIndex][1];\n }\n \n Collections.reverse(res);\n return res;\n }\n \n //Checks if two strings are equal length and hamming distance is 1\n private boolean hammingDist(String s1, String s2){\n if(s1.length()!=s2.length()) return false;\n int curr = 0;\n for(int i =0; i< s1.length(); i++){\n if(s1.charAt(i) != s2.charAt(i)){\n curr++;\n if(curr >1 ) return false;\n }\n }\n return curr ==1;\n }\n}\n\n```
1
0
['Dynamic Programming', 'Java']
1
longest-unequal-adjacent-groups-subsequence-ii
Dynamic Programming || Easy to understand || C++
dynamic-programming-easy-to-understand-c-vtno
\n# Complexity\n- Time complexity : O(n^2)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity : O(n)\n Add your space complexity here, e.g. O(n)
GojoSatrou
NORMAL
2023-10-14T16:19:39.803380+00:00
2023-10-14T16:19:39.803398+00:00
125
false
\n# Complexity\n- Time complexity : $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code :\n```\nclass Solution {\npublic:\n // This function finds the longest subsequence of words with specific conditions.\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n // We need a dynamic programming array to keep track of the longest subsequences.\n vector<int> dp(n, 1);\n // Initialize maxLen with 1, and endIndex to track where the longest subsequence ends.\n int maxLen = 1;\n int endIndex = 0;\n\n // We\'re going to iterate through the words and groups to find the longest subsequence.\n for (int i = 1; i < n; ++i) {\n for (int j = 0; j < i; ++j) {\n // We\'ll check if words[i] and words[j] meet certain conditions to be part of the same subsequence.\n if (groups[i] != groups[j] && words[i].length() == words[j].length() && hammingDistance(words[i], words[j]) == 1) {\n // If conditions are met, update the dp array.\n dp[i] = max(dp[i], dp[j] + 1);\n // If we find a longer subsequence, update maxLen and endIndex.\n if (dp[i] > maxLen) {\n maxLen = dp[i];\n endIndex = i;\n }\n }\n }\n }\n\n // Now, let\'s reconstruct the longest subsequence.\n vector<string> result(maxLen); // We know the length now.\n result[maxLen - 1] = words[endIndex]; // The last word is the one at the endIndex.\n\n for (int i = maxLen - 2; i >= 0; --i) {\n for (int j = endIndex - 1; j >= 0; --j) {\n // We need to find words to fill in the subsequence.\n if (dp[j] == i + 1 && groups[j] != groups[endIndex] && words[j].length() == words[endIndex].length() && hammingDistance(words[j], words[endIndex]) == 1) {\n result[i] = words[j];\n endIndex = j; // Move to the next word.\n break;\n }\n }\n }\n\n // Finally, return the result containing the longest subsequence.\n return result;\n }\n\n // This function calculates the Hamming distance between two strings.\n int hammingDistance(const string& a, const string& b) {\n int diff = 0;\n for (int i = 0; i < a.length(); ++i) {\n if (a[i] != b[i]) {\n ++diff;\n }\n }\n return diff;\n }\n};\n\n```\n---\n\n**PLEASE UPVOTE IF YOU LIKED THE SOLUTION :)**\n\n![Happy Doggo Leetcode.gif](https://assets.leetcode.com/users/images/20003afb-511b-4624-8579-39a617a3ce16_1697300300.8906367.gif)\n
1
0
['Dynamic Programming', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
Easy C++ DP Solution || Explain Intuition
easy-c-dp-solution-explain-intuition-by-0k4kn
\n# Code\n\nclass Solution {\npublic:\n \n vector<int> dp;\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& gro
manraj_singh_16447
NORMAL
2023-10-14T16:13:16.317974+00:00
2023-10-14T16:13:16.318007+00:00
212
false
\n# Code\n```\nclass Solution {\npublic:\n \n vector<int> dp;\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n \n dp.resize(n , -1);\n \n \n int maxi = 0 , index = 0;\n \n // keeping next stored of each indx to rebuild the sequence\n vector<int> next(n , -1);\n for(int i = 0; i < n; i++){\n \n int ans = solve(i , n , words , groups , next);\n if(maxi < ans){\n\n maxi = ans;\n index = i;\n }\n }\n\n \n vector<string> s;\n\n // while next != -1 , means no possible next\n while(index != -1){\n \n // push word at index\n s.push_back(words[index]);\n // move to next index\n index = next[index];\n }\n \n return s;\n }\n\n // function to check the conditions of hamming distance and groups\n bool isok(int index, int i, vector<string>& words, vector<int>& groups) {\n\n \n if (groups[index] == groups[i]) {\n return false;\n }\n\n if (words[index].size() != words[i].size()) {\n return false;\n }\n\n int ham = 0;\n for (int k = 0; k < words[index].size(); k++) {\n if (words[index][k] != words[i][k]) {\n ham++;\n }\n if (ham > 1) { // If the Hamming distance exceeds 1, it\'s not a valid match.\n return false;\n }\n }\n\n return (ham == 1); // Hamming distance must be exactly 1.\n}\n\n int solve(int index , int n, vector<string>& words, vector<int>& groups ,vector<int>& next) {\n \n // if index reaches end\n if(index >= n){\n \n return 0;\n }\n \n // using memoizatiosn\n if(dp[index] != -1){\n \n return dp[index];\n }\n \n int ans = 1;\n for(int k = index+1; k < n; k++){\n \n if(isok(index , k , words , groups)){\n \n // check the answer\n int tempans = 1 + solve(k , n , words , groups , next);\n if(tempans > ans){\n \n // if answer is greater than previous then set next as k\n // from current index next = k\n ans=tempans;\n next[index] = k;\n \n }\n }\n \n }\n \n return dp[index] = ans;\n }\n};\n```
1
1
['Dynamic Programming', 'Memoization', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
[JAVA] 100% Faster | O(n^2) Time | Dynamic Programming | Longest Increasing Subsequence Pattern |
java-100-faster-on2-time-dynamic-program-r569
Please Upvote if you understand the approach.\n\n# Complexity\n- Time complexity: O(n^2)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)
yash_vish87
NORMAL
2023-10-14T16:02:59.926832+00:00
2023-10-14T16:20:44.029732+00:00
215
false
# Please Upvote if you understand the approach.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n private boolean validHamming(String word1, String word2) {\n if(word1.length() != word2.length()) {\n return false;\n }\n boolean diff = false;\n for(int i = 0; i < word1.length(); i++) {\n if(word1.charAt(i) != word2.charAt(i)) {\n if(diff) {\n return false;\n }\n diff = true;\n }\n }\n return true;\n }\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n int[] max = new int[n];\n max[n-1] = 1;\n int maxSubseq = 1;\n \n for(int i = n-2; i >= 0; i--) {\n int maxDist = 1;\n for(int j = i+1; j < n; j++) {\n if(groups[i] != groups[j] && validHamming(words[i], words[j])) {\n maxDist = Math.max(max[j]+1, maxDist); \n }\n }\n max[i] = maxDist;\n maxSubseq = Math.max(maxSubseq, maxDist);\n }\n List<String> ans = new ArrayList<>();\n int i = 0, last = -1;\n while(i < n) {\n while(max[i] != maxSubseq) {\n i++;\n }\n \n if(last == -1 || groups[last] != groups[i] && validHamming(ans.get(ans.size()-1), words[i])) {\n ans.add(words[i]);\n last = i;\n maxSubseq--;\n if(maxSubseq == 0) {\n break;\n } \n }\n \n i++;\n }\n return ans;\n }\n}\n```
1
1
['Dynamic Programming', 'Java']
0
longest-unequal-adjacent-groups-subsequence-ii
simple intuitive dp similar to lcs/lis pattern
simple-intuitive-dp-similar-to-lcslis-pa-cqvm
\nclass Solution {\npublic:\n int dis(string &a, string&b)\n {\n if(a.size()!=b.size()) return false;\n int n=a.size();\n int c=0;\n
demon_code
NORMAL
2023-10-14T16:01:59.448215+00:00
2023-10-14T16:12:22.347066+00:00
157
false
```\nclass Solution {\npublic:\n int dis(string &a, string&b)\n {\n if(a.size()!=b.size()) return false;\n int n=a.size();\n int c=0;\n for(int i=0; i<n; i++) if(a[i]!=b[i]) c++;\n \n return c==1;\n \n }\n \n vector<string> getWordsInLongestSubsequence(int n, vector<string>& a, vector<int>& g) \n {\n for(int i=0; i<1000000; i++);\n vector<int> dp(n,1);\n vector<int> p(n,0);\n // int n=a.size();\n for(int i=0; i<n; i++) p[i]=i;\n int mi=0;\n int maxi=1;\n for(int i=0; i<n; i++)\n {\n for(int j=0; j<i; j++)\n {\n if(g[i]!=g[j] && dp[i]<dp[j]+1 && a[i].length()==a[j].length() && dis(a[i],a[j]))\n {\n dp[i]=dp[j]+1;\n p[i]=j;\n if(maxi< dp[i])\n {\n // p[i]=j;\n maxi=dp[i];\n mi=i;\n }\n }\n }\n }\n // cout<<maxi<<endl;\n // cout<<mi<<endl;\n // for(auto i: p) cout<<i<<" ";\n vector<string> ans;\n while(p[mi]!=mi)\n {\n ans.push_back(a[mi]);\n mi=p[mi]; \n } ans.push_back(a[mi]);\n \n reverse(ans.begin(),ans.end());\n return ans;\n \n \n \n }\n};\n\n```
1
0
['C']
0
longest-unequal-adjacent-groups-subsequence-ii
LIS VARIANT | USE SIMPLE LIS TEMPLATE
lis-variant-use-simple-lis-template-by-h-rt9o
IntuitionThis questions revolves arouund lisApproachCheck the condition as described in the question . Similar to LIS , we run two loops i and j i from 1 to n a
Harshthakur1079
NORMAL
2025-04-11T11:24:58.381157+00:00
2025-04-11T11:24:58.381157+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> This questions revolves arouund lis # Approach <!-- Describe your approach to solving the problem. --> Check the condition as described in the question . Similar to LIS , we run two loops i and j i from 1 to n and j from 0 to less than i . check the condions i) words[i].size== words[j].size ii) check if groups [i]!= groups[j] iii) check the hamming dist between words[i] and words[j] is equal to 1 iv) lis condion check if dp[i]< dp[j]+1 then dp[i]=dp[j]+1 ALSO keep an prev vector to get the string # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ -->O(N^2) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ -->O(N) # Code ```cpp [] class Solution { public: int hammingDis(string a,string b){ int x=0; int n=a.size(); int i=0; while(i<n){ if(a[i]!=b[i]) x++; i++; } return x; } vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) { // // lis variant int n=words.size(); if(n==1) return {words[0]}; vector<int>dp(n,1),prev(n,-1); int maxLen=0; int last_ind=-1; for(int i=1;i<n;i++){ for(int j=0;j<i;j++){ if(words[i].size()== words[j].size() && groups[i]!=groups[j] && hammingDis(words[i],words[j])==1 && dp[i]<dp[j]+1 ){ dp[i]=dp[j]+1; prev[i]=j; } if(dp[i] > maxLen){ maxLen=dp[i]; last_ind=i; } } } vector<string>ans; while(last_ind!=-1){ ans.push_back(words[last_ind]); last_ind=prev[last_ind]; } reverse(ans.begin(),ans.end()); return ans; } }; ```
0
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
Longest Hamming Distance Subsequence with Different Groups
longest-hamming-distance-subsequence-wit-u3rk
IntuitionWe need to find the longest subsequence of words such that: Each consecutive pair of words in the subsequence has a Hamming distance of exactly 1 (only
kuldeepchaudhary123
NORMAL
2025-03-19T12:27:41.775347+00:00
2025-03-19T12:27:41.775347+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We need to find the longest subsequence of words such that: 1. Each consecutive pair of words in the subsequence has a Hamming distance of exactly 1 (only one character difference). 2. The words in the subsequence must belong to different groups. The problem requires dynamic programming (DP) to track the longest valid subsequence ending at each index. # Approach <!-- Describe your approach to solving the problem. --> 1. Define DP array: Let dp[i] represent the length of the longest valid subsequence ending at index i. Initialize dp[i] = 1 (each word alone is a valid subsequence). Use parent[i] to store the previous index in the longest sequence. 2. Nested Iteration: Iterate over words[i] and for each words[j] (where j < i), check: If hammingDistance(words[i], words[j]) == 1. If groups[i] != groups[j]. If dp[j] + 1 > dp[i], update dp[i] and set parent[i] = j. 3. Find Maximum Length: Track the maximum element in dp and its corresponding index. 4. Reconstruct the Longest Subsequence: Backtrack using the parent array to construct the sequence. 5. Reverse the Sequence: Since we backtrack from the last element, reverse the sequence before returning. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> Hamming Distance Check: 𝑂(𝑚) per comparison, where 𝑚 is the length of the string. DP Calculation: 𝑂(𝑛2⋅𝑚), since we compare each pair of words. Reconstruction: 𝑂(𝑛). Total Complexity: 𝑂(𝑛2⋅𝑚), which is feasible for moderate input sizes. # Code ```cpp [] class Solution { public: bool hammingDistance(string&s1,string&s2) { if(s1.size()!=s2.size()) return false; int count=0; for(int i=0;i<s1.size();i++) { if(s1[i]!=s2[i]) count++; if(count>1) return false; } return true; } vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) { int n=words.size(); int maxElement=0; vector<int>dp(n,1); vector<int>parent(n,-1); for(int i=0;i<n;i++) { for(int j=0;j<i;j++) { if(hammingDistance(words[i],words[j])&&groups[i]!=groups[j]&&dp[j]+1>dp[i]) { dp[i]=dp[j]+1; parent[i]=j; } } maxElement=max(maxElement,(int)dp[i]); } int maxIndex=-1; for(int i=0;i<n;i++) { if(maxElement==dp[i]) { maxIndex=i; } } vector<string>result; while(maxIndex!=-1) { result.push_back(words[maxIndex]); maxIndex=parent[maxIndex]; } reverse(result.begin(),result.end()); return result; } }; ```
0
0
['Array', 'String', 'Dynamic Programming', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
DP
dp-by-linda2024-uax5
IntuitionApproachComplexity Time complexity: Space complexity: Code
linda2024
NORMAL
2025-03-06T23:11:27.058720+00:00
2025-03-06T23:11:27.058720+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```csharp [] public class Solution { private bool IsHammingDist(string s1, string s2) { int len = s1.Length; if(s2.Length != len) return false; int diffCnt = 0; for(int i = 0; i < len; i++) { if(s1[i] != s2[i]) { if(++diffCnt > 1) return false; } } return diffCnt == 1; } public IList<string> GetWordsInLongestSubsequence(string[] words, int[] groups) { int len = words.Length; int[] dp = Enumerable.Repeat(1, len).ToArray(), preId = Enumerable.Repeat(-1, len).ToArray(); int maxLen = 1, maxId = 0; for(int i = 1; i < len; i++) { for(int j = 0; j < i; j++) { if(groups[i] == groups[j]) continue; if(IsHammingDist(words[i], words[j])) { if(dp[j]+1 > dp[i]) { dp[i] = dp[j]+1; preId[i] = j; } } } if(maxLen < dp[i]) { maxLen = dp[i]; maxId = i; } } int wId = maxId; List<string> res = new(); while(wId != -1) { res.Insert(0, words[wId]); wId = preId[wId]; } return res; } } ```
0
0
['C#']
0
longest-unequal-adjacent-groups-subsequence-ii
beats Minimum 90 || readable code
beats-minimum-90-readable-code-by-sumant-vzc5
Code
sumanth2328
NORMAL
2025-02-23T23:08:08.378447+00:00
2025-02-23T23:08:08.378447+00:00
2
false
# Code ```python3 [] class Solution: def getWordsInLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]: dp=[1]*len(words) mem=[-1]*len(words) for i in range(len(words)-1,-1,-1): for j in range(i+1,len(words)): if groups[i]!=groups[j] and len(words[i])==len(words[j]): dist=0 for k in range(len(words[i])): if words[i][k]!=words[j][k]: dist+=1 if dist>1:break if dist==1: if dp[j]+1>dp[i]: dp[i]=dp[j]+1 mem[i]=j index=dp.index(max(dp)) res = [words[index]] bool=True while bool: if mem[index]==-1: bool=False else: res.append(words[mem[index]]) index=mem[index] return res ```
0
0
['Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
longest inc subsequence variant || optimized code
longest-inc-subsequence-variant-optimize-8gnt
Code
sumanth2328
NORMAL
2025-02-07T15:30:40.720191+00:00
2025-02-07T15:30:40.720191+00:00
6
false
# Code ```python3 [] class Solution: def getWordsInLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]: dp=[1]*(len(words)) store=[-1]*len(words) for i in range(len(words)-1,-1,-1): for j in range(i+1,len(words)): hammingdistance = 0 if len(words[i])==len(words[j]): for k in range(len(words[i])): if words[i][k]!=words[j][k]: hammingdistance+=1 if hammingdistance==1 and groups[i]!=groups[j]: if dp[i]<dp[j]+1: dp[i]=dp[j]+1 store[i]=j maxi = max(dp) idx = dp.index(maxi) res = [words[idx]] while maxi!=1: res.append(words[store[idx]]) idx=store[idx] maxi -= 1 return res ```
0
0
['Array', 'String', 'Dynamic Programming', 'Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
scala threeliner
scala-threeliner-by-vititov-8w0z
null
vititov
NORMAL
2025-02-06T10:39:09.819185+00:00
2025-02-06T10:39:09.819185+00:00
1
false
```scala [] object Solution { import scala.util.chaining._ def getWordsInLongestSubsequence(words: Array[String], groups: Array[Int]): List[String] = { lazy val aMap = (for{ i <- words.indices.to(List) j <- Iterator.range(i+1,words.length) if words(i).size == words(j).size && groups(i) != groups(j) && (words(i) zip words(j)).map{case (a,b) => (a-b).sign.abs}.sum == 1 } yield {(i,j)}).groupMap(_._1)(_._2) lazy val cMap = words.indices.reverse.foldLeft(Map.empty[Int,Int]){case (bMap,i) => bMap + (i -> (aMap.getOrElse(i,Nil).flatMap(bMap.get).maxOption.getOrElse(0)+1)) } List.unfold(cMap.iterator.maxBy(_._2)._1){case i => Option.when(i>=0){ (words(i), aMap.get(i).toList.flatten.maxByOption(cMap).getOrElse(-1)) }} } } ```
0
0
['Dynamic Programming', 'Greedy', 'Scala']
0
longest-unequal-adjacent-groups-subsequence-ii
DP solution JAVA
dp-solution-java-by-prachikumari-d3y9
IntuitionNot much of complex dp : Things to keep in mind : Get the maxSubLen (following all conditions) ending at any index i Take the maxSubLen, and retrace th
PrachiKumari
NORMAL
2025-01-15T13:31:30.129101+00:00
2025-01-15T13:31:30.129101+00:00
3
false
# Intuition Not much of complex dp : Things to keep in mind : - Get the maxSubLen (following all conditions) ending at any index i - Take the maxSubLen, and retrace the index of words making the subsequence ending at ith index (longest length) - To retrace the path for resultant list of strings, keep tracking the prev word Index of word , which subs end at ith index # Approach 1. Take dp[], prevIdx[], maxSubsLen, maxIdx(wordIdx where longest Subsequence ends) 2. for dp[i] = maxLength of Subsequence ending at ith index , check all words from j=0 upto j<i 3. Conditions :- - Groups Values not equal - Words length should be = - If length = then check for hamming distance 4. then if valid word at any jth idx found where j<i, update the length of maxLen of subseque dp[i] = dp[j] + 1 (i.e to merge the length of sub ending at j ) & since words[j], words[i] also satisfies to be in valid subsquence then update the length ending at ith index, dp[i] And do update the prevWord index for prev[i] = j, because now the prevWord in subsequence ending at ith idx = jth words 5. Then after calculate all maxSubs length, for the ith idx (maximise the maxSubsLength found in whole words) and idx as well 6. Then maxIdx give the where the maxSubsLength has been ended and then retrack using prevIdx , as prevIdx contains the idx of prevWord forming a valid subs ending at the idx But since we are retracking then do reverse the resultant list , to get right seq # Complexity - Time complexity: O(n^2*length(words[i])) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n + n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public boolean hamCheck(String w1, String w2){ int diff = 0; int n = w1.length(); for (int i = 0; i < n; i++) { if (w1.charAt(i) != w2.charAt(i)) { diff++; if (diff > 1) return false; } } return diff == 1; } public List<String> getWordsInLongestSubsequence(String[] words, int[] groups) { int n = words.length; List<String> res = new ArrayList<>(); if (n <= 0) return res; if (n == 1) { res.add(words[0]); return res; } int []dp = new int[n];// length of maxSub ending at ith index int []prevIdx = new int[n];// to keep track the prevWord idx of subSeq (-1 shows subsequence ended) Arrays.fill(dp, 1); Arrays.fill(prevIdx, -1); int maxSubsLen = -1; int maxIdx = -1; for (int i = 1 ; i<n ;i++){// len of subs ending at ith index for (int j = 0; j<i ; j++){// get the subsequence if (groups[i] == groups[j]) continue; if (words[i].length() != words[j].length()) continue; if (!hamCheck(words[i], words[j])) continue; if (dp[i] < dp[j]+1){ dp[i] = dp[j] + 1; prevIdx[i] = j;// this is the prevWord in Sub for ith } } if (maxSubsLen < dp[i]){ maxSubsLen = dp[i]; maxIdx = i;// ie maxSubs is ending at ith index } } while (maxIdx != -1){ res.add(words[maxIdx]); maxIdx = prevIdx[maxIdx]; } Collections.reverse(res); return res; } } ```
0
0
['Java']
0
longest-unequal-adjacent-groups-subsequence-ii
Bottom-up DP, beats 100%
bottom-up-dp-beats-100-by-germanov_dev-a0p7
Complexity Time complexity: O(n2) Space complexity: O(n2) Code
germanov_dev
NORMAL
2025-01-11T12:11:04.125217+00:00
2025-01-11T12:11:04.125217+00:00
4
false
# Complexity - Time complexity: $$O(n^2)$$ - Space complexity: $$O(n^2)$$ # Code ```rust [] impl Solution { pub fn get_words_in_longest_subsequence(words: Vec<String>, groups: Vec<i32>) -> Vec<String> { let mut dp:Vec<Vec<&str>> = vec![vec![];words.len()]; dp[words.len()-1] = vec![]; let (mut max,mut max_idx) = (0,0); for idx in (0..words.len()-1).rev() { for idx1 in idx+1..words.len() { if Solution::is_match(&words,&groups,idx,idx1) && dp[idx].len() <= dp[idx1].len() { let mut items = vec![words[idx1].as_str()]; for item in dp[idx1].iter() { items.push(item); } dp[idx] = items; if dp[idx].len() > max { max = dp[idx].len(); max_idx = idx; } } } } let mut result = vec![words[max_idx].clone()]; for item in dp[max_idx].iter() { result.push(item.to_string()) } result } pub fn is_match(words: &Vec<String>, groups: &Vec<i32>, idx1:usize, idx2:usize) -> bool { if groups[idx1] == groups[idx2] { return false;} if words[idx1].len() != words[idx2].len() { return false; } let mut dist = 0; let word1 = words[idx1].as_bytes(); let word2 = words[idx2].as_bytes(); for idx in 0..word1.len() { if word1[idx] != word2[idx] { dist += 1;} } dist == 1 } } ```
0
0
['Rust']
0
longest-unequal-adjacent-groups-subsequence-ii
Deep Down DP lane
deep-down-dp-lane-by-tonitannoury01-2lxd
IntuitionApproachComplexity Time complexity: O(n**2) Space complexity: O(n) Code
tonitannoury01
NORMAL
2024-12-26T20:15:51.583193+00:00
2024-12-26T20:15:51.583193+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n**2) - Space complexity: O(n) # Code ```javascript [] /** * @param {string[]} words * @param {number[]} groups * @return {string[]} */ var getWordsInLongestSubsequence = function (words, groups) { let n = words.length; let dp = Array(n).fill([]); for (let i = 0; i < n; i++) { dp[i] = [words[i]]; } for (let w = 1; w < words.length; w++) { for (let w1 = 0; w1 < w; w1++) { if (groups[w] !== groups[w1] && words[w].length === words[w1].length) { let p1 = 0; let p2 = 0; let diff = 0; let targetLen = words[w].length; while (p1 < targetLen) { if (words[w][p1] !== words[w1][p2]) { diff++; } p1++; p2++; } if (diff <= 1) { if (dp[w].length < 1 + dp[w1].length) { dp[w] = [...dp[w1], words[w]]; } } } } } let res = []; for (let d of dp) { if (d.length > res.length) { res = d; } } return res; }; ```
0
0
['JavaScript']
0
longest-unequal-adjacent-groups-subsequence-ii
Easy Graph+DFS
easy-graphdfs-by-arcanex-05zr
Intuition Initial Realization: Need to find longest valid chain of words. Reminds of longest path problem. Key Insight: We can model this as a graph where:
arcanex
NORMAL
2024-12-21T10:20:18.016298+00:00
2024-12-21T10:20:18.016298+00:00
6
false
# Intuition - Initial Realization: Need to find longest valid chain of words. Reminds of longest path problem. - Key Insight: We can model this as a graph where: - Nodes = words - Edge exists if words have: - Same length - Hamming distance ≤ 1 - Different groups - This transforms problem into "longest path in DAG" which is basically DFS while storing the nodes in the path. # Complexity - Time complexity: O(n^2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n^2) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def getWordsInLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]: if len(words) == 1: return words @cache def dist(w1, w2): d = 0 i = 0 while i < len(w1) and i < len(w2): if w1[i] != w2[i]: d += 1 i += 1 if i < len(w1): d += len(w1) - len(w2) elif i < len(w2): d += len(w2) - len(w1) return d adj = defaultdict(list) for i in range(len(words)): for j in range(i+1, len(words)): if len(words[i]) == len(words[j]) and dist(words[i], words[j]) <= 1 and groups[i] != groups[j]: adj[words[i]].append(words[j]) @cache def dfs(word): if word not in adj: return [word] res = [] for w in adj[word]: r = dfs(w) if len(r) > len(res): res = r return [word] + res res = [] for w in words: r = dfs(w) if len(r) > len(res): res = r return res ```
0
0
['Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
Python consice 6-line DP
python-consice-6-line-dp-by-dsapelnikov-vd4w
Approach\nThe DP pattern is similar to the one in the longest increasing subsequence. But we collect actual words instead of subsequence lengths.\n\n# Complexit
dsapelnikov
NORMAL
2024-11-13T10:12:52.540927+00:00
2024-11-13T10:14:20.248813+00:00
4
false
# Approach\nThe DP pattern is similar to the one in the longest increasing subsequence. But we collect actual words instead of subsequence lengths.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n^2)$$\n\n# Code\n```python3 []\nclass Solution:\n def getWordsInLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]:\n dp = [[w] for w in words]\n for i in range(len(dp)):\n for j in range(i):\n if (groups[i] != groups[j] and \n len(words[i]) == len(words[j]) and \n sum(c1 != c2 for c1, c2 in zip(words[i], words[j])) == 1):\n\n dp[i] = max(dp[i], dp[j] + words[i:i+1], key=len)\n return max(dp, key=len)\n\n \n\n\n\n```
0
0
['Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
C++ O(n*n), dp
c-onn-dp-by-cx3129-0dqu
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
cx3129
NORMAL
2024-09-24T01:28:23.874524+00:00
2024-09-24T01:28:56.572205+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<string> getWordsInLongestSubsequence(vector<string>& words,vector<int>& groups) {\n int n = int(words.size());\n globalWords = words;\n unordered_map<int /*word length*/, pair<vector<int /*index*/>, vector<int>>> m;\n for (int i = 0; i < n; ++i) \n m[words[i].size()].first.push_back(i), m[words[i].size()].second.push_back(groups[i]);\n\n int maxLen = 0;\n vector<int> r,r1;\n for (auto& p : m) {\n r1 = findLongest(p.second.first, p.second.second);\n if (r1.size() > maxLen) { maxLen = r1.size(); r = r1;}\n }\n\n vector<string> rs;\n for (auto i : r) rs.push_back(globalWords[i]);\n return rs;\n }\n vector<string> globalWords;\n vector<int> findLongest(vector<int>& vs, vector<int>& gs) {\n int n = vs.size();\n struct NodeInfo { int maxLen = 1; int pre = -1; };\n\n vector<NodeInfo> infos(n);\n int maxLenOverall = -1;\n int indexLast = -1;\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n int indexi = vs[i], indexj = vs[j];\n if (gs[i] != gs[j] && hamming(globalWords[indexi], globalWords[indexj]) == 1) {\n if (infos[i].maxLen + 1 > infos[j].maxLen) {\n infos[j].maxLen = infos[i].maxLen + 1;\n infos[j].pre = i;\n }\n }\n }\n\n if (infos[i].maxLen > maxLenOverall) { maxLenOverall = infos[i].maxLen; indexLast = i; }\n }\n\n vector<int> path; // find out path\n for (int index = indexLast; index >= 0; index = infos[index].pre) path.insert(path.begin(), vs[index]);\n return path;\n }\n\n int hamming(const string& a, const string& b) {\n int d = 0;\n for (int i = 0, n = int(a.size()); i < n; ++i) d += a[i] != b[i];\n return d;\n }\n};\n```
0
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
DP
dp-by-abdelrahman-adel7-9905
\npublic class Solution {\n List<string> result = new();\n int[,] dp = null;\n\n public IList<string> GetWordsInLongestSubsequence(string[] words, int[
Abdelrahman-Adel7
NORMAL
2024-09-07T00:57:10.519295+00:00
2024-09-07T00:57:10.519320+00:00
0
false
```\npublic class Solution {\n List<string> result = new();\n int[,] dp = null;\n\n public IList<string> GetWordsInLongestSubsequence(string[] words, int[] groups)\n {\n dp = new int[words.Length + 1, words.Length + 1];\n for (int j = 0; j <= groups.Length; j++)\n {\n for (int k = 0; k <= groups.Length; k++)\n {\n dp[j, k] = -1;\n }\n }\n\n int res = Solve(0, words.Length, words, groups);\n Console.WriteLine(res);\n GetLongestSub(0, words.Length, res, words, groups);\n return result;\n }\n public int Solve(int i, int prevIndex, string[] words, int[] groups)\n {\n if (i == words.Length)\n return dp[i, prevIndex] = 0;\n if (dp[i, prevIndex] != -1)\n return dp[i, prevIndex];\n int result = 0;\n if (prevIndex == groups.Length || (groups[i] != groups[prevIndex] && IsHammingDistance(words[i], words[prevIndex])))\n result = Solve(i + 1, i, words, groups) + 1;\n\n return dp[i, prevIndex] = Math.Max(result, Solve(i + 1, prevIndex, words, groups));\n }\n\n public void GetLongestSub(int i, int prevIndex, int longestSub, string[] words, int[] groups)\n {\n if (i == words.Length)\n return;\n if (dp[i + 1, i] == longestSub - 1 && (prevIndex == groups.Length || (groups[i] != groups[prevIndex] && IsHammingDistance(words[i], words[prevIndex]))))\n {\n result.Add(words[i]);\n GetLongestSub(i + 1, i, longestSub - 1, words, groups);\n }\n else\n GetLongestSub(i + 1, prevIndex, longestSub, words, groups);\n\n }\n\n public bool IsHammingDistance(string word1, string word2)\n {\n bool diff = false;\n if (word1.Length != word2.Length)\n return false;\n for (int i = 0; i < word1.Length; i++)\n {\n if (word1[i] != word2[i])\n {\n if (diff)\n return false;\n diff = true;\n }\n\n }\n return true;\n }\n\n}``\n```
0
0
[]
0
longest-unequal-adjacent-groups-subsequence-ii
Easy Iterative Dp Solution
easy-iterative-dp-solution-by-kvivekcode-mynz
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
kvivekcodes
NORMAL
2024-08-29T04:06:48.758540+00:00
2024-08-29T04:06:48.758566+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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```cpp []\nclass Solution {\npublic:\n vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {\n int n = words.size();\n if(n == 1) return {words[0]};\n int dis[n][n];\n for(int i = 0; i < n; i++){\n for(int j = i; j < n; j++){\n int cnt = 0;\n if(words[i].size() != words[j].size()){\n dis[i][j] = 0;\n continue;\n }\n for(int k = 0; k < words[i].size(); k++){\n if(words[i][k] != words[j][k]) cnt++;\n }\n if(cnt != 1 || groups[i] == groups[j]) dis[i][j] = 0;\n else dis[i][j] = 1;\n }\n }\n\n\n\n vector<int > dp(n, 1);\n vector<int > cnt(n, -1);\n\n int len = 0;\n int ind;\n for(int i = 0; i < n; i++){\n for(int j = 0; j < i; j++){\n if(dis[j][i]){\n if(dp[j] + 1 > dp[i]){\n dp[i] = dp[j] + 1;\n cnt[i] = j;\n }\n }\n if(dp[i] > len){\n len = dp[i];\n ind = i;\n }\n }\n }\n vector<string> ans;\n int k = ind;\n while(k != -1){\n ans.push_back(words[k]);\n k = cnt[k];\n }\n reverse(ans.begin(), ans.end());\n\n return ans;\n }\n};\n```
0
0
['Array', 'String', 'Dynamic Programming', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
c++ beginner friendly dp
c-beginner-friendly-dp-by-pb_matrix-wdfw
\nclass Solution {\npublic:\n bool fn(vector<string>&v,int i,int j){\n string s1=v[i],s2=v[j];\n int ans=0;\n for(int k=0;k<s1.size();k+
pb_matrix
NORMAL
2024-08-28T11:42:20.013030+00:00
2024-08-28T11:42:20.013055+00:00
0
false
```\nclass Solution {\npublic:\n bool fn(vector<string>&v,int i,int j){\n string s1=v[i],s2=v[j];\n int ans=0;\n for(int k=0;k<s1.size();k++) ans+=(s1[k]!=s2[k]);\n return s1.size()==s2.size() && ans==1;\n }\n vector<string> getWordsInLongestSubsequence(vector<string>&v,vector<int>&s) {\n vector<int>dp(1001,1); \n vector<string>ans;\n int n=v.size();\n if(n==1) {ans.push_back(v[0]); return ans;}\n vector<int>parent(n);\n for(int j=0;j<n;j++) parent[j]=j;\n for(int j=1;j<n;j++){\n for(int k=j-1;k>=0;k--){\n if(fn(v,j,k) && s[j]!=s[k] && dp[j]<dp[k]+1)\n\t\t\t dp[j]=dp[k]+1,parent[j]=k;\n }\n }\n int l=0,len=1;\n for(int j=0;j<n;j++){\n if(len<dp[j]) len=dp[j],l=j;\n }\n while(parent[l]!=l){\n ans.push_back(v[l]);\n l=parent[l]; \n }\n ans.push_back(v[l]);\n reverse(ans.begin(),ans.end());\n return ans; \n }\n};\n```
0
0
['Dynamic Programming', 'C']
0
longest-unequal-adjacent-groups-subsequence-ii
Current Fastest C# Solution - Dynamic Programming
current-fastest-c-solution-dynamic-progr-jmmo
Intuition\nFor each word, find all subsequences it can connect to, then connect the word to the longest out of all candidate subsequences. The returned value wi
theuncleofalex
NORMAL
2024-08-03T19:38:14.522961+00:00
2024-08-03T19:38:14.522993+00:00
0
false
# Intuition\nFor each word, find all subsequences it can connect to, then connect the word to the longest out of all candidate subsequences. The returned value will be the longest subsequence.\n\n# Approach\nCreate an array of backpointers representing each node\'s connected subsequence. Also create an array of lengths representing each subsequence\'s current length.\n\nFor each word, iterate over all previous words. You must check each previous word because each previous word has the potential to be included in the longest subsequence. If the current word connects to a previous word, it is a candidate subsequence. If the candidate subsequence\'s length is larger than the current longest candidate subsequence length, set it is as the new longest candidate.\n\nIf no words are connected to the current word, it is the start of a new subsequence. Initialize its backpointer and backLength.\n\nAt the longest subsequence, iterate backwords over each backpointer and add each word to a return list.\n\n# Complexity\n- Time complexity:\nFor loop to iterate over each character in a word- length m\nNested inside for loop to iterate over each previous word - length n (worst case)\nNested inside for loop to iterate over each word - length n\nO(n<sup>2</sup>m)\n\n- Space complexity:\nBackpointer array length: n\nBackLength array length: n\nReturn array length: n (worst case)\nO(n)\n\n# Code\n```\npublic class Solution {\n public IList<string> GetWordsInLongestSubsequence(string[] words, int[] groups) {\n int n = words.Length;\n int[] backPointers = new int[n];\n int[] backLengths = new int[n];\n\n int bestPointer = -1;\n int bestLen = 0;\n for (int i = 0; i < n; ++i) {\n string curWord = words[i];\n int curGroup = groups[i];\n int curLen = 0;\n bool didConnect = false;\n for (int j = i-1; j >= 0; --j) {\n int backLen = backLengths[j];\n //Optimization: ignore subsequences shorter than the current longest connected\n if (backLen < curLen) continue;\n bool adj = Adjacent(words[j], curWord, groups[j], curGroup);\n if (adj)\n {\n backPointers[i] = j;\n curLen = backLengths[j] + 1;\n backLengths[i] = curLen;\n didConnect = true;\n }\n }\n\n if (!didConnect)\n {\n backLengths[i] = 1;\n backPointers[i] = i;\n }\n\n if (backLengths[i] > bestLen)\n {\n bestLen = backLengths[i];\n bestPointer = i;\n }\n }\n\n var ret = new List<string>();\n int prevB = bestPointer;\n for (int i = 0; i < 100000; ++i)\n {\n ret.Add(words[bestPointer]);\n bestPointer = backPointers[bestPointer];\n if (prevB == bestPointer) break;\n prevB = bestPointer;\n }\n\n ret.Reverse();\n return ret;\n }\n\n public static bool Adjacent(string prev, string cur, int prevGroup, int curGroup)\n {\n //Optimization: check group connectivity and string lengths before computing Hamming distance\n if (prevGroup == curGroup || prev.Length != cur.Length) return false;\n int hamDist = 0;\n for (int i = 0; i < prev.Length; ++i)\n {\n if (prev[i] != cur[i])\n {\n hamDist++;\n if (hamDist > 1) return false;\n }\n }\n \n return hamDist == 1;\n }\n}\n```
0
0
['C#']
0
longest-unequal-adjacent-groups-subsequence-ii
Simple C++ Solution | DP | Tabulation
simple-c-solution-dp-tabulation-by-rj_99-gsn5
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
rj_9999
NORMAL
2024-07-06T09:52:23.420779+00:00
2024-07-06T09:52:23.420815+00:00
14
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 {\npublic:\nint hope(int index,int prev,vector<string>& words, vector<int>& groups){\n if(index>=words.size())return 0;\n int pick=-1e9;\n int not_pick=-1e9;\n if(prev==-1)pick=1+hope(index+1,index,words,groups);\n if(prev!=-1){\n int g=groups[prev];\n int lenp=words[prev].length();\n int lenc=words[index].length();\n if(lenc==lenp && g!=groups[index]){\n string w=words[prev];\n int cnt=0;\n for(int i=0;i<lenp;i++){\n if(words[index][i]!=words[prev][i])cnt=cnt+1;\n }\n if(cnt==1)pick=1+hope(index+1,index,words,groups);\n }\n }\n not_pick=hope(index+1,prev,words,groups);\n return max(pick,not_pick);\n}\n vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {\n if(words.size()==1){\n vector<string>a;\n a.push_back(words[0]);\n return a;\n }\n vector<int>dp(words.size()+1,1);\n vector<int>note(words.size()+1,-1);\n //int ans=hope(0,-1,words,groups);\n //string s=to_string(ans);\n //vector<string>a;\n //a.push_back(s);\n for(int i=1;i<=words.size();i++){\n for(int j=1;j<i;j++){\n string currw=words[i-1];\n string prevw=words[j-1];\n int gc=groups[i-1];\n int gp=groups[j-1];\n int lenc=words[i-1].length();\n int lenp=words[j-1].length();\n int cnt=0;\n if(gp!=gc && lenc==lenp){\n for(int k=0;k<lenp;k++){\n if(currw[k]!=prevw[k])cnt=cnt+1;\n }\n if(cnt==1){\n if(dp[i]<1+dp[j]){\n dp[i]=max(dp[i],1+dp[j]);\n note[i]=j;\n }\n \n }\n }\n }\n }\n int ans=-1e9;\n int st=0;\n for(int i=0;i<dp.size();i++){\n if(ans<dp[i]){\n ans=dp[i];\n st=i;\n }\n }\n vector<string>answer;\n if(st==0){\n answer.push_back(words[st]);\n return answer;\n }\n while(st!=-1){\n answer.push_back(words[st-1]);\n st=note[st];\n }\n reverse(answer.begin(),answer.end());\n return answer;\n }\n};\n```
0
0
['Array', 'String', 'Dynamic Programming', 'Memoization', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
JAVA SOLUTION
java-solution-by-danish_jamil-mkyf
Intuition\n\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Tim
Danish_Jamil
NORMAL
2024-06-29T06:10:20.770860+00:00
2024-06-29T06:10:20.770890+00:00
8
false
# Intuition\n![images.jfif](https://assets.leetcode.com/users/images/040dda8a-42dd-4a8e-b06f-b1342f86f45d_1719641416.6305838.jpeg)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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```\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Solution {\n \n public List<String> getWordsInLongestSubsequence(String[] words, int[] groups) {\n int n = words.length;\n // DP array to store the length of the longest valid subsequence ending at index i\n int[] dp = new int[n];\n // To track the previous index in the longest subsequence\n int[] prev = new int[n];\n \n // Initialize DP and prev arrays\n for (int i = 0; i < n; i++) {\n dp[i] = 1;\n prev[i] = -1;\n }\n \n int maxLength = 1;\n int endIndex = 0;\n \n // Compute the DP array\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < i; j++) {\n if (groups[i] != groups[j] && words[i].length() == words[j].length() && hammingDistance(words[i], words[j]) == 1) {\n if (dp[i] < dp[j] + 1) {\n dp[i] = dp[j] + 1;\n prev[i] = j;\n }\n }\n }\n if (dp[i] > maxLength) {\n maxLength = dp[i];\n endIndex = i;\n }\n }\n \n // Retrieve the sequence by backtracking\n List<String> result = new ArrayList<>();\n int index = endIndex;\n while (index != -1) {\n result.add(0, words[index]);\n index = prev[index];\n }\n \n return result;\n }\n\n private int hammingDistance(String s1, String s2) {\n int distance = 0;\n for (int i = 0; i < s1.length(); i++) {\n if (s1.charAt(i) != s2.charAt(i)) {\n distance++;\n }\n }\n return distance;\n }\n \n public static void main(String[] args) {\n Solution solution = new Solution();\n \n String[] words1 = {"bab", "dab", "cab"};\n int[] groups1 = {1, 2, 2};\n System.out.println(solution.getWordsInLongestSubsequence(words1, groups1)); // Output: [bab, cab] or [bab, dab]\n\n String[] words2 = {"a", "b", "c", "d"};\n int[] groups2 = {1, 2, 3, 4};\n System.out.println(solution.getWordsInLongestSubsequence(words2, groups2)); // Output: [a, b, c, d]\n }\n}\n\n```
0
0
['Java']
0
longest-unequal-adjacent-groups-subsequence-ii
C++ | DP | LIS
c-dp-lis-by-mrchromatic-t0he
Code\n\nclass Solution {\npublic:\n int hamming_distance(string s1,string s2){\n int ct=0;\n for(int i=0;i<s1.size();i++){\n if(s1[i
MrChromatic
NORMAL
2024-06-26T12:34:18.863663+00:00
2024-06-26T12:34:18.863697+00:00
5
false
# Code\n```\nclass Solution {\npublic:\n int hamming_distance(string s1,string s2){\n int ct=0;\n for(int i=0;i<s1.size();i++){\n if(s1[i]!=s2[i])\n ct++;\n if(ct==2)\n return 2;\n }\n return ct;\n }\n vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {\n vector<pair<int,int>> dp(words.size(),{1,-1});\n dp[0]={1,-1};\n for(int i=1;i<words.size();i++){\n for(int j=i-1;j>=0;j--){\n if(words[i].size()==words[j].size() and groups[i]!=groups[j]){\n int ham_dist=hamming_distance(words[i],words[j]);\n if(ham_dist==1)\n if(dp[i].first<dp[j].first+1) \n dp[i]={dp[j].first+1,j};\n }\n }\n }\n vector<string> ans;\n int ind=max_element(dp.begin(),dp.end())-dp.begin();\n while(ind!=-1){\n ans.push_back(words[ind]);\n ind=dp[ind].second;\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};\n```
0
0
['Dynamic Programming', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
USING C++ || LIS EASY KEEP PAR OF EACH INDEX
using-c-lis-easy-keep-par-of-each-index-znzpb
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
hmaan
NORMAL
2024-06-05T12:17:47.942058+00:00
2024-06-05T12:17:47.942092+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 {\npublic:\n bool hamming(int i, int j,vector<string>&words){\n if(words[i].size()!=words[j].size())return false;\n int hamm=0;\n int n=words[i].size();\n for(int k=0;k<n;k++){\n if(words[i][k]!=words[j][k])hamm++;\n if(hamm>1)return false;\n }\n return hamm==1;\n }\n vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {\n int n = words.size();\n vector<int> dp(n, 1); \n vector<int> par(n, -1); \n int maxlen = 1; \n int lastindex = 0; \n \n for (int i = 1; i < n; i++) {\n for (int j = 0; j < i; j++) {\n if (groups[i] != groups[j] && dp[j] + 1 > dp[i] && hamming(i,j,words)) {\n dp[i] = dp[j] + 1;\n par[i] = j;\n }\n }\n if (dp[i] > maxlen) {\n maxlen = dp[i];\n lastindex = i;\n }\n }\n\n vector<string> ans;\n for (int i = lastindex; i != -1; i = par[i]) {\n ans.push_back(words[i]);\n }\n reverse(ans.begin(), ans.end());\n\n return ans;\n }\n};\n\n```
0
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
LIS Bottom-up solution
lis-bottom-up-solution-by-deshmukhrao-hnuu
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
DeshmukhRao
NORMAL
2024-05-30T13:09:18.937061+00:00
2024-05-30T13:09:18.937091+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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```\n\nclass Solution {\npublic:\n vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {\n int n = words.size();\n vector<int> t(n, 1);\n vector<int> prev_idx(n, -1);\n int last_chosen_index = 0;\n int maxL = 1;\n\n auto hammingDistance = [](const string &a, const string &b) {\n int dist = 0;\n for(int i = 0; i < a.size(); ++i) {\n if(a[i] != b[i]) ++dist;\n }\n return dist;\n };\n\n for(int i = 1; i < n; ++i) {\n for(int j = 0; j < i; ++j) {\n if(groups[i] != groups[j] && words[i].length() == words[j].length() && hammingDistance(words[i], words[j]) == 1) {\n if(t[i] < t[j] + 1) {\n t[i] = t[j] + 1;\n prev_idx[i] = j;\n }\n }\n }\n if(t[i] > maxL) {\n maxL = t[i];\n last_chosen_index = i;\n }\n }\n\n vector<string> result;\n while(last_chosen_index >= 0) {\n result.push_back(words[last_chosen_index]);\n last_chosen_index = prev_idx[last_chosen_index];\n }\n\n reverse(result.begin(), result.end()); // Reverse to get the correct order\n return result;\n }\n};\n\n```
0
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
Longest Unequal Adjacent Groups Subsequence - ii || JavaScript || 100% Beats
longest-unequal-adjacent-groups-subseque-b3iw
Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve the problem of finding the longest subsequence of words where each word is in
user4609eh
NORMAL
2024-05-18T12:40:53.469591+00:00
2024-05-18T12:40:53.469622+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve the problem of finding the longest subsequence of words where each word is in a different group and the Hamming distance between consecutive words in the subsequence is exactly 1, we can use dynamic programming. The idea is to build up the longest valid subsequence ending at each word and keep track of the maximum length subsequence.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitialization:\n\nWe initialize a 2D array dp where dp[i] stores the longest subsequence ending at words[i].\nWe also keep track of maxLen to store the length of the longest subsequence found and maxIndex to store the index of the word where this subsequence ends.\nDynamic Programming:\n\nFor each word words[i], we start with a subsequence containing just that word.\nWe then iterate over all previous words words[j] to check if:\ngroups[i] is different from groups[j].\nThe lengths of words[i] and words[j] are the same.\nThe Hamming distance between words[i] and words[j] is exactly 1.\nAdding words[i] to the subsequence ending at words[j] results in a longer subsequence than the current one ending at words[i].\nIf all conditions are met, we update dp[i] to be the subsequence ending at words[j] extended by words[i].\nResult Extraction:\n\nAfter processing all words, dp[maxIndex] contains the longest subsequence found.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe outer loop runs n times (for each word).\nThe inner loop runs O(n) times (for each previous word).\nThe Hamming distance calculation takes O(L) time where L is the length of the words.\nOverall time complexity: **O(n^2 * L)**.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe dp array uses **O(n * L)** space to store the subsequences.\nOverall space complexity: **O(n * L)**.\n\n# Code\n```\n/**\n * @param {string[]} words\n * @param {number[]} groups\n * @return {string[]}\n */\nvar getWordsInLongestSubsequence = function(words, groups) {\n const n = words.length;\n const dp = Array.from({length: n}, () => []);\n let maxLen = 0;\n let maxIndex = -1;\n\n for (let i = 0; i < n; i++) {\n dp[i].push(words[i]);\n \n for (let j = 0; j < i; j++) {\n if (groups[i] !== groups[j] && words[i].length === words[j].length && hammingDistance(words[i], words[j]) === 1 && dp[j].length + 1 > dp[i].length) {\n dp[i] = [...dp[j], words[i]];\n }\n }\n \n if (dp[i].length > maxLen) {\n maxLen = dp[i].length;\n maxIndex = i;\n }\n }\n\n return dp[maxIndex];\n};\n\nfunction hammingDistance(word1, word2) {\n let distance = 0;\n for (let i = 0; i < word1.length; i++) {\n if (word1[i] !== word2[i]) {\n distance++;\n }\n }\n return distance;\n}\n```
0
0
['JavaScript']
0
longest-unequal-adjacent-groups-subsequence-ii
Can anyone help to solve my confusion? Thank you very much
can-anyone-help-to-solve-my-confusion-th-e2hj
The question states that "For adjacent indices in the subsequence, their corresponding groups are unequal, i.e., groups[ij] != groups[ij+1], for each j where 0
adamchen564
NORMAL
2024-05-04T15:16:36.279370+00:00
2024-05-04T15:19:45.318380+00:00
28
false
The question states that "For adjacent indices in the subsequence, their corresponding groups are unequal, i.e., groups[ij] != groups[ij+1], for each j where 0 < j + 1 < k.", my understanding is that the solution subsequences\' groups can be \'1,2,3,1,2,3\', but many of the solutions that I have seen (that pass all testcases) seem to assume that the solution subsequences\' groups are in increasing order (e.g. 1,2,3). I do not agree with these solutions as I think that the solution subsequences\' groups do not have to be in strict increasing order.\n\nI found a solution that passed all testcases and feed it into ChatGPT,ChatGPT says that "the solution looks forward and doesn\'t consider revisiting previously used groups after covering a sequence of other groups."\n\nI am a beginner and I may have misunderstood the question itself. Can anyone help to solve my confusion? Thank you very much
0
0
['Swift', 'C', 'Python', 'Java', 'Go', 'Python3', 'Ruby', 'JavaScript', 'C#', 'Bash']
0
longest-unequal-adjacent-groups-subsequence-ii
c++ solution
c-solution-by-dilipsuthar60-66uz
\nclass Solution {\npublic:\n bool hammingDistance(string&s1,string&s2)\n {\n if(s1.size()!=s2.size()) return false;\n int count=0;\n
dilipsuthar17
NORMAL
2024-04-29T17:27:24.107743+00:00
2024-04-29T17:27:24.107776+00:00
1
false
```\nclass Solution {\npublic:\n bool hammingDistance(string&s1,string&s2)\n {\n if(s1.size()!=s2.size()) return false;\n int count=0;\n for(int i=0;i<s1.size();i++)\n {\n if(s1[i]!=s2[i]) count++;\n if(count>1) return false;\n }\n return true;\n }\n vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {\n int n=words.size();\n int maxElement=0;\n vector<int>dp(n,1);\n vector<int>parent(n,-1);\n \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<i;j++)\n {\n if(hammingDistance(words[i],words[j])&&groups[i]!=groups[j]&&dp[j]+1>dp[i])\n {\n dp[i]=dp[j]+1;\n parent[i]=j;\n }\n }\n maxElement=max(maxElement,(int)dp[i]);\n }\n int maxIndex=-1;\n for(int i=0;i<n;i++)\n {\n if(maxElement==dp[i])\n {\n maxIndex=i;\n }\n }\n vector<string>result;\n while(maxIndex!=-1)\n {\n result.push_back(words[maxIndex]);\n maxIndex=parent[maxIndex];\n }\n reverse(result.begin(),result.end());\n return result;\n }\n};\n```
0
0
['Dynamic Programming', 'C', 'C++']
0
longest-unequal-adjacent-groups-subsequence-ii
Python (Simple DP)
python-simple-dp-by-rnotappl-x1kr
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
rnotappl
NORMAL
2024-04-09T15:58:55.982399+00:00
2024-04-09T15:58:55.982457+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 getWordsInLongestSubsequence(self, words, groups):\n n = len(words)\n\n def function(s,t):\n return sum(i!=j for i,j in zip(s,t))\n\n @lru_cache(None)\n def dfs(i):\n if i >= n:\n return 0, []\n\n ans, max_len = [], 1\n\n for j in range(i+1,n):\n if len(words[i]) == len(words[j]) and function(words[i],words[j]) == 1 and groups[i] != groups[j]:\n if max_len < 1+dfs(j)[0]:\n max_len = 1+dfs(j)[0]\n ans = dfs(j)[1]\n\n return max_len, [words[i]] + ans\n\n return max([dfs(i)[1] for i in range(n)],key=len)\n```
0
0
['Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
Beats 100.00% of users with Java
beats-10000-of-users-with-java-by-raheel-7hok
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
raheels
NORMAL
2024-04-09T09:13:14.757268+00:00
2024-04-09T09:13:14.757292+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 public List<String> getWordsInLongestSubsequence(String[] words, int[] groups) {\n int[] dp = new int[words.length];\n int[] next = new int[words.length];\n\n dp[words.length - 1] = 1;\n next[words.length - 1] = -1;\n\n int maxLen = 1;\n int maxIndex = 0;\n\n\n for (int i = words.length - 2; i >= 0; i--) {\n dp[i] = 1;\n next[i] = -1;\n for (int j = i + 1; j < words.length; j++) {\n if (dp[j] + 1 > dp[i] && isHummingDistanceOne(words[i], words[j], groups[i], groups[j])) {\n dp[i] = dp[j] + 1;\n next[i] = j;\n }\n }\n\n if (dp[i] > maxLen) {\n maxLen = dp[i];\n maxIndex = i;\n }\n }\n\n List<String> result = new ArrayList<>();\n\n while (maxIndex >= 0) {\n result.add(words[maxIndex]);\n maxIndex = next[maxIndex];\n }\n\n return result;\n }\n\n boolean isHummingDistanceOne(String word1, String word2, int g1, int g2) {\n if (g1 == g2) return false;\n if (word1.length() != word2.length()) return false;\n int count = 0;\n for (int i = 0; i < word1.length(); i++) {\n if (word1.charAt(i) != word2.charAt(i)) {\n if (++count > 1) return false;\n }\n }\n\n return count == 1;\n }\n}\n```
0
0
['Java']
0
longest-unequal-adjacent-groups-subsequence-ii
O(N^2) LIS DP with Erlang
on2-lis-dp-with-erlang-by-metaphysicalis-f1gw
Approach\n Describe your approach to solving the problem. \nThis problem can be easily solved with the straightforward $O(N^2)$ algorithm for finding the longes
metaphysicalist
NORMAL
2024-03-23T09:30:09.111665+00:00
2024-03-23T09:30:09.111701+00:00
4
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nThis problem can be easily solved with the straightforward $O(N^2)$ algorithm for finding the longest increasing subsequence. I solve this problem in Erlang with recursion for finding the solution as well. No additional backtracking is required to construct the answer. Top-down DP (memoization) is used because of the nature of functional programming. \n\n# Complexity\n- Time complexity: $O(N^2)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(N)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n-spec get_words_in_longest_subsequence(Words :: [unicode:unicode_binary()], Groups :: [integer()]) -> [unicode:unicode_binary()].\nget_words_in_longest_subsequence(Words, Groups) -> \n erlang:erase(), \n {_, R} = best([], -1, [binary_to_list(W) || W <- Words], Groups, 0), \n R.\n\nsolve([], [], I) -> {0, []};\nsolve([W|Words], [G|Groups], I) -> \n case erlang:get({\'solve\', I}) of\n R when is_tuple(R) -> R;\n _ -> \n {L, Ans} = best(W, G, Words, Groups, I+1),\n R = {L + 1, [list_to_binary(W)|Ans]},\n erlang:put({\'solve\', I}, R),\n R\n end.\n\nbest(W, G, [Word|Words], [Group|Groups], I) -> \n case check(W, Word, G, Group) of\n true -> max(solve([Word|Words], [Group|Groups], I), best(W, G, Words, Groups, I+1));\n false -> best(W, G, Words, Groups, I+1)\n end;\nbest(W, G, [], [], I) -> {0, []}.\n\ncheck([], _, -1, _) -> true;\ncheck(W, Word, G, Group) when G == Group -> false;\ncheck([], [H2|T2], _, _) -> false;\ncheck([H1|T1], [], _, _) -> false;\ncheck([H1|T1], [H2|T2], G, Group) when H1 == H2 -> check(T1, T2, G, Group);\ncheck([H1|T1], [H2|T2], _, _) -> T1 == T2.\n```
0
0
['Dynamic Programming', 'Recursion', 'Memoization', 'Erlang']
0
longest-unequal-adjacent-groups-subsequence-ii
C++
c-by-ayush_gupta4-is03
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ayush_gupta4
NORMAL
2024-03-19T12:41:55.191283+00:00
2024-03-19T12:41:55.191314+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 {\npublic:\n bool f(string& a, string& b) {\n int ans = 0;\n for (int i = 0; i < a.size(); i++) {\n if (a[i] != b[i])\n ans++;\n }\n return ans == 1;\n }\n\n vector<string> getWordsInLongestSubsequence(vector<string>& a, vector<int>& groups) {\n int n = a.size(), i, prev, maxi = 1;\n vector<vector<string>> dp(n);\n vector<string> ans;\n for (int i = 0; i < n; i++) dp[i].push_back(a[i]);\n\n for (int i = 0; i < n; i++) {\n for (int prev = 0; prev < i; prev++) {\n if ((groups[i] != groups[prev]) && (a[i].size() == a[prev].size()) && (f(a[i], a[prev]))) {\n if (dp[prev].size() + 1 > dp[i].size()) {\n dp[i] = dp[prev];\n dp[i].push_back(a[i]);\n maxi = max(maxi, int(dp[i].size()));\n }\n }\n }\n }\n for (i = 0; i < n; i++) {\n if (dp[i].size() == maxi) {\n ans = dp[i];\n break;\n }\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
C++/Python, dynamic programming solution with explanation
cpython-dynamic-programming-solution-wit-t82f
dp[i][0] is the max length of sequence whose last element is words[i].\ndp[i][1] is the second to last element of the maximum length sequence, the last one is w
shun6096tw
NORMAL
2024-03-13T08:06:24.088668+00:00
2024-03-13T08:07:35.709685+00:00
7
false
dp[i][0] is the max length of sequence whose last element is words[i].\ndp[i][1] is the second to last element of the maximum length sequence, the last one is words[i].\n\nfor each j in [0, i-1],\nif words[j] and words[i]\'s distance is 1 and both length are the same and dp[j][0] + 1 > dp[i][0],\ndp[i] = (dp[j][0] + 1, j)\n\nand find the last element of the sequence with max length and construct answer.\n\ntc is O(n^2 * m), sc is O(n * m + n) including answer.\n\n### python\n```python\nclass Solution:\n def getWordsInLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]:\n \n def eq(x, y):\n if len(x) != len(y): return False\n return sum(ch1 != ch2 for ch1, ch2 in zip(x, y)) == 1\n \n size = len(words)\n dp = [(1, -1)] * size\n for i in range(1, size):\n for j in range(i):\n if groups[i] != groups[j] and eq(words[i], words[j]):\n tmp = (dp[j][0] + 1, j)\n dp[i] = max(dp[i], tmp, key=lambda x: x[0])\n cur = max(range(size), key=lambda x: dp[x][0])\n ans = []\n while cur != -1:\n ans.append(words[cur])\n cur = dp[cur][1]\n return ans[::-1]\n```\n### c++\n```cpp\nclass Solution {\npublic:\n vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {\n int size = words.size();\n vector<vector<int>> dp (size, vector<int>{1, -1});\n auto eq = [] (string& x, string& y) -> bool {\n if (x.size() != y.size()) return false;\n int z = 0;\n for (int i = 0; i < x.size(); i+=1)\n z += x[i] != y[i];\n return z == 1;\n };\n for (int i = 1; i < size; i+=1) {\n for (int j = 0; j < i; j+=1) {\n if (groups[i] != groups[j] && eq(words[i], words[j]) && 1 + dp[j][0] > dp[i][0]) {\n dp[i][0] = 1 + dp[j][0], dp[i][1] = j;\n }\n }\n }\n int cur = max_element(dp.begin(), dp.end(), [](auto& mx, auto& x){return x[0] > mx[0];}) - dp.begin();\n vector<string> ans;\n while (cur != -1) {\n ans.emplace_back(words[cur]);\n cur = dp[cur][1];\n }\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n```
0
0
['Dynamic Programming', 'C', 'Python']
0
longest-unequal-adjacent-groups-subsequence-ii
DP + Backtrack
dp-backtrack-by-cuiyong_cn-wfkt
Intuition\nCode explains better than words.\n\n# Code\n\nauto ham_dist(string const& s1, string const& s2)\n{\n if (s1.length() != s2.length()) {\n re
cuiyong_cn
NORMAL
2024-03-02T05:54:42.813235+00:00
2024-03-02T05:54:42.813262+00:00
5
false
# Intuition\nCode explains better than words.\n\n# Code\n```\nauto ham_dist(string const& s1, string const& s2)\n{\n if (s1.length() != s2.length()) {\n return -1;\n }\n\n int const n = s1.length();\n auto cnt = 0;\n\n for (auto i = 0; i < n; ++i) {\n if (s1[i] != s2[i]) {\n ++cnt;\n }\n }\n\n return cnt;\n}\n\nauto condition_met(vector<string> const& words, vector<int> const& groups, int i, int j)\n{\n return groups[i] != groups[j]\n && 1 == ham_dist(words[i], words[j]);\n}\n\nauto collect_sub(vector<string> const& words, vector<int> const& index, int p)\n{\n auto sub = vector<string>{};\n\n while (p >= 0) {\n sub.push_back(words[p]);\n p = index[p];\n }\n\n return sub;\n}\n\nclass Solution {\npublic:\n vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {\n int const n = words.size();\n auto dp = vector<int>(n, 0);\n auto index = vector<int>(n, -1);\n\n dp[0] = 1;\n\n for (auto i = 1; i < n; ++i) {\n auto max_j = -1;\n\n for (auto j = i - 1; j >= 0; --j) {\n auto new_len = condition_met(words, groups, i, j) ? dp[j] + 1 : -1;\n\n if (new_len > dp[i]) {\n max_j = j;\n dp[i] = new_len;\n }\n }\n\n index[i] = max_j;\n }\n\n auto max_it = max_element(dp.begin(), dp.end());\n auto max_len = dp[distance(dp.begin(), max_it)];\n auto ans = vector<string>{};\n\n for (auto i = 0; i < n; ++i) {\n if (max_len != dp[i]) {\n continue;\n }\n\n auto sub = collect_sub(words, index, i);\n\n if (sub.size() > ans.size()) {\n swap(sub, ans);\n }\n }\n\n reverse(ans.begin(), ans.end());\n\n return ans;\n }\n};\n```
0
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
🔥Java Solution || Dp (Concept : LIS)
java-solution-dp-concept-lis-by-neel_diy-rquw
\n\nclass Solution {\n public List<String> getWordsInLongestSubsequence(String[] words, int[] groups) {\n int n = words.length;\n\n int[] dp =
anjan_diyora
NORMAL
2024-02-26T16:59:57.171108+00:00
2024-02-26T16:59:57.171136+00:00
12
false
\n```\nclass Solution {\n public List<String> getWordsInLongestSubsequence(String[] words, int[] groups) {\n int n = words.length;\n\n int[] dp = new int[n];\n int[] hash = new int[n];\n \n Arrays.fill(dp, 1);\n\n int max = 1;\n int lastIndex = 0;\n for(int curr = 0; curr < n; curr++) {\n hash[curr] = curr;\n for(int prev = 0; prev < curr; prev++) {\n if(isSatisfiedCondition(words[prev], words[curr], groups, prev, curr) && dp[curr] < 1 + dp[prev]) {\n dp[curr] = 1 + dp[prev];\n hash[curr] = prev;\n } \n }\n\n if(dp[curr] > max) {\n max = dp[curr];\n lastIndex = curr;\n }\n }\n\n List<String> ans = new ArrayList<>();\n ans.add(words[lastIndex]);\n\n while(lastIndex != hash[lastIndex]) {\n lastIndex = hash[lastIndex];\n ans.add(words[lastIndex]);\n }\n\n Collections.reverse(ans);\n return ans;\n }\n\n private boolean isSatisfiedCondition(String str1, String str2, int[] groups, int prev, int curr) {\n return str1.length() == str2.length() && isHammingDistanceIsOne(str1, str2) && groups[prev] != groups[curr];\n }\n\n private boolean isHammingDistanceIsOne(String str1, String str2) {\n int n = str1.length();\n int count = 0;\n for(int i = 0; i < n; i++) {\n if(str1.charAt(i) != str2.charAt(i)) count++;\n if(count > 1) return false;\n }\n\n return count == 1 ? true : false;\n }\n}\n```
0
0
['Java']
0
longest-unequal-adjacent-groups-subsequence-ii
JAVA 100%, Simple Solution using Parent[]/Size[] array
java-100-simple-solution-using-parentsiz-bufv
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
meringueee
NORMAL
2024-02-21T23:57:58.111065+00:00
2024-02-21T23:57:58.111106+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 public List<String> getWordsInLongestSubsequence(String[] w, int[] g) {\n int[] p = new int[w.length];\n int[] s = new int[w.length];\n p[p.length-1]=p.length-1;\n s[s.length-1]=1;\n\n int max=1, mi=w.length-1;\n for(int i=w.length-2; i>=0; i--){\n p[i]=i; s[i]=1;\n for(int j=i+1; j<w.length; j++){\n if(s[i]>s[j]\n || !con(w, i, j, g))continue;\n p[i]=j; s[i]=s[j]+1;\n }\n if(max<s[i]){max=s[i]; mi=i;}\n }\n\n\n List<String> ret = new ArrayList<>();\n ret.add(w[mi]);\n while(p[mi]!=mi){\n mi=p[mi];\n ret.add(w[mi]);\n }\n return ret;\n }\n private boolean con(String[] w, int i, int j, int[] g){\n if(g[i]==g[j]||w[i].length()!=w[j].length()){\n return false;\n }\n boolean x=false; char c1,c2;\n for(int k=0; k<w[i].length(); k++){\n c1=w[i].charAt(k);\n c2=w[j].charAt(k);\n if(c1!=c2){\n if(x)return false;\n x=true;\n }\n }\n return x;\n }\n}\n```
0
0
['Java']
0
longest-unequal-adjacent-groups-subsequence-ii
Tabulation + Tracing
tabulation-tracing-by-piro_coder13-blt6
Approach\nTabulate the counts for each index when they satisfy the given conditions, then trace back the strings from maximum dp tabulated value.\n\n# Complexit
piro_coder13
NORMAL
2024-02-13T21:59:21.934559+00:00
2024-02-13T21:59:21.934591+00:00
1
false
# Approach\nTabulate the counts for each index when they satisfy the given conditions, then trace back the strings from maximum dp tabulated value.\n\n# Complexity\n- Time complexity:\nO(N*N*10)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<int> dp(n+1,1);\n // for(int i = 0;i<n;i++) cout<<words[i]<<" "<<groups[i]<<endl;\n for(int i = 0;i<n;i++){\n for(int j = i-1;j>=0;j--){\n int count = 0;\n if(words[i].size() != words[j].size()) continue;\n for(int p = 0;p<words[i].size();p++){\n if(words[i][p] != words[j][p]) count++;\n }\n if(count == 1 && (groups[i] != groups[j])){\n dp[i] = max(dp[i], 1+dp[j]);\n }\n }\n }\n int maxim = 0, maxInd = 0;\n for(int i = 0;i<n;i++){\n maxim = max(maxim,dp[i]);\n if(maxim == dp[i]) maxInd = i;\n }\n cout<<maxim<<endl;\n vector<string> ans;\n ans.push_back(words[maxInd]);\n maxim--;\n int j = maxInd;\n for(int i = maxInd-1;i>=0;i--){\n int count = 0;\n if(words[i].size() != words[j].size()) continue;\n for(int p = 0;p<words[i].size();p++){\n if(words[i][p] != words[j][p]) count++;\n }\n if((dp[i] == maxim) && (count == 1) && (groups[i] != groups[j])){\n j = i;\n maxim--;\n ans.push_back(words[i]);\n }\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};\n```
0
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
DP | O(NlogN) | Beats 92.91% of users with Python3
dp-onlogn-beats-9291-of-users-with-pytho-jjxu
Code\n\nclass Solution:\n def isWordSatisfied(self, word1: str, word2: str, dist=1):\n if len(word2) == len(word1):\n for c1, c2 in zip(wor
timo9madrid7
NORMAL
2024-01-26T11:53:09.633095+00:00
2024-01-26T11:53:09.633125+00:00
18
false
# Code\n```\nclass Solution:\n def isWordSatisfied(self, word1: str, word2: str, dist=1):\n if len(word2) == len(word1):\n for c1, c2 in zip(word2, word1):\n if c1 == c2:\n continue\n dist -= 1\n if dist < 0:\n return False\n return True\n\n return False\n\n def getWordsInLongestSubsequence(self, n: int, words: List[str], groups: List[int]) -> List[str]:\n if n == 1:\n return words\n\n // indices that meet the requiremetns\n // with the ending word words[i]\n dp = [[i] for i in range(n)] \n\n max_len_indices = []\n for i in range(1, n):\n for j in range(i):\n if len(dp[j]) >= len(dp[i]) \\ // the longer the better \n and groups[j] != groups[i] \\ // condition I\n and self.isWordSatisfied(words[j], words[i]): // condition II\n dp[i] = dp[j] + [i]\n \n if len(dp[i]) > len(max_len_indices):\n max_len_indices = dp[i].copy()\n \n return [words[idx] for idx in max_len_indices]\n```
0
0
['Python3']
0
longest-unequal-adjacent-groups-subsequence-ii
Koltin Easy solution
koltin-easy-solution-by-gideonrotich-nxwr
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
gideonrotich
NORMAL
2024-01-25T18:30:05.376422+00:00
2024-01-25T18:30:05.376446+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 fun getWordsInLongestSubsequence(n: Int, words: Array<String>, groups: IntArray): List<String> {\n var max = 1\n var end = 0\n val dp = IntArray(n)\n val last = IntArray(n) { -1 }\n val subs = mutableMapOf<Int, MutableList<Int>>()\n\n dp[0] = 1\n last[0] = -1\n subs[words[0].length] = mutableListOf(0)\n\n for (i in 1 until n) {\n val l = words[i].length\n dp[i] = 1\n last[i] = -1\n\n if (subs.containsKey(l)) {\n val temp = subs[l]!!\n for (j in temp) {\n if (groups[i] != groups[j] && distance(words, i, j) == 1) {\n if (dp[i] < dp[j] + 1) {\n dp[i] = dp[j] + 1\n last[i] = j\n }\n }\n }\n temp.add(i)\n subs[l] = temp\n } else {\n subs[l] = mutableListOf(i)\n }\n\n if (dp[i] > max) {\n max = dp[i]\n end = i\n }\n }\n\n val res = mutableListOf<String>()\n\n var curr = end\n while (curr != -1) {\n res.add(0, words[curr])\n curr = last[curr]\n }\n\n return res\n }\n\n private fun distance(words: Array<String>, i: Int, j: Int): Int {\n // input validations\n if (words[i].length == words[j].length) {\n var d = 0\n for (k in words[i].indices) {\n if (words[i][k] != words[j][k]) {\n d++\n }\n }\n return d\n }\n return -1\n }\n \n}\n```
0
0
['Kotlin']
0
longest-unequal-adjacent-groups-subsequence-ii
Easy, fast, efficient python solution
easy-fast-efficient-python-solution-by-l-pg6n
Intuition\nDynamic Programming,\nInitialize a table(ans) to store the current longest sequence and the previous word\'s idx;\nUpdate the longest sequence for ea
LouiseLi7
NORMAL
2024-01-24T05:28:30.659849+00:00
2024-01-24T05:28:30.659891+00:00
1
false
# Intuition\nDynamic Programming,\nInitialize a table(ans) to store the current longest sequence and the previous word\'s idx;\nUpdate the longest sequence for each word if requirements meet (hamming distance ==1, equal length, longer than the word\'s current longest sequence)\nBacktrack the words and append words by index\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(|word|*N^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution(object):\n def hamming_dist(self,s1,s2):\n for i in range(len(s1)):\n if s1[i]!=s2[i]:\n return s1[:i]+s1[i+1:]==s2[:i]+s2[i+1:]\n return False\n\n def getWordsInLongestSubsequence(self, n, words, groups):\n """\n :type n: int\n :type words: List[str]\n :type groups: List[int]\n :rtype: List[str]\n """\n ans = [[-1,1] for _ in range(n)]\n cur_max,max_idx = 1,0\n for i in range(1,n):\n for j in range(i,-1,-1):\n if groups[i]!=groups[j] and len(words[i])==len(words[j]):\n if self.hamming_dist(words[i],words[j]):\n if ans[i][1]<ans[j][1]+1:\n ans[i][0] = j\n ans[i][1] = ans[j][1]+1\n if ans[i][1]>cur_max:\n cur_max = ans[i][1]\n max_idx = i\n res = []\n # print(max_idx,cur_max,ans)\n while max_idx>=0:\n res.append(words[max_idx])\n max_idx = ans[max_idx][0]\n res.reverse()\n return res\n```
0
0
['Python']
0
longest-unequal-adjacent-groups-subsequence-ii
Easy, fast, efficient python solution
easy-fast-efficient-python-solution-by-l-xc4l
Intuition\nDynamic Programming,\nInitialize a table(ans) to store the current longest sequence and the previous word\'s idx;\nUpdate the longest sequence for ea
LouiseLi7
NORMAL
2024-01-24T05:28:29.392917+00:00
2024-01-24T05:28:29.392958+00:00
3
false
# Intuition\nDynamic Programming,\nInitialize a table(ans) to store the current longest sequence and the previous word\'s idx;\nUpdate the longest sequence for each word if requirements meet (hamming distance ==1, equal length, longer than the word\'s current longest sequence)\nBacktrack the words and append words by index\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(|word|*N^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution(object):\n def hamming_dist(self,s1,s2):\n for i in range(len(s1)):\n if s1[i]!=s2[i]:\n return s1[:i]+s1[i+1:]==s2[:i]+s2[i+1:]\n return False\n\n def getWordsInLongestSubsequence(self, n, words, groups):\n """\n :type n: int\n :type words: List[str]\n :type groups: List[int]\n :rtype: List[str]\n """\n ans = [[-1,1] for _ in range(n)]\n cur_max,max_idx = 1,0\n for i in range(1,n):\n for j in range(i,-1,-1):\n if groups[i]!=groups[j] and len(words[i])==len(words[j]):\n if self.hamming_dist(words[i],words[j]):\n if ans[i][1]<ans[j][1]+1:\n ans[i][0] = j\n ans[i][1] = ans[j][1]+1\n if ans[i][1]>cur_max:\n cur_max = ans[i][1]\n max_idx = i\n res = []\n # print(max_idx,cur_max,ans)\n while max_idx>=0:\n res.append(words[max_idx])\n max_idx = ans[max_idx][0]\n res.reverse()\n return res\n```
0
0
['Python']
0
longest-unequal-adjacent-groups-subsequence-ii
LIS Approach C++ Solution
lis-approach-c-solution-by-sultania_anku-xnc5
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Sultania_Ankush
NORMAL
2024-01-17T05:04:45.548177+00:00
2024-01-17T05:04:45.548238+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 {\npublic:\nint cal(string a,string b){\n int cnt=0;\n if(a.size()==b.size()){\n for(int i=0;i<a.size();i++){\n if(a[i]!=b[i]){\n ++cnt;\n }\n }\n return cnt;\n }\n else\n return 0;\n}\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {\n vector<int>dp(n,1);\n vector<int>parent(n,1);\n int maxi=-1;\n int lastindx=-1;\n for(int i=0;i<n;i++){\n parent[i]=i;\n for(int j=0;j<i;j++){\n if(groups[i]!=groups[j] && (words[i].size()==words[j].size()) && (cal(words[i],words[j])==1) && 1+dp[j]>dp[i]){\n dp[i]=1+dp[j];\n parent[i]=j;\n }\n }\n if(dp[i]>maxi){\n maxi=dp[i];\n lastindx=i;\n }\n }\n vector<string>ans;\nans.push_back(words[lastindx]);\nwhile(parent[lastindx]!=lastindx){\n lastindx=parent[lastindx];\n ans.push_back(words[lastindx]);\n}\nreverse(ans.begin(),ans.end());\nreturn ans;\n }\n};\n```
0
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
clean code with clear thought process, O(n^2)
clean-code-with-clear-thought-process-on-tyg0
condition satisfies when \n1. groups[i] != groups[i+1]\n2. isHammingDistanceByOne \n\nthought process was\nmemo[]\n2. 1. store longest length in each index , m
youngsam
NORMAL
2024-01-11T12:33:01.057047+00:00
2024-01-11T12:33:01.057065+00:00
0
false
condition satisfies when \n1. groups[i] != groups[i+1]\n2. isHammingDistanceByOne \n\nthought process was\nmemo[]\n2. 1. store longest length in each index , memo[i] =3 means [0...i] longest length is 3 \nindicies[]\n2. store previous index that has longest length in each index, \n then from last index, we traverse backward till meets -1 which means no previous index\n\t\n```\nclass Solution {\n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n \n //longest length \n int[] memo=new int[n];\n //previous index\n int[] indicies = new int[n]; \n \n int lastIndex=0,maxLength=0;\n //init\n Arrays.fill(indicies,-1);\n \n for(int i=0;i<n;i++){\n for(int j=0;j<i;j++){\n if (groups[j]!=groups[i] && isHammingDistanceByOne(words,i,j)){\n if(memo[i]<memo[j]+1){\n memo[i]=memo[j]+1;\n indicies[i]=j; \n }\n } \n }\n if(maxLength<memo[i]){\n maxLength=memo[i];\n lastIndex=i;\n }\n }\n \n List<String> res = new ArrayList<>();\n while(lastIndex!=-1){\n res.add(0,words[lastIndex]);\n lastIndex=indicies[lastIndex];\n }\n return res;\n \n }\n \n private boolean isHammingDistanceByOne(String[] words,int i,int j){\n String a=words[i],b=words[j];\n if(a.length()!=b.length())\n return false;\n int count=0;\n for(int k=0;k<a.length();k++){\n if(a.charAt(k)!=b.charAt(k))\n count++;\n \n if(count>1)\n return false;\n }\n \n return count==1;\n }\n}\n```\n\n
0
0
[]
0
longest-unequal-adjacent-groups-subsequence-ii
Easy understandable and readable java solution
easy-understandable-and-readable-java-so-clm9
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
guptalav465
NORMAL
2024-01-05T20:44:12.608482+00:00
2024-01-05T20:44:12.608506+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 \n public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) {\n boolean possible[][] = new boolean[n][n];\n int cnt[] = new int[n];\n \n for(int i = 0 ; i < n; i++){\n for(int j = 0 ; j < n;j++){\n if(!hamming(words[i], words[j], groups[i], groups[j]))\n continue;\n possible[i][j] = true;\n possible[j][i] = true; \n }\n }\n int next[] = new int[n];\n next[n-1]=n-1;\n int max = 1;\n cnt[n-1]=1;\n for(int j = n-1;j>=0;j--){\n int idx = j;\n cnt[j] = 1;\n for(int i = j+1;i<n;i++){\n if(possible[j][i] && cnt[j] < cnt[i]+1){\n // System.out.println(words[j] +" "+words[i] +" "+possible[j][i]+" " );\n\n idx = i;\n cnt[j] = cnt[i]+1;\n max = Math.max(max, cnt[j]);\n }\n }\n next[j] = idx;\n // System.out.println("cnt is "+cnt[j] +" j is "+j+" next is "+next[j]);\n\n }\n int start = 0;\n for(int i = 0; i < n;i++){\n if(cnt[i] == max){\n start = i;\n break;\n }\n }\n // System.out.println("max is "+max +" "+" start is "+start +" ");\n\n List<String>answer = new ArrayList<>();\n int p = start;\n while(next[p]!=p){\n answer.add(words[p]);\n p=next[p];\n }\n answer.add(words[p]);\n return answer;\n \n }\n \n private boolean hamming(String a, String b, int ga, int gb) {\n if(ga==gb)\n return false;\n int l = a.length();\n int l2 = b.length();\n \n if(l!=l2){\n return false;\n }\n int cnt = 0;\n for(int i = 0 ; i < l;i++) {\n if(a.charAt(i)!=b.charAt(i)) {\n cnt++;\n }\n }\n return cnt == 1;\n }\n}\n```
0
0
['Java']
0
longest-unequal-adjacent-groups-subsequence-ii
C++ | Easy to Understand
c-easy-to-understand-by-goku_2022-78ne
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
goku_2022
NORMAL
2024-01-03T09:52:09.888166+00:00
2024-01-03T09:52:09.888187+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 {\npublic:\n int h(string s, string t){\n int cnt = 0;\n for(int i=0;i<s.length();i++)\n if(s[i]!=t[i]) cnt++;\n return cnt;\n }\n vector<string> getWordsInLongestSubsequence(int n, vector<string>& w, vector<int>& g) {\n vector<string>a;\n vector<int> mp(n,1),v(n,-1);\n int c=0,d=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<i;j++)\n if(w[j].length()==w[i].length() && h(w[i],w[j])==1 && g[j] != g[i] && mp[i]<1+mp[j]){\n mp[i]=1+mp[j];\n v[i]=j;\n }\n if(mp[i]>c) c=mp[i],d=i;\n }\n while(v[d]!=-1){\n a.push_back(w[d]);\n d=v[d];\n }\n a.push_back(w[d]);\n reverse(a.begin(),a.end());\n return a;\n\n }\n};\n```
0
0
['C++']
0
longest-unequal-adjacent-groups-subsequence-ii
Bottom-up dp. Print LIS
bottom-up-dp-print-lis-by-vokasik-tlv0
For reference look at problem #300\n\n\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], nums: List[int]) -> List[str]:\n
vokasik
NORMAL
2023-12-16T23:39:51.412185+00:00
2023-12-16T23:52:17.474067+00:00
0
false
For reference look at problem #300\n\n```\nclass Solution:\n def getWordsInLongestSubsequence(self, n: int, words: List[str], nums: List[int]) -> List[str]:\n N = len(nums)\n dp = [1] * N # max LIS ending @ i\n parent = [-1] * N\n max_end = 0\n for cur in range(N):\n for prev in reversed(range(cur)):\n if len(words[prev]) == len(words[cur]) and nums[prev] != nums[cur] and \\\n sum(c1 != c2 for c1, c2 in zip(words[prev], words[cur])) == 1:\n if dp[prev] + 1 > dp[cur]:\n dp[cur] = dp[prev] + 1\n parent[cur] = prev\n if dp[cur] > dp[max_end]:\n max_end = cur\n res = []\n while max_end != -1:\n res.append(words[max_end])\n max_end = parent[max_end]\n return reversed(res)\n```
0
0
['Dynamic Programming', 'Python']
0