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
destroy-sequential-targets
C++ || Using unordered_map || modulo
c-using-unordered_map-modulo-by-bharat_b-0sij
\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n \n unordered_map<int,int>mp,mp1;\n \n sort(num
bharat_bardiya
NORMAL
2022-10-29T17:50:46.069191+00:00
2022-10-29T18:11:10.299808+00:00
44
false
```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n \n unordered_map<int,int>mp,mp1;\n \n sort(nums.begin(), nums.end());\n \n for(int x : nums){\n if(mp.find(x%space)==mp.end()){\n mp1[x%space] = x;\n }\n mp[x%space]++;\n }\n \n pair<int,int>maxi = {-1,-1};\n \n for(auto pr : mp){\n \n if(pr.second>maxi.second){\n maxi = pr;\n }\n else if(pr.second==maxi.second){\n if(mp1[pr.first] < mp1[maxi.first]){\n maxi = pr;\n }\n }\n }\n return mp1[maxi.first];\n }\n};\n```
1
0
['C']
0
destroy-sequential-targets
C++ simple Code with explanation(Hashing)
c-simple-code-with-explanationhashing-by-qx8j
Take two map and store the modular in first map with its frequency and after that check what is the frequency of the maximum modulo from the first map\nusing th
awesoME_15
NORMAL
2022-10-29T16:56:54.885380+00:00
2022-10-29T16:56:54.885416+00:00
18
false
Take two map and store the modular in first map with its frequency and after that check what is the frequency of the maximum modulo from the first map\nusing the second map.Check the corresponding modulo with the minimum value and return the ans.\n\n**C++ code** :\n\n int destroyTargets(vector<int>& nums, int space) {\n \n map<int,int>m1;\n int n = nums.size();\n \n for(int i=0;i<n;i++){\n m1[nums[i]%space]++;\n }\n \n \n \n int maxi{},res{};\n for(auto it : m1){\n // cout << it.first << " " <<it.second <<endl;\n maxi = max(maxi,it.second);\n }\n \n map<int,int>m2;\n for(auto it : m1){\n if(it.second==maxi){\n m2[it.first]++;\n }\n }\n \n \n int ans{};\n ans = 1e9+7;\n for(auto it : nums){\n long long int a = it%space;\n if(m2.find(a)!=m2.end()){\n ans = min(ans,it);\n }\n }\n \n return ans;\n }\n\n\nThank you.\n\t\n
1
0
['C']
0
destroy-sequential-targets
Java || Easy to understand || Clean code
java-easy-to-understand-clean-code-by-ag-u06b
\nclass Solution {\n \n // nums[i] + c * space = nums[j] ==> remainder + quotient * divisor = dividend,\n\t// you had to find the remainder \n // sort
agarwalaarrav
NORMAL
2022-10-29T16:32:52.667158+00:00
2022-10-29T17:20:07.691055+00:00
258
false
```\nclass Solution {\n \n // nums[i] + c * space = nums[j] ==> remainder + quotient * divisor = dividend,\n\t// you had to find the remainder \n // sort the array, so to find first minimum occurence\n public int destroyTargets(int[] nums, int space) {\n int n = nums.length;\n Arrays.sort( nums );\n HashMap<Integer, Integer> map = new HashMap<>();\n\n for( int num : nums )\n {\n map.compute( num % space, ( k, v ) -> v == null ? 1 : v+1 );\n }\n\n int max = 0;\n int max_count = 0;\n\n for( int num : nums )\n {\n if( map.containsKey( num ) && max_count < map.get( num ) )\n {\n max = num;\n max_count = map.get( num );\n }\n \n // edge - cases.\n if( map.containsKey( num % space ) && max_count < map.get( num % space ) )\n {\n max = num;\n max_count = map.get( num % space );\n }\n }\n\n return max == 0 ? nums[0] : max;\n }\n}\n```
1
0
[]
0
destroy-sequential-targets
[C++] | A.P | O(nlogn) time | O(n) space
c-ap-onlogn-time-on-space-by-muheshkumar-e8d2
Intuition\n Notice that the term nums[i] + c * space represents a general term of an A.P(Arithmetic Progression) with first element as nums[i] and common differ
muheshkumar
NORMAL
2022-10-29T16:24:13.589101+00:00
2022-10-29T16:24:13.589143+00:00
456
false
**Intuition**\n* Notice that the term nums[i] + c * space represents a general term of an A.P(Arithmetic Progression) with first element as nums[i] and common difference as space\n* Now, the problem just reduces to finding the first term of the longest A.P(not necessarily consecutive terms) which is present in the given input array.\n* Since, we know that the the answer\'s part of an A.P with common difference `space`, we assume each element a[i] to be part of an A.P with such common difference and try to remove the largest multiple of `space` from a[i] (which is just taking modulo with `space`. Idk why I was complicating this in the contest).\n* Now, every term a[i] has been reduced such that we can check if it belongs to an A.P starting with a[i] or not\n* Then the length of the longest A.P is just the maximum frequency of any reduced a[i]\n\n**Code**\n```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& a, int space) {\n sort(a.begin(), a.end());\n vector<int> b = a;\n map<int, int> cnt;\n\t \n int mx = 0;\n for (auto &bi: b) {\n bi -= bi / space * space;\n cnt[bi]++;\n mx = max(mx, cnt[bi]);\n }\n\t \n int mn = 2e9;\n for (auto &ai: a) {\n int aii = ai - ai / space * space;\n if (cnt[aii] == mx)\n mn = min(mn, ai);\n }\n return mn;\n }\n};\n```
1
0
['C++']
0
destroy-sequential-targets
Short & Concise | C++
short-concise-c-by-tusharbhart-53mp
\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n unordered_map<int, int> m;\n for(int i : nums) m[i % space]+
TusharBhart
NORMAL
2022-10-29T16:09:48.076067+00:00
2022-10-29T16:09:48.076115+00:00
392
false
```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n unordered_map<int, int> m;\n for(int i : nums) m[i % space]++;\n \n vector<pair<int, int>> v;\n for(auto i : m) v.push_back({i.second, i.first});\n \n sort(v.begin(), v.end(), greater<pair<int, int>>());\n int f = v[0].first, j = 0, ans = INT_MAX;\n \n while(j < v.size() && v[j].first == f) {\n int mn = INT_MAX;\n for(int i : nums) {\n if(i % space == v[j].second) mn = min(mn, i);\n }\n ans = min(ans, mn);\n j++;\n }\n \n return ans;\n }\n};\n```
1
0
['Math', 'Sorting', 'C++']
0
destroy-sequential-targets
C++ map | Three line solution
c-map-three-line-solution-by-__abcd-utav
\nclass Solution {\npublic:\n int destroyTargets(vector<int>& arr, int space,int mn = INT_MAX,int mx = -1,map<int,int>mp = {}) {\n for(auto ele:ar
__Abcd__
NORMAL
2022-10-29T16:06:46.873556+00:00
2022-10-29T16:06:46.873595+00:00
103
false
```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& arr, int space,int mn = INT_MAX,int mx = -1,map<int,int>mp = {}) {\n for(auto ele:arr)mp[ele%space]++,mx = max(mx,mp[ele%space]);\n for(auto ele:arr)if(mp[ele%space] == mx) mn = min(mn,ele);\n return(mn); \n }\n};\n```
1
0
[]
2
destroy-sequential-targets
Java using reminder
java-using-reminder-by-mi1-qxr1
\nclass Solution {\npublic int destroyTargets(int[] nums, int space) {\n Map<Integer, List<Integer>> map = new HashMap<>();\n int ans = Integer.MA
mi1
NORMAL
2022-10-29T16:03:01.155320+00:00
2022-10-29T16:03:01.155361+00:00
72
false
```\nclass Solution {\npublic int destroyTargets(int[] nums, int space) {\n Map<Integer, List<Integer>> map = new HashMap<>();\n int ans = Integer.MAX_VALUE;\n for (int num : nums) {\n map.putIfAbsent(num % space, new ArrayList<>());\n map.get(num % space).add(num);\n }\n int max = -1;\n for (int key : map.keySet()) {\n Collections.sort(map.get(key));\n max = Math.max(max, map.get(key).size());\n }\n\n for (int key : map.keySet()) {\n if (map.get(key).size() == max) {\n ans = Math.min(ans, map.get(key).get(0));\n }\n }\n\n\n return ans;\n }\n}\n```
1
0
[]
0
destroy-sequential-targets
Two Hashmaps
two-hashmaps-by-wanderer_00-c8u8
Sort the array in non decreasing order. Count the frequency of (target MOD space) using a hashmap. If the key is absent, map it to the target in another hashmap
WandereR_00
NORMAL
2022-10-29T16:03:00.509979+00:00
2022-10-29T16:03:00.510021+00:00
289
false
Sort the array in non decreasing order. Count the frequency of `(target MOD space)` using a hashmap. If the key is absent, map it to the target in another hashmap (This is the smallest seed value)\n```\nclass Solution\n{\n public int destroyTargets(int[] nums, int space)\n {\n Arrays.sort(nums);\n Map<Integer, Integer> map = new HashMap<>(), ans = new HashMap<>();\n for(int i : nums)\n {\n int key = i % space;\n if(!map.containsKey(key))\n ans.put(key,i);\n map.put(key, map.getOrDefault(key,0)+1);\n }\n int ret = -1;\n for(int i : map.keySet())\n {\n if(ret == -1)\n ret = i;\n if(map.get(ret) < map.get(i) || (map.get(ret) == map.get(i) && ans.get(ret) > ans.get(i)))\n ret = i;\n }\n return ans.get(ret);\n }\n}\n```
1
0
['Java']
0
destroy-sequential-targets
Simple Java Solution
simple-java-solution-by-sakshikishore-7pcu
Code
sakshikishore
NORMAL
2025-03-21T10:02:32.580259+00:00
2025-03-21T10:02:32.580259+00:00
4
false
# Code ```java [] class Solution { public int destroyTargets(int[] nums, int space) { Arrays.sort(nums); int max=0; HashMap<Integer,Integer> h=new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++) { int p=nums[i]%space; if(!h.containsKey(p)) { h.put(p,1); if(1>max){ max=1; } } else { h.put(p,h.get(p)+1); if(h.get(p)>max) { max=h.get(p); } } } for(int i=0;i<nums.length;i++) { if(h.get(nums[i]%space)==max) { return nums[i]; } } return 0; } } ```
0
0
['Java']
0
destroy-sequential-targets
(72ms) HashMap<Int, Pair<Int, Int>>()
72ms-hashmapint-pairint-int-by-sav200119-zjmv
ApproachHashMap<Int, Pair<Int, Int>>()ComplexityCode
sav20011962
NORMAL
2025-02-14T08:43:47.979195+00:00
2025-02-14T08:43:47.979195+00:00
3
false
# Approach HashMap<Int, Pair<Int, Int>>() # Complexity ![image.png](https://assets.leetcode.com/users/images/097b4f3f-d934-4b8a-84c6-e0b53cb7f30a_1739522606.7031102.png) # Code ```kotlin [] class Solution { fun destroyTargets(nums: IntArray, space: Int): Int { val map = HashMap<Int, Pair<Int, Int>>() for (N in nums) { val ost = N % space if (map.containsKey(ost)) { val (min,cou) = map.getValue(ost) map[ost] = Pair(Math.min(min,N),cou+1) } else map[ost] = Pair(N,1) } var rez = nums[0] var maxcou = 0 for ((key,pair) in map) { val (min,cou) = pair if (cou==maxcou) rez = Math.min(rez,min) else if (cou>maxcou) { maxcou = cou rez = min } } return rez } } ```
0
0
['Kotlin']
0
destroy-sequential-targets
2453. Destroy Sequential Targets
2453-destroy-sequential-targets-by-g8xd0-d8be
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-18T15:54:40.359181+00:00
2025-01-18T15:54:40.359181+00:00
7
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 ```cpp [] class Solution { public: int destroyTargets(vector<int>& nums, int space) { int result = INT_MAX, highestCount = INT_MIN; unordered_map<int, int> modCounts; for (const int& value : nums) { int remainder = value % space; modCounts[remainder]++; highestCount = max(highestCount, modCounts[remainder]); } for (const int& value : nums) { if (modCounts[value % space] == highestCount) { result = min(result, value); } } return result; } }; ```
0
0
['C++']
0
destroy-sequential-targets
Python Code
python-code-by-amirmazaheri-9tuk
IntuitionApproachGet the remainer of each num with space, and keep a list per remainder. Return the minimum of the longest list.Complexity Time complexity: O(n
amirmazaheri
NORMAL
2024-12-29T23:14:03.801038+00:00
2024-12-29T23:14:03.801038+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Hash by space modulation -- Python code # Approach <!-- Describe your approach to solving the problem. --> Get the remainer of each num with space, and keep a list per remainder. Return the minimum of the longest list. # Complexity - Time complexity: $$O(n)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(n)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python [] class Solution(object): def destroyTargets(self, nums, space): """ :type nums: List[int] :type space: int :rtype: int """ # nums = sorted(nums) seeds = dict() for n in nums: m = n%space seeds.setdefault(m, []).append(n) print(seeds) l = [] for seed, values in seeds.items(): l.append((-len(values), min(values))) l = min(l) print(l) return l[-1] ```
0
0
['Python']
0
destroy-sequential-targets
hashmap
hashmap-by-kai_xd-dft3
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
Kai_XD
NORMAL
2024-10-27T06:22:40.234245+00:00
2024-10-27T06:22:40.234284+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```python3 []\nclass Solution:\n def destroyTargets(self, nums: List[int], space: int) -> int:\n hashmap =defaultdict(int)\n for num in nums:\n hashmap[num % space] += 1\n \n ans = float(\'inf\')\n max_len = 0\n for num in nums:\n mod_val = num % space\n if hashmap[mod_val] > max_len or (hashmap[mod_val] == max_len and num < ans):\n max_len = hashmap[mod_val]\n ans = num\n \n return ans\n```
0
0
['Python3']
0
destroy-sequential-targets
Java simple solution. (hashmap)
java-simple-solution-hashmap-by-meatymon-a82a
Intuition \n\n\nSince the distance is in multiples of space, we can mod every number by space to group them together.\n\nIf nums = [1,3,5,2,4,6] and space = 2\n
meatymonken
NORMAL
2024-10-02T16:29:36.083962+00:00
2024-10-02T16:38:30.279163+00:00
6
false
# Intuition \n\n\nSince the distance is in multiples of `space`, we can mod every number by `space` to group them together.\n\nIf nums = `[1,3,5,2,4,6]` and space = 2\nthe resulting modulus by 2 is `[1,1,1,0,0,0]`.\n\nIf we were to pick `1`, three targets goes down. and if we were to pick `0` also three targets goes down. The smallest number between both groups is `nums[0]` which is 1, which is our answer. We pick the smallest number since it is the start of the sequence `nums[i] + c * space`, which results in the most targets down.\n\nOur goal becomes: among every group of modulus with the largest size (since more than one group can have the largest size), what is the smallest element among all of them?\n\n# Approach \n\nFirst we initialise a hashmap\n- key: the group\n- value: we store two things, the size of this group, and the smallest number part of this group. we can represent the value of the hashmap as an `int[]` to store two values\n\nThen we process every value in `nums` , which i call `i`\n1. calculate `group`, which is `i%space`\n2. look up the hashmap to see if the group already exist\n3. if the group exist, we increment the size of it by one, and we update the smallest value by using `Math.min()`\n4. if the group does not exist, we create one, with the size of it as 1 and the smallest value as `i` itself\n\nNext we create an int `max` to keep track of the largest group as we iterate the values of the hashmap. we also create `res` to store the result of the smallest element \n\nfor each value pair in the hashmap\n- if this group also has the same max size, we compare who has the smallest element and make it the result, `res`\n- if this group has a greater max size, we update max and automatically make its smallest element as `res`\n\n\n\nTime: O(n) \n\n\n\n# Code\n```java []\nclass Solution {\n public int destroyTargets(int[] nums, int space) {\n Map<Integer,int[]> map = new HashMap<>();\n for (int i: nums){\n int group = i%space;\n if (map.containsKey(group)){\n int[] val = map.get(group);\n val[0]++;\n val[1] = Math.min(val[1],i);\n map.put(group,val);\n }\n else map.put(group,new int[]{1,i});\n }\n\n int max = 0;\n int res = Integer.MAX_VALUE;\n for (int[] i: map.values()){\n if (i[0]==max) res = Math.min(res,i[1]);\n else if (i[0]>max){ \n max = i[0];\n res=i[1];\n }\n }\n return res;\n }\n}\n```
0
0
['Java']
0
destroy-sequential-targets
C++ GRANDMASTER LEGENDARY SOLUTION EASY TO UNDERSTAND FOR ALL :)
c-grandmaster-legendary-solution-easy-to-y6cl
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
Half-Dimension
NORMAL
2024-10-01T14:04:50.362962+00:00
2024-10-01T14:04:50.362987+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```cpp []\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n unordered_map<int, int> freq;\n unordered_map<int, int> smallest;\n \n // Track frequencies of nums[i] % space\n for (int num : nums) {\n int rem = num % space;\n freq[rem]++;\n if (smallest.find(rem) == smallest.end() || num < smallest[rem]) {\n smallest[rem] = num;\n }\n }\n\n // Find the remainder group with the max frequency\n int maxCount = 0;\n int result = INT_MAX;\n \n for (auto& [rem, count] : freq) {\n if (count > maxCount || (count == maxCount && smallest[rem] < result)) {\n maxCount = count;\n result = smallest[rem];\n }\n }\n\n return result;\n }\n};\n\n```
0
0
['C++']
0
destroy-sequential-targets
C++ | Counting n Sorting
c-counting-n-sorting-by-kena7-7ygu
\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) \n {\n sort(nums.begin(),nums.end());\n unordered_map<int,int
kenA7
NORMAL
2024-09-11T14:34:08.535997+00:00
2024-09-11T14:34:08.536031+00:00
1
false
```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) \n {\n sort(nums.begin(),nums.end());\n unordered_map<int,int>m;\n for(auto &x:nums)\n m[x%space]++;\n int mx=-1,res=-1;\n for(auto &x:nums)\n {\n int r=x%space;\n if(m[r]>mx)\n {\n res=x;\n mx=m[r];\n }\n m[r]--;\n }\n return res;\n }\n};\n```
0
0
[]
0
destroy-sequential-targets
Common Logic
common-logic-by-shaanpatel9889-sthi
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-06T11:38:40.377598+00:00
2024-08-06T11:38:40.377627+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 destroyTargets(vector<int>& nums, int space) {\n vector<pair<int,int>> vp;\n for(int i = 0; i < nums.size(); i++) {\n vp.push_back({nums[i], nums[i] % space});\n }\n\n map<int, multiset<int>> mp;\n for(auto it : vp) {\n mp[it.second].insert(it.first);\n }\n\n int maxi = -1;\n int mini = INT_MAX;\n for(auto it : mp) {\n int size = it.second.size();\n if(size > maxi) {\n maxi = size;\n mini = *it.second.begin();\n }\n else if(size == maxi && *it.second.begin() < mini) {\n mini = *it.second.begin();\n }\n }\n\n return mini;\n }\n};\n\n```
0
0
['C++']
0
destroy-sequential-targets
Destroy Sequential Targets | Sorting | MOD | Easy C++
destroy-sequential-targets-sorting-mod-e-eyav
\n# Complexity\n- Time complexity: O(nlogn)\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) \
JeetuGupta
NORMAL
2024-08-01T19:21:48.410989+00:00
2024-08-01T19:21:48.411020+00:00
1
false
\n# Complexity\n- Time complexity: $$O(nlogn)$$\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 int destroyTargets(vector<int>& nums, int space) {\n sort(nums.begin(), nums.end());\n map<int ,int> mp;\n for(int i = nums.size() - 1; i>=0; i--){\n mp[nums[i]%space] = nums[i];\n }\n\n map<int, int> count;\n for(auto x : nums){\n count[x%space]++;\n }\n\n int ans = -1, maxi = 0;\n for(auto x : count){\n if(ans == -1){\n ans = x.first;\n maxi = x.second;\n }else if(maxi == x.second){\n if(mp[x.first] < mp[ans]){\n ans = x.first;\n }\n }else if(maxi < x.second){\n maxi = x.second;\n ans = x.first;\n }\n }\n\n return mp[ans];\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
JAVA
java-by-manu-bharadwaj-bn-mtfa
Code\n\nclass Solution {\n public int destroyTargets(int[] nums, int space) {\n int n = nums.length;\n HashMap<Integer, Integer> map = new Hash
Manu-Bharadwaj-BN
NORMAL
2024-07-17T12:22:13.603174+00:00
2024-07-17T12:22:13.603197+00:00
1
false
# Code\n```\nclass Solution {\n public int destroyTargets(int[] nums, int space) {\n int n = nums.length;\n HashMap<Integer, Integer> map = new HashMap<>();\n for (int num : nums) {\n num = num % space;\n map.put(num, map.getOrDefault(num, 0) + 1);\n }\n int maxi = Collections.max(map.values());\n Arrays.sort(nums);\n for (int i = 0; i < n; i++) {\n if (map.get(nums[i] % space) == maxi)\n return nums[i];\n }\n return 0;\n }\n}\n```
0
0
['Java']
0
destroy-sequential-targets
O(n) time complexity | C++ | Clean code
on-time-complexity-c-clean-code-by-prana-d26v
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires us to determine the minimum value of nums[i] such that when used t
pranay_battu
NORMAL
2024-06-30T07:38:12.671178+00:00
2024-06-30T07:38:12.671209+00:00
7
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to determine the minimum value of `nums[i]` such that when used to seed the machine, it destroys the maximum number of targets. My initial thought was to consider the remainders when each element in `nums` is divided by `space`. This is because numbers with the same remainder when divided by `space` can form a sequence that the machine can destroy. By counting these remainders, we can determine which starting value will allow us to destroy the most targets.\n\n`nums[i]` always part of only one sequence, as `nums[i] = x + c*space`, so every number of a sequence can be represnted as x (min value or starting point of imaginary seq) which is `nums[i] % space`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create an unordered map to store pairs where the key is the remainder when an element in `nums` is divided by `space`, and the value is a pair consisting of the count of that remainder and the smallest number with that remainder.\n2. Iterate through the `nums` array, calculate the remainder of each number when divided by `space`, and update the map accordingly.\n3. Traverse the map to find the remainder that has the highest count. In case of ties, select the smallest number associated with that remainder.\n4. Return the smallest number that corresponds to the remainder with the highest count.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is $$O(n)$$ because we iterate through the `nums` array twice: once to populate the map and once to determine the result.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is $$O(n)$$ due to the additional space used by the unordered map. - worst case when all are unique and space is larger than n\n\n# Code\n```cpp\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n int n = nums.size();\n unordered_map<int, pair<int,int>> m;\n \n for(int i = 0; i < n; ++i) {\n int rem = nums[i] % space;\n if(m.find(rem) != m.end()) {\n m[rem].first++;\n if(m[rem].second > nums[i]) m[rem].second = nums[i];\n } else {\n m[rem] = {1, nums[i]};\n }\n }\n\n int ans = INT_MAX, maxCnt = 0;\n for(auto it: m) {\n int num = it.second.second;\n int currCnt = it.second.first;\n if(currCnt > maxCnt) {\n maxCnt = currCnt;\n ans = num;\n }\n else if(currCnt == maxCnt && ans > num) {\n ans = num;\n }\n }\n\n return ans;\n }\n};\n
0
0
['Hash Table', 'Math', 'C++']
0
destroy-sequential-targets
HINDI Solution.
hindi-solution-by-aman_kr_1810-5msz
\n# Approach\nAgar tumhe english solutions samajhne me issue ho raha hai to isko padho samajh jaaoge.\n\n\n\n# Code\n\n// Acha conceptual question hai.\n/*\n
aman_kr_1810
NORMAL
2024-06-16T12:39:44.676917+00:00
2024-06-16T12:39:44.676940+00:00
4
false
\n# Approach\n**Agar tumhe english solutions samajhne me issue ho raha hai to isko padho samajh jaaoge.**\n\n\n\n# Code\n```\n// Acha conceptual question hai.\n/*\n Question mein bol kya raha hai :-\n Koi ek value daal denge gun me aur wo khud ko aur space ke saath apne saare multiple ko delete kar dege.\n Hum maximum ko delete karna hai.\n Agar 1 se jyada value same amount ko delete kar raha hai to minimum value ko return karna hai.\n*/\n\n/*\n Solving process :-\n Hum map me modulo with sapce store kar lenge har value ke liye.\n Ye to obvious hai ki maximum frequency wala hi answer hoga.\n Agar maximum frequency wala 1 se jyada number hai to usme sochna hoga.\n Iske liye sorted array me check kar lenge ki kya is value ke liye map me maximum frequency stored hai.\n Agar hai to usko hi return kar dena hai.\n*/\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n int n = nums.size();\n sort(nums.begin(),nums.end());\n unordered_map<int,int> mp;\n\n // Map me modulo store kara lenge.\n for(auto &i:nums)\n mp[i%space]++;\n \n vector<int> temp;\n int maxfreq=0;\n\n // Maximum frequency nikaal lenge.\n for(auto &i:mp)\n maxfreq = max(maxfreq,i.second);\n \n // Sorted array me check karnege ki kya is value ke liye map me maximum value stored hai.\n for(int i=0;i<n;i++){\n if(mp[nums[i]%space]==maxfreq)\n return nums[i];\n }\n return -1;\n }\n};\n```
0
0
['Array', 'Hash Table', 'Sorting', 'Counting', 'C++']
0
destroy-sequential-targets
Mod by space - Java - O(N) | O(Space)
mod-by-space-java-on-ospace-by-wangcai20-i5ey
Intuition\n Describe your first thoughts on how to solve this problem. \nCount the result of each numbers % space. The highest count is the one we want to feed
wangcai20
NORMAL
2024-05-08T18:45:11.688598+00:00
2024-05-08T19:43:50.822928+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCount the result of each `numbers % space`. The highest count is the one we want to feed to machine cause it destroys the most. Pay attention to corner cases that there might be multiple same highest count, need to pick the smallest among all of them.\n\nOne test case the `space` with very high value, that kills the solution of using counting array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(space)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int destroyTargets(int[] nums, int space) {\n // count freq of % space result, the biggest one reture the smallest\n Map<Integer, int[]> map = new HashMap<>();\n int max = 0, res = Integer.MAX_VALUE;\n for (int val : nums) {\n map.putIfAbsent(val % space, new int[] { 0, Integer.MAX_VALUE });\n int[] arr = map.get(val % space);\n arr[0]++;\n arr[1] = Math.min(arr[1], val);\n if (arr[0] > max) {\n res = arr[1];\n max = arr[0];\n } else if (arr[0] == max)\n res = Math.min(res, arr[1]);\n }\n return res;\n }\n}\n```
0
0
['Java']
0
destroy-sequential-targets
C++ | O(N)
c-on-by-shubhamchandra01-8u8e
Intuition\n Describe your first thoughts on how to solve this problem. \n\nWe are tempted to try remainder / mod operation on each number.\n\nIf two numbers sha
shubhamchandra01
NORMAL
2024-04-17T17:08:13.056834+00:00
2024-04-17T17:08:13.056866+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nWe are tempted to try remainder / mod operation on each number.\n\nIf two numbers share the same remainder when divided by `space`, bigger no. will always be `small + k * space`\n\n```\n// a and b share same remainder r\n\na = r + q1 * space\nb = r + q2 * space\n\na - b = (q1 - q2) * space\na = b + (q1 - q2) * space\n```\nThis allows us to group all numbers by their remainder with space.\n\nThe remainder group with highest count is the answer. \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 destroyTargets(vector<int>& nums, int space) {\n int n = nums.size();\n\t\tint mx = 0, ans = 1e9 + 5;\n\t\tunordered_map<int, int> dp;\n\t\tfor (int &x: nums) {\n\t\t\tint r = x % space;\n\t\t\tint cur = ++dp[r];\n\t\t\tmx = max(mx, cur);\n\t\t}\n\t\tfor (int &x: nums) {\n\t\t\tint r = x % space;\t\t\n\t\t\tint cur = dp[r];\n\t\t\tif (cur == mx && x < ans) ans = x;\n\t\t}\n\t\treturn ans;\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
C++
c-by-preetsahil289-idnt
\n# Approach\n(b-a)%space=0\n\n# Complexity\n- Time complexity:\n- best and average case =>O(2*nums.size())\n\n- Space complexity:\nO(n)\n\n# Code\n\nclass Solu
preetsahil289
NORMAL
2024-04-06T10:55:10.072765+00:00
2024-04-06T10:55:10.072783+00:00
0
false
\n# Approach\n(b-a)%space=0\n\n# Complexity\n- Time complexity:\n- best and average case =>O(2*nums.size())\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n\n\n int destroyTargets(vector<int>& nums, int space) {\n unordered_map<int,int> mpp;\n int high=0;\n for(int i=0;i<nums.size();i++){\n mpp[nums[i]%space]++;\n high=max(high,mpp[nums[i]%space]);\n }\n int ans=INT_MAX;\n for(int i=0;i<nums.size();i++){\n if(mpp[nums[i]%space]==high){\n ans=min(ans,nums[i]);\n }\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
21ms beats 100% Rust Solution
21ms-beats-100-rust-solution-by-esmail_2-fz9y
Code\n\nuse::std::collections::HashMap;\n\nimpl Solution {\n pub fn destroy_targets(nums: Vec<i32>, space: i32) -> i32 {\n let mut map: HashMap<i32, (
Esmail_2
NORMAL
2024-04-03T19:40:04.919957+00:00
2024-04-03T19:40:04.919996+00:00
3
false
# Code\n```\nuse::std::collections::HashMap;\n\nimpl Solution {\n pub fn destroy_targets(nums: Vec<i32>, space: i32) -> i32 {\n let mut map: HashMap<i32, (i32, i32)> = HashMap::new();\n let (mut res, mut size): (i32, i32) = (0, 0);\n for value in nums.into_iter() {\n map.entry(value % space).or_insert((0, 1e9 as i32 + 1));\n let refer: &mut (i32, i32) = map.get_mut(&(value % space)).unwrap();\n refer.0 += 1;\n refer.1 = if refer.1 > value {value} else {refer.1};\n }\n for (key, value) in map.into_iter() {\n if (value.0 < res || (value.0 == res && value.1 >= size)) {continue;}\n res = value.0; size = value.1;\n }\n return size;\n }\n}\n```
0
0
['Rust']
0
destroy-sequential-targets
Simple python3 solution | Sorting + Greedy + Hash Map
simple-python3-solution-sorting-greedy-h-n8nx
Complexity\n- Time complexity: O(n \cdot \log(n))\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g.
tigprog
NORMAL
2024-03-27T11:47:29.527256+00:00
2024-03-27T11:47:29.527287+00:00
7
false
# Complexity\n- Time complexity: $$O(n \\cdot \\log(n))$$\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``` python3 []\nclass Solution:\n def destroyTargets(self, nums: List[int], space: int) -> int:\n if space == 1:\n return min(nums)\n\n dp = Counter()\n max_ = 0\n arg_max = 0\n for elem in sorted(nums, reverse=True):\n dp[elem % space] += 1\n if dp[elem % space] >= max_:\n max_ = dp[elem % space]\n arg_max = elem\n return arg_max\n```
0
0
['Hash Table', 'Greedy', 'Sorting', 'Counting', 'Python3']
0
destroy-sequential-targets
100% results of space and time beat!
100-results-of-space-and-time-beat-by-ki-oojy
Approach\n- Keep count of all the elements\' modulo results\n- get the max values of the counted results\n- Filter through the number vector and find the minimu
kirubelmidru
NORMAL
2024-03-24T08:27:00.555892+00:00
2024-03-24T08:27:00.555925+00:00
6
false
# Approach\n- Keep count of all the elements\' modulo results\n- get the max values of the counted results\n- Filter through the number vector and find the minimum element that is part of the maximum modulo result\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n\n# Code\n```\nuse std::collections::HashMap;\nuse std::cmp;\n\nimpl Solution {\n pub fn destroy_targets(mut nums: Vec<i32>, space: i32) -> i32 {\n let mut hash: HashMap<i32, i32> = HashMap::new();\n let mut list: Vec<i32> = Vec::new();\n\n for i in nums.iter() {\n *hash.entry(i % space).or_insert(0) += 1;\n }\n let max = *hash.values().max().unwrap();\n \n for i in hash.into_iter() {\n if i.1 == max {\n list.push(i.0);\n }\n }\n nums.into_iter().filter(|x| list.contains(&(x % space))).min().unwrap()\n }\n}\n```
0
0
['Array', 'Hash Table', 'Counting', 'Rust']
0
destroy-sequential-targets
ok ^^
ok-by-andrii_khlevniuk-m9ag
\nint destroyTargets(vector<int>& n, int s)\n{\n\tunordered_map<int,int> N,m;\n\tint iM{INT_MAX};\n\tfor(const auto & n : n)\n\t{\n\t\t++N[n%s];\n\t\tm[n%s] = m
andrii_khlevniuk
NORMAL
2024-02-06T15:32:33.200914+00:00
2024-02-06T15:32:33.200947+00:00
1
false
```\nint destroyTargets(vector<int>& n, int s)\n{\n\tunordered_map<int,int> N,m;\n\tint iM{INT_MAX};\n\tfor(const auto & n : n)\n\t{\n\t\t++N[n%s];\n\t\tm[n%s] = m.count(n%s) ? min(m[n%s],n) : n;\n\n\t\tif(N[n%s]>N[iM%s])\n\t\t\tiM = m[n%s];\n\t\telse if(N[n%s]==N[iM%s])\n\t\t\tiM = min(iM, m[n%s]);\n\t}\n\treturn iM;\n}\n```
0
0
['C', 'C++']
0
destroy-sequential-targets
Beats 88.95% of users with Python3
beats-8895-of-users-with-python3-by-st20-x9ny
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
st20080675
NORMAL
2024-02-05T02:55:49.800843+00:00
2024-02-05T02:55:49.800872+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:\n def destroyTargets(self, nums: List[int], space: int) -> int:\n nums.sort()\n buf = nums.copy()\n n = len(nums)\n for i in range(n):\n nums[i] = nums[i] % space\n\n t = Counter(nums).most_common(1)[0][0]\n idx = nums.index(t)\n return buf[idx]\n \n \n\n\n \n```
0
0
['Python3']
0
destroy-sequential-targets
cpp easy explanation
cpp-easy-explanation-by-abhi_bittu2525-qq9r
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
abhi_bittu2525
NORMAL
2024-01-18T13:07:13.805317+00:00
2024-01-18T13:07:13.805350+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 {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n sort(nums.begin(),nums.end());\n map<int,vector<int> >mp;\n for(int i =0;i<nums.size();i++){\n int modlus = nums[i]%space;\n mp[modlus].push_back(nums[i]);\n }\n for(auto it : mp){\n cout<<it.first<<" "<<it.second.size()<<endl;\n }\n \n int ans =INT_MAX;\n int last =0;\n for(auto it : mp){\n \n if(it.second.size() > last){\n sort(it.second.begin(),it.second.end());\n for(auto itt : it.second){\n cout<<itt<<" ";\n ans = itt;\n break;\n }\n }\n else if(it.second.size() == last){\n sort(it.second.begin(),it.second.end());\n for(auto itt : it.second){\n cout<<itt<<" ";\n ans = min(ans,itt);\n break;\n }\n \n }\n int ss = it.second.size();\n last = max(last,ss);\n }\n return ans;\n\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
scala solution
scala-solution-by-vititov-108q
\n\nobject Solution {\n def destroyTargets(nums: Array[Int], space: Int): Int = {\n lazy val list = nums.toList.map(x => x -> x % space).groupMap(_._2)(_._1
vititov
NORMAL
2024-01-08T16:08:15.306170+00:00
2024-01-08T16:08:15.306201+00:00
7
false
\n```\nobject Solution {\n def destroyTargets(nums: Array[Int], space: Int): Int = {\n lazy val list = nums.toList.map(x => x -> x % space).groupMap(_._2)(_._1).values.toList\n lazy val mxSize = list.maxBy(_.size).size\n list.filter(_.size == mxSize).flatten.min\n }\n}\n```
0
0
['Scala']
0
destroy-sequential-targets
Easy C++ Solution | Sorting
easy-c-solution-sorting-by-sakshamchhimw-rpto
Intuition\nThis problem demands the following equation to be satisfied\n$\frac{(nums[i]-nums[j])}{space} \in Integer$.\n\n> Proof\n\n\because \frac{(nums[i]-num
sakshamchhimwal2410
NORMAL
2024-01-07T11:03:57.902341+00:00
2024-01-07T11:03:57.902375+00:00
4
false
# Intuition\nThis problem demands the following equation to be satisfied\n$\\frac{(nums[i]-nums[j])}{space} \\in Integer$.\n\n> Proof\n$$\n\\because \\frac{(nums[i]-nums[j])}{space} \\in Integer \\\\\n\\implies (\\space nums[i]-nums[j]\\space )\\%space = 0 \\\\\n\\implies (\\space nums[i]\\%space - nums[j]\\%space \\space)\\%space = 0 \\\\\n\\therefore \\space nums[i]\\space \\% \\space space = nums[j]\\space \\%\\space space\n$$\n\n# Approach\nWe create a pair of integers `{nums[i] % space, nums[i]}`. Then we will sort it and count all the numbers with equal `nums[i]%space`. This will be the number of numbers in `nums` that staisfy the above equation.\n\n# Complexity\n- Time complexity:\n\n>Creating the new `vector<pair<int,int>>`: $$O(n)$$\nSorting : $$O(n \\space log(n))$$\n\n**Overall : $$O(n \\space log(n))$$**\n\n- Space complexity:\n>Creating the new `vector<pair<int,int>>`: $$O(n)$$\nSorting : $$O(n)$$\n\n**Overall : $$O(n)$$**\n\n# Code\n```\nclass Solution\n{\npublic:\n int destroyTargets(vector<int> &nums, int space)\n {\n int n = nums.size();\n vector<pair<int, int>> modVals(n);\n for (int i = 0; i < n; i++)\n modVals[i] = {nums[i] % space, nums[i]};\n sort(modVals.begin(), modVals.end());\n int maxCommon = 0;\n int minSeed = INT_MAX;\n for (int i = 0; i < n; i++)\n {\n int currCommon = 1;\n int currMinSeed = modVals[i].second;\n while (i + 1 < n && modVals[i].first == modVals[i + 1].first)\n {\n currCommon += 1;\n currMinSeed = min(currMinSeed, modVals[i].second);\n i++;\n }\n if (currCommon >= maxCommon)\n {\n minSeed = (currCommon == maxCommon) ? min(minSeed, currMinSeed) : currMinSeed;\n maxCommon = currCommon;\n }\n }\n return minSeed;\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
O(n) Common Reminder Approach
on-common-reminder-approach-by-abhishekm-j8os
Intuition\nIf, nums[j]%space = nums[i]%space\nThen, nums[j] = nums[i] + c * space,\n\n Describe your first thoughts on how to solve this problem. \n\n# Approach
abhishekmen
NORMAL
2024-01-03T04:43:56.674579+00:00
2024-01-03T04:43:56.674615+00:00
2
false
# Intuition\nIf, nums[j]%space = nums[i]%space\nThen, nums[j] = nums[i] + c * space,\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nunordered_map<int,pair<int, int>> mp;\n\n- mp.first = nums[i]%space\n- mp.second.first = no.of nums[i] \n - whose nums[i]%space=mp.first\n- mp.second.second = min of nums[i] \n - whose nums[i]%space=mp.first\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(n)$$\n - unordered_map insert and find is O(1) \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 destroyTargets(vector<int>& nums, int space) {\n int n = nums.size();\n unordered_map<int, pair<int, int>> mp;\n int ans = nums[0];\n int maxx = 0;\n\n for (auto i : nums) {\n auto t = mp.find(i % space);\n if (t != mp.end()) {\n mp[i % space] = {t->second.first + 1,\n t->second.second > i ? i : t->second.second};\n if ((t->second.first)>maxx) {\n maxx = t->second.first;\n ans = t->second.second;\n } else if ((t->second.first)==maxx) {\n ans = min(ans, t->second.second);\n }\n } else {\n mp[i % space] = {1, i};\n if (1>maxx) {\n maxx=1;\n ans=i;\n } else if (1==maxx) {\n ans=min(ans, i);\n }\n }\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
Python, use a Counter (almost always)
python-use-a-counter-almost-always-by-ma-lnkq
Intuition\n Describe your first thoughts on how to solve this problem. \nAs the hint suggests, the first step is to calculate for all nums[i] the value nums[i]
markalavin
NORMAL
2024-01-01T14:12:30.607612+00:00
2024-01-01T14:12:30.607644+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the hint suggests, the first step is to calculate for all ```nums[i]``` the value ```nums[i] % space```; let\'s refer to this as ```mod_num[i]```. It turns out that ```nums``` that go into the same "kill group" (the subset of ```nums``` that could be killed by the same "seed") have the same ```mod_num[i]```.\n\nWe want the *maximum* kill group. So, for each possible value of ```mod_num[i]```, we want to count how many ```nums``` have that value, and select the ```mod_num[i]``` that appears most frequently. But, we want the *minimal* seed, the smallest value in ```nums``` that maps into the most frequently. To get this, we have to recover all the ```nums``` that map into the maximal ```mod_num``` and then take the minimum one.\n\nOne further elaboration: In some cases, there will be *multiple* maximum kill groups. In that case, we calculate the minimal seed for each of the kill groups and take the minimum of *those*.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo, how to implement all the stuff described above? For me, the answer was easy: Use Python\'s nifty ```Counter``` class, in conjunction with the ```Counter``` method ```most_common```. The statement\n``` \nmod_nums_counts = Counter( mod_nums ).most_common\n```\ntakes the ```mod_nums``` we\'ve calculated and determines how many of each value in ```mod_nums``` there are. Specifically, it produces a structure like:\n```\n( ( mod_num_A, count(mod_num_A) ), ( mod_num_B, count( mod_num_B ), ... ) )\n```\nThis provides us with most of the required information (which ```mod_num```(s) is/are most frequent). Then it\'s a matter of Pythonery to loop over the structure above, and for each, using a *list comprehension* to map back to the original ```nums```. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe first statement in the program loops over all elements in ```nums``` and thus is $$O(n)$$ where n is the number of ```nums```.\nThe ```for``` loop executes once per kill group. As we can see in the third Example, it\'s possible that all the kill groups are singletons, in which case *that* loop is $$O(n)$$. One additional factor: lurking in the ```for``` loop, there is a loop comprehension, and the effect is that the overall time complexity is $$O(n*k)$$ where $$n$$ is the number of ```nums``` and $$k$$ is the number of kill groups, so worst case, $$O(n^2)$$. In practice, for the test cases, this worst case didn\'t appear much, if at all.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThere are three non-scalar variables (not counting input): ```mod_nums```, which is $$O(n)$$ in storage, ```mod_nums_counts``` , which is $$O(k)$$ and ```nums_with_mod_count```, which is also $$O(n)$$ for an overall space complexity of $$O(n)$$.\n# Code\n```\nclass Solution:\n def destroyTargets(self, nums: List[int], space: int) -> int:\n mod_nums = [ num % space for num in nums ]\n mod_nums_counts = Counter( mod_nums ).most_common()\n max_count = mod_nums_counts[ 0 ][ 1 ]\n min_num = math.inf\n for mod_num, count in mod_nums_counts:\n if count < max_count:\n break\n # OK, so "mod_num" is one of the most frequent (maximum number of\n # targets destroyed). If there is more than one such "mod_num",\n # select the one whose "count bucket" contains the smallest value:\n nums_with_mod_count = [ num for num in nums if num % space == mod_num ]\n this_min_num = min( nums_with_mod_count )\n min_num = min( min_num, this_min_num )\n return min_num\n```
0
0
['Python3']
0
destroy-sequential-targets
C++ Easy Solution
c-easy-solution-by-md_aziz_ali-4u7q
Code\n\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n int ans = 0;\n int count = 0;\n unordered_map<i
Md_Aziz_Ali
NORMAL
2023-12-20T09:33:22.394621+00:00
2023-12-20T09:33:22.394682+00:00
2
false
# Code\n```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n int ans = 0;\n int count = 0;\n unordered_map<int,pair<int,int>> mp;\n for(int i = 0;i < nums.size();i++) {\n int k = nums[i]%space;\n if(mp[k].first == 0) \n mp[k].second = nums[i];\n else \n mp[k].second = min(nums[i],mp[k].second);\n\n mp[k].first++;\n if(count < mp[k].first) {\n count = mp[k].first;\n ans = mp[k].second;\n }\n else if(count == mp[k].first)\n ans = min(ans,mp[k].second);\n }\n return ans;\n }\n};\n```
0
0
['Hash Table', 'C++']
0
destroy-sequential-targets
Python | HashMap Solution| O(n)
python-hashmap-solution-on-by-pandeypriy-1377
Intuition\n Describe your first thoughts on how to solve this problem. \nKeeping track of remainders is the key to this problem.\n\n# Approach\n Describe your a
pandeypriyesh184
NORMAL
2023-12-17T02:06:40.512685+00:00
2023-12-17T02:06:40.512702+00:00
7
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nKeeping track of remainders is the key to this problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nProblem can be divided into following cases:\n1. len(nums) == 1: only 1 value then return it as seed value\n2. find max(nums), if space >= max(nums) then num in nums cannot be divided by `space`, hence in this case simply return number which occurs the most in the array as seed value.\n3. Here space < max(nums): \n 1. keep track of remainders count as well as min_seed corresponding to that remainder in a dict(hash map)\n 2. get min_seed with max remainder freq.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n \'\'\'\n [3,5,8,9,7,1,3] : \n What is the maximum length of array? : 1 to 10^5\n What is the range of numbers?: 1 to 10^9\n Are the numbers unique? or duplicates are allowed? : non-unique/ follow-up: does it matter?\n\n space : integer : range? : 1 to 10^9\n\n problem: find max number of numbers in nums array that can be destroyed?\n destroy func: if seed + c*space == num : destroy it\n Find seed value: it should be one of num in nums (minimum)\n\n Cases: \n 1: L = 1: -> seed = nums[0]\n 2: space >= max(nums) : seed = num with max freq in nums\n 3: space < max(nums): \n [1,3,5,2,4,6] --> [1,1,1,0,0,0]\n {1:(3, 1), 0:(3,2)} -> get min of maxcount items\n max_count = 0\n min_seed = inf\n for key, val in store.items():\n count, seed = val\n if count > max_count:\n max_count = count\n min_seed = seed\n elif count == max_count:\n min_seed = min(min_seed, seed)\n 4: space < min(nums):\n [3,5,4,6] space = 2\n [1,1,0,0]\n\n \'\'\'\n def destroyTargets(self, nums: List[int], space: int) -> int:\n n = len(nums)\n if n == 1: return nums[0]\n max_ = max(nums)\n\n if space >= max_:\n freq = defaultdict(int)\n for num in nums:\n freq[num] += 1\n max_freq = 0\n target = -1\n for key, val in freq.items():\n if val > max_freq:\n max_freq = val\n target = key\n elif val == max_freq:\n if key < target:\n target = key\n return target\n \n store = {}\n\n for num in nums:\n r = num%space\n if r not in store:\n store[r] = (1, num)\n else:\n count, min_seed = store[r]\n store[r] = (count+1, min(min_seed, num))\n \n max_count = 0\n min_seed = inf\n for key, val in store.items():\n count, seed = val\n if count > max_count:\n max_count = count\n min_seed = seed\n elif count == max_count:\n min_seed = min(min_seed, seed)\n \n return min_seed\n \n \n```
0
0
['Hash Table', 'Python3']
0
destroy-sequential-targets
Destroy Sequential Targets
destroy-sequential-targets-by-ananytomar-s0bz
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
ananytomar01
NORMAL
2023-12-04T18:56:37.900602+00:00
2023-12-04T18:56:37.900629+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 {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n int n = nums.size();\n int c =0;\n map<int,int>map;\n for(int i=0;i<n;i++)\n {\n map[nums[i]%space]++;\n c = max(map[nums[i]%space],c);\n }\n int ans = INT_MAX;\n for(int i=0;i<n;i++)\n {\n if(map[nums[i]%space] == c)\n ans = min(nums[i],ans);\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
Count maximum frequency of (nums[i] % space) || INTUITION Explained
count-maximum-frequency-of-numsi-space-i-w0zl
Intuition\n\nIf we select nums[i] as a seed, \nthan all nums[index] will get destroyed given\n"nums[index] = nums[i] + c * space"\non performing "modulo space"
coder_rastogi_21
NORMAL
2023-12-02T11:29:38.281084+00:00
2023-12-02T11:29:38.281107+00:00
2
false
# Intuition\n```\nIf we select nums[i] as a seed, \nthan all nums[index] will get destroyed given\n"nums[index] = nums[i] + c * space"\non performing "modulo space" on both sides\nnums[index] % space = (nums[i] + c * space) % space\nnums[index] % space = nums[i] % space\nThus, they both have same remainders.\n//---------------------------------------//\nSo, problem gets decomped to\nIf val%space is stored for all values in nums,\nthen find smallest number such that (number % space) is maximized.\n```\n\n# Complexity\n- Time complexity: $$O(n)$$ \n\n- Space complexity: $$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n unordered_map<int,int> remainder;\n int maxi = 0, ans = INT_MAX;\n\n for(int i=0; i<nums.size(); i++)\n {\n remainder[nums[i] % space]++; //update frequency of remainders\n maxi = max(maxi,remainder[nums[i] % space]); //store max frequency found\n }\n \n for(auto it : nums)\n { //for all values of nums[i] having largest remainder frequency\n if(remainder[it % space] == maxi) \n ans = min(ans,it); //take smallest among them as seed\n }\n return ans;\n }\n};\n```
0
0
['Hash Table', 'C++']
0
destroy-sequential-targets
Clever
clever-by-user3043sb-dzqg
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
user3043SB
NORMAL
2023-11-29T08:19:11.804370+00:00
2023-11-29T08:19:11.804398+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```\nimport java.util.*;\n\npublic class Solution {\n\n// public int destroyTargets(int[] nums, int space) {\n// int n = nums.length;\n// HashMap<Integer, Integer> leftoverToCnt = new HashMap<>();\n// int maxCnt = 1;\n// for (int i = 0; i < n; i++) {\n// int lftOvr = nums[i] % space;\n// int newCnt = leftoverToCnt.getOrDefault(lftOvr, 0) + 1;\n// leftoverToCnt.put(lftOvr, newCnt);\n// maxCnt = Math.max(maxCnt, newCnt);\n// }\n//\n// int minElem = Integer.MAX_VALUE;\n// for (int num : nums) {\n// int lftOvr = num % space;\n// if (leftoverToCnt.get(lftOvr) == maxCnt) {\n// minElem = Math.min(minElem, num);\n// }\n// }\n//\n// return minElem;\n// }\n\n // IDEA: (C + x * space) means we can take % space of each elem to get\n // the residual/leftover that we want C, then we need to find that C in arr\n // to subtract and destroy the target completely!\n\n // Step 1: Count freq of each LEFTOVER (num % space) = targetC\n // Step 2: Find the SMALLEST elem that cancels MOST targetC\'s (freq)\n // We actually do not need to know the TRUE number of elems being cancelled!\n // We only need to group elems based on their LEFTOVER and find the SMALLEST\n // elem in each group! This DOESN\'T MEAN the whole group will be cancelled by the\n // elem!!! e.g.\n // [3,5,6] space = 2 -> map into:\n // [1,1,0]\n // {1 -> 2, 0 -> 1} leftovers\n // Result = 3; smallest elem from most frequent group!\n // But it only cancels 1 TARGET, even though it\'s in group of 2!\n\n // ONE PASS VERSION:\n public int destroyTargets(final int[] nums, int space) {\n Map<Integer, int[]> cnt = new HashMap();\n int[] ans = new int[]{0, Integer.MAX_VALUE};\n for(int num: nums){\n int[] entry = cnt.computeIfAbsent(num % space, k -> new int[]{0, num});\n entry[0] += 1;\n entry[1] = Math.min(num, entry[1]);\n if(entry[0] > ans[0])\n ans = entry;\n else if(entry[0] == ans[0] && entry[1] < ans[1])\n ans = entry;\n }\n return ans[1];\n }\n}\n\n```
0
0
['Java']
0
destroy-sequential-targets
O(n) time complexity solution
on-time-complexity-solution-by-tus_tus-fych
Intuition\n Describe your first thoughts on how to solve this problem. \n\nWe need to find the remainder of each value with space.\n\nNow, we need to find that
Tus_Tus
NORMAL
2023-11-23T16:32:02.898786+00:00
2023-11-23T16:32:02.898815+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nWe need to find the remainder of each value with space.\n\nNow, we need to find that minimum number whose remainder\'s frequency is maximum . \n\n# Code\n```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n \n int n = nums.size();\n unordered_map<int,int>rem;\n\n for(int i = 0; i < n; i++) {\n rem[nums[i] % space]++;\n }\n\n int maxiFreqRem = 0;\n\n for(auto it : rem) {\n if(it.second > maxiFreqRem) {\n maxiFreqRem = it.second;\n }\n }\n\n int ans = 1e9 + 1;\n\n for(int i = 0; i < n; i++) {\n \n int remain = nums[i] % space;\n if(rem[remain] == maxiFreqRem) {\n ans = min(ans, nums[i]);\n }\n\n }\n\n return ans;\n \n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
One Pass O(n) C# Solution
one-pass-on-c-solution-by-mark0960-xlf2
Intuition\nWe will need to use modulo (%) to determine whict targets get destroyed in the same seed.\n\n# Approach\n1. Dictionary<modulo, (min, count)> will sto
Mark0960
NORMAL
2023-10-21T09:46:25.035792+00:00
2023-10-21T09:46:25.035819+00:00
7
false
# Intuition\nWe will need to use modulo (%) to determine whict targets get destroyed in the same seed.\n\n# Approach\n1. `Dictionary<modulo, (min, count)>` will store each modulo and its occurrences and minimum num.\n2. Iterate nums and get modulo of each num.\n3. Update count and minimum num per modulo in the Dictionary.\n4. Update the best modulo found based on max count then minimum num.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\npublic class Solution {\n public int DestroyTargets(int[] nums, int space) {\n Dictionary<int, (int min, int count)> dict = new();\n dict.Add(-1, (-1, 0));\n int bestSeedKey = -1;\n\n foreach(int num in nums)\n {\n int mod = num % space;\n if(dict.TryGetValue(mod, out (int min, int count) currentSeedValue))\n {\n currentSeedValue = (Math.Min(currentSeedValue.min, num), currentSeedValue.count + 1);\n }\n else\n {\n currentSeedValue = (num, 1);\n }\n\n dict[mod] = currentSeedValue;\n\n (int min, int count) bestSeedValue = dict[bestSeedKey];\n if(bestSeedValue.count < currentSeedValue.count)\n {\n bestSeedKey = mod;\n }\n else if(bestSeedValue.count == currentSeedValue.count &&\n bestSeedValue.min > currentSeedValue.min)\n {\n bestSeedKey = mod;\n }\n }\n\n return dict[bestSeedKey].min;\n }\n}\n```
0
0
['C#']
0
destroy-sequential-targets
Ruby solution using Modulo
ruby-solution-using-modulo-by-ksodha93-t6vh
Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \nO(n) -> O(nlogn) because sorting\n\n- Space complexity:\n Add your space complexity
ksodha93
NORMAL
2023-10-02T20:10:00.979991+00:00
2023-10-02T20:10:00.980017+00:00
2
false
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) -> O(nlogn) because sorting\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\n# @param {Integer[]} nums\n# @param {Integer} space\n# @return {Integer}\ndef destroy_targets(nums, space)\n hash = Hash.new(0)\n nums.each do |i|\n hash[(i % space)] += 1\n end\n\n max_value = hash.values.max\n\n nums.sort.each do |i|\n if hash[(i % space)] == max_value\n return i\n end\n end\nend\n```
0
0
['Ruby']
0
destroy-sequential-targets
Brute to best : A smooth shift towards best solution - Explanation with full Intuition.
brute-to-best-a-smooth-shift-towards-bes-zt77
2453. Destroy Sequential Targets\n\n## Brute Force Approach :-\n- So try to use every ele as seed and keep count of how many ele has been destroied with that se
hiimvikash
NORMAL
2023-09-19T19:13:39.533866+00:00
2023-09-19T19:13:39.533898+00:00
11
false
# [2453. Destroy Sequential Targets](https://leetcode.com/problems/destroy-sequential-targets/description/)\n\n## Brute Force Approach :-\n- So try to use every ele as seed and keep count of how many ele has been destroied with that seed and keep track of ur minimum seed which destroied maximum ele in nums[].\n![image.png](https://assets.leetcode.com/users/images/92ad9d2e-2e4a-46ca-95d1-6aa08a00a215_1695150603.0014324.png)\n```java\nclass Solution {\n public int destroyTargets(int[] nums, int space) {\n int n = nums.length;\n if(n==1) return nums[0];\n\n int ans = Integer.MAX_VALUE;\n int td = 0;\n for(int i = 0; i<nums.length; i++){\n int seed = nums[i];\n int targetDestroyed = 0;\n for(int j = 0; j<nums.length; j++){\n if((nums[j]-seed)%space == 0) targetDestroyed++;\n }\n if(targetDestroyed == td) ans = Math.min(ans,seed);\n else if(targetDestroyed > td){\n ans = seed;\n td = targetDestroyed;\n }\n }\n return ans;\n }\n}\n```\n## Optimised Approach\n![image.png](https://assets.leetcode.com/users/images/cc45553f-cb26-4a20-888f-ac193e92c90b_1695150638.385468.png)\n```java\nclass Solution {\n public int destroyTargets(int[] nums, int space) {\n HashMap<Integer, Integer> hm=new HashMap<>();\n int mf = 0;\n for(int ele : nums){ \n hm.put(ele%space, hm.getOrDefault(ele%space,0)+1);\n mf = Math.max(mf, hm.get(ele%space));\n }\n \n int ans = (int)1e9+1;\n for(int ele :nums){\n if(hm.get(ele%space) == mf){\n ans = Math.min(ele,ans);\n }\n }\n return ans;\n }\n}\n```
0
0
['Java']
0
destroy-sequential-targets
Python beats 100% using hashmap and modulos
python-beats-100-using-hashmap-and-modul-dcxz
Intuition\n Describe your first thoughts on how to solve this problem. \nIt all boils down to see what is the modulo of space that appears the most time.\n\n# A
poss03
NORMAL
2023-09-18T08:29:58.954573+00:00
2023-09-18T08:29:58.954600+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt all boils down to see what is the modulo of `space` that appears the most time.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each number, compute the modulo of it, and update the dictionary, then you know what is the most frequent. Then, you see which of the item with this modulo is the smaller\n\n# Complexity\n- Time complexity:\n$$O(n)$$ \n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def destroyTargets(self, nums: List[int], space: int) -> int:\n mods = {}\n for num in nums:\n mods[num%space] = mods.get(num%space, 0) + 1\n maxV = max(mods.values())\n res = float(\'inf\')\n for num in nums:\n if mods[num%space] == maxV:\n res = min(res, num)\n\n return res\n```
0
0
['Python3']
0
destroy-sequential-targets
Python Solution Using modulo in O(n) and O(n)
python-solution-using-modulo-in-on-and-o-mdi1
Code\n\nclass Solution:\n def destroyTargets(self, nums: List[int], space: int) -> int:\n d={}\n for item in nums:\n r=item%space\n
ng2203
NORMAL
2023-09-06T17:13:34.921152+00:00
2023-09-06T17:13:34.921172+00:00
2
false
# Code\n```\nclass Solution:\n def destroyTargets(self, nums: List[int], space: int) -> int:\n d={}\n for item in nums:\n r=item%space\n if(r in d):\n d[r]+=1\n else:\n d[r]=1\n ans=nums[0]\n c=d[ans%space]\n for item in nums:\n if(c<d[item%space] or (c==d[item%space] and item<ans)):\n c=d[item%space]\n ans=item\n return ans\n```
0
0
['Python3']
0
destroy-sequential-targets
✅✅C++ Simple solution || Unordered_map || Explanation || O(n).
c-simple-solution-unordered_map-explanat-xm8r
EXPLANATION\nAt first we created an unordered_map.\nWe traverse in the given vector nums.\nWe checked if the mod of that number with space is in map or not, the
praegag
NORMAL
2023-09-03T06:53:12.398686+00:00
2023-09-03T06:53:12.398713+00:00
6
false
# EXPLANATION\nAt first we created an unordered_map.\nWe traverse in the given vector **nums**.\nWe checked if the mod of that number with **space** is in map or not, then we insert in it, or if present then we update it with **increased count and min number, as a pair**.\nSet **s=-1 and ans=INT_MAX.**\nAfter this we traverse in the map **m**.\nChecked if pair\'s first is greater than **s**, if so then we update **s** and **ans**.\nIf it is same as **s** then we update **ans** with minimum value.\nFinally return **ans** as answer.\n# SOLUTION\n```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n unordered_map<int,pair<int,int>> m;\n for(auto x:nums){\n int i=x%space;\n if(m.count(i)){\n int a=m[i].first,b=m[i].second;\n b=min(x,b);\n m[i]={++a,b};\n }\n else\n m[i]={1,x};\n }\n int s=-1,ans=INT_MAX;\n for(auto x:m){\n if(x.second.first==s)\n ans=min(ans,x.second.second);\n else if(x.second.first>s){\n s=x.second.first;\n ans=x.second.second;\n }\n }\n return ans;\n }\n};\n```
0
0
['Array', 'Hash Table', 'Counting', 'C++']
0
destroy-sequential-targets
Easy || Based on remainder intuition
easy-based-on-remainder-intuition-by-g_k-5qlq
Intuition\nstore the remainder of every number when divided by space.\nThe highest number of same remainder will be our answer.\nfor handelling the stiuations w
g_ky
NORMAL
2023-08-31T17:54:20.392810+00:00
2023-08-31T17:54:20.392839+00:00
4
false
# Intuition\nstore the remainder of every number when divided by space.\nThe highest number of same remainder will be our answer.\nfor handelling the stiuations where there is more than one highest then store all those in a set.\n\n\n\n# Complexity\n- Time complexity:\no(n)\n\n- Space complexity:\no(n)\n# Code\n```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n unordered_map<int,int>mp;\n\n for(int i=0;i<nums.size();i++)\n {\n mp[nums[i]%space]++;\n }\n\n int maxi=INT_MIN;\n \n unordered_set<int>st;\n for(auto it:mp)\n {\n if(it.second>maxi)\n {\n maxi=it.second;\n \n }\n }\n\n for(auto it:mp)\n {\n if(it.second==maxi)\n st.insert(it.first);\n }\n \n int ans=INT_MAX;\n\n for(auto it:nums)\n {\n if(st.find(it%space)!=st.end())\n ans=min(ans,it);\n }\n return ans;\n\n \n }\n};\n```
0
0
['Ordered Map', 'C++']
0
destroy-sequential-targets
Easiest cpp code :) Best from rest
easiest-cpp-code-best-from-rest-by-sanya-uf5j
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
sanyam46
NORMAL
2023-08-26T17:55:20.887917+00:00
2023-08-26T17:55:20.887948+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 {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n //sort(nums.begin() , nums.end());\n unordered_map<int , int> ump;\n int min_val = 1e9;\n int max_count = 0;\n for(int num: nums)\n {\n ump[num%space]++;\n max_count = max(max_count , ump[num%space]);\n }\n for(const int num: nums)\n {\n if(ump[num%space]==max_count)\n {\n min_val = min(num , min_val);\n }\n }\n \n return min_val;\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
Easy to Understand Python Solution
easy-to-understand-python-solution-by-sr-g6wi
Intuition\n Describe your first thoughts on how to solve this problem. \nYou can destroy all targets $x$ with seed $y$ with $x \equiv y \left(\mod \text{space}\
srihariv
NORMAL
2023-08-17T01:59:30.427825+00:00
2023-08-17T01:59:30.427848+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou can destroy all targets $x$ with seed $y$ with $x \\equiv y \\left(\\mod \\text{space}\\right)$ i.e. with the same modulus.\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$ - Two passes of the list (could be done in one pass too if needed)\n\n- Space complexity:\n$$O(space)$$ - We store at most $space$ integers in the Counter\n\n# Code\n```\nclass Solution:\n def destroyTargets(self, nums: List[int], space: int) -> int:\n counts, best = Counter(), 0\n for x in nums:\n counts[x % space] += 1\n best = max(best, counts[x % space])\n return min(x for x in nums if counts[x % space] == best)\n\n```
0
0
['Python3']
0
destroy-sequential-targets
c++ solution using sort and map
c-solution-using-sort-and-map-by-tiandin-m194
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
tiandingz
NORMAL
2023-08-10T22:12:42.568920+00:00
2023-08-10T22:15:23.428933+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 {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n unordered_map<int,int> m;\n // sort nums to make sure the last number can destroy the maximunm number of target (number of % space) is minimum\n sort(nums.begin(), nums.end(),greater<int>());\n int ans;\n int max_count = 0;\n for(int i = 0; i < nums.size(); i++) {\n m[nums[i] % space]++;\n if (m[nums[i] % space] >= max_count){ // as long as we have a equal or lager numbers of target with same modulo, change it to the smaller one\n max_count = m[nums[i] % space];\n ans = nums[i];\n }\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
C++ hashing O(n)
c-hashing-on-by-gagapoopoo-y9o9
```\nclass Solution {\npublic:\n int destroyTargets(vector& nums, int space) {\n \n unordered_map,greater\>> ourmap;\n int n=nums.size()
Gagapoopoo
NORMAL
2023-08-02T19:23:03.073139+00:00
2023-08-02T19:23:03.073159+00:00
2
false
```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n \n unordered_map<int,priority_queue<int,vector<int>,greater<int>>> ourmap;\n int n=nums.size();\n for(int i=0;i<n;i++){\n int rem=nums[i]%space;\n ourmap[rem].push(nums[i]);\n }\n auto it=ourmap.begin();\n int maxi=-1e9;\n while(it!=ourmap.end()){\n int num=it->second.size();\n maxi=max(maxi,num);\n it++;\n }\n it=ourmap.begin();\n int ans=1e9;\n while(it!=ourmap.end()){\n if(it->second.size()==maxi){\n priority_queue<int,vector<int>,greater<int>> minheap=it->second;\n ans=min(ans,minheap.top());\n }\n it++;\n }\n return ans;\n }\n};
0
0
[]
0
destroy-sequential-targets
:: Kotlin :: Sorting Solution
kotlin-sorting-solution-by-znxkznxk1030-t1t0
\nclass Solution {\n fun destroyTargets(nums: IntArray, space: Int): Int {\n val modulo = HashMap<Int, Int>()\n var mod = 0\n\n for (num
znxkznxk1030
NORMAL
2023-08-02T08:09:19.539924+00:00
2023-08-02T08:09:19.539944+00:00
2
false
```\nclass Solution {\n fun destroyTargets(nums: IntArray, space: Int): Int {\n val modulo = HashMap<Int, Int>()\n var mod = 0\n\n for (num in nums) {\n val m = num % space\n modulo.put(m, modulo.getOrDefault(m, 0) + 1)\n }\n\n var max = modulo.values.max()!!\n var modList = mutableListOf<Int>()\n\n for ((k, v) in modulo) {\n if (v == max) modList.add(k)\n }\n\n Arrays.sort(nums)\n for (num in nums) {\n for (mod in modList) {\n if (num % space == mod) return num\n }\n }\n\n return -1\n }\n}\n```
0
0
['Kotlin']
0
destroy-sequential-targets
C++ Short | O(N)/O(N) time/space
c-short-onon-timespace-by-skoparov-tzha
All numbers that can be destroyed with a seed share the common modulo. We just need to count them and keep the minimum value for them as well as the overall max
skoparov
NORMAL
2023-07-31T14:47:50.567330+00:00
2023-07-31T14:47:50.567361+00:00
4
false
All numbers that can be destroyed with a seed share the common modulo. We just need to count them and keep the minimum value for them as well as the overall max count/min value.\n```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) \n { \n int maxCnt{ 0 };\n int minVal{ 0 };\n unordered_map<int, pair<size_t, int>> moduloCnt;\n\n for (size_t i{ 0 }; i < nums.size(); ++i)\n {\n auto& [cnt, val]{ moduloCnt[nums[i] % space] };\n if (!exchange(cnt, cnt + 1) || val > nums[i])\n val = nums[i];\n\n if (maxCnt < cnt || (maxCnt == cnt && val < minVal))\n tie(maxCnt, minVal) = tie(cnt, val);\n }\n\n return minVal;\n }\n};\n```
0
0
['C++']
0
destroy-sequential-targets
C++ | Easy to understand approach
c-easy-to-understand-approach-by-khanhtc-ygiv
Intuition\n Describe your first thoughts on how to solve this problem. \nSince num = seed + c * space, numbers will be marked as destroied targets by the same s
khanhtc
NORMAL
2023-07-25T09:30:34.965446+00:00
2023-07-25T09:30:34.965464+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince `num = seed + c * space`, numbers will be marked as destroied targets by the same seed if `num % space` is the same ( = seed ).\n\nWe will count those numbers and return the smallest one as the answer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nHave to build a hashmap of type `unordered_map<int, pair<int, int>>` which \n- key is the seed (`num % space`)\n- value is pair of `{how many number in nums has same seed, smallest number which accepts seed}`\n\nThen iterate through the hashmap and get the answer.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSince we iterate through the input to build hashmap, then iterate through hashmap to get the answer.\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nHashmap space.\n\n# Code\n```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) {\n unordered_map<int, pair<int, int>> memo;\n int remainder, targets = INT_MIN;\n for (auto num: nums) {\n remainder = num % space;\n if (memo.find(remainder) == memo.end()) {\n memo[remainder] = make_pair(1, num);\n } else {\n memo[remainder] = make_pair(memo[remainder].first+1, min(memo[remainder].second, num));\n }\n targets = max(targets, memo[remainder].first);\n }\n\n int ans = INT_MAX;\n for (auto [k, v]: memo) {\n if (v.first == targets) {\n ans = min(ans, v.second);\n }\n }\n return ans;\n }\n};\n```
0
0
['Array', 'Hash Table', 'C++']
0
destroy-sequential-targets
C++ Solution using Hashmap and Sorting
c-solution-using-hashmap-and-sorting-by-s81ha
Intuition\n Describe your first thoughts on how to solve this problem. \nCan approach the problem statement with a Mathematical equation and then try to hash th
deaththunder333
NORMAL
2023-07-21T12:17:38.779985+00:00
2023-07-21T12:17:38.780008+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCan approach the problem statement with a Mathematical equation and then try to hash the maxiumum frequency of the desired answer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIf any number x is representable in the form => y + factor*space \nThen, (x - y)/space; so (x - y)%space == 0, so (x % space == y).\n\nFor each nums[i]; store (nums[i]%space) in a hashmap and then find the maximum frequency count amongst all hashed values. Now find the smallest nums[i] by traversing through the array; that has the count of (nums[i]%space) == Maximum Frequency of all possible (nums[i]%space).\n\n# Complexity\n- Time complexity: O(nlogn)\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 int destroyTargets(vector<int>& nums, int space) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n // if any number x is representable in the form => y + factor*space\n // (x - y)/space; so (x - y)%space == 0, so (x % space == y)\n map<int, int> mp;\n int mx_cnt = INT_MIN, rem;\n for(int i = 0; i < n; i++){\n mp[nums[i]%space]++;\n if(mx_cnt < mp[nums[i]%space]){\n mx_cnt = max(mx_cnt, mp[nums[i]%space]);\n rem = nums[i]%space;\n }\n }\n //cout<<mx_cnt<<" "<<rem<<endl;\n int ans = INT_MAX;\n for(int i = 0; i < n; i++){\n if(mp[nums[i]%space] == mx_cnt){\n ans = nums[i];\n break;\n }\n }\n return ans;\n }\n};\n```
0
0
['Hash Table', 'Sorting', 'C++']
0
destroy-sequential-targets
🔥🔥Destroy Sequential Targets 🔥🔥With Comments🔥🔥 Easy Approach 🔥🔥 Simple & Fast
destroy-sequential-targets-with-comments-5pzq
\n\n# Code\n\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) \n {\n int ans = INT_MAX;\n int mx = INT_MIN;\n
_sinister_
NORMAL
2023-07-21T06:39:31.160503+00:00
2023-07-21T06:39:31.160533+00:00
3
false
\n\n# Code\n```\nclass Solution {\npublic:\n int destroyTargets(vector<int>& nums, int space) \n {\n int ans = INT_MAX;\n int mx = INT_MIN;\n unordered_map<int, int> mp;\n\n for(auto n: nums)\n {\n int r = n % space; //evaluate reminder\n mp[r]++; // add reminder to map\n if(mx < mp[r])\n {\n mx = mp[r];\n } //keep track of the max count, with same reminder\n }\n for(auto n: nums)\n { //scan smalest element with same riminder as of mx\n if(mx == mp[n%space])\n {\n ans = min(ans, n);\n }\n }\n return ans;\n }\n};\n```
0
0
['Array', 'Hash Table', 'Counting']
0
destroy-sequential-targets
[JavaScript] Easy Understaning Solution!
javascript-easy-understaning-solution-by-x4my
Code\n\n/**\n * @param {number[]} nums\n * @param {number} space\n * @return {number}\n */\nvar destroyTargets = function(nums, space) {\n nums.sort((a, b) =
nguyennhuhung72
NORMAL
2023-07-17T06:56:21.869979+00:00
2023-07-17T06:56:21.870001+00:00
9
false
# Code\n```\n/**\n * @param {number[]} nums\n * @param {number} space\n * @return {number}\n */\nvar destroyTargets = function(nums, space) {\n nums.sort((a, b) => a - b);\n let m = new Map(), res = 0, cnt = 0;\n for (let i = 0; i < nums.length; i++){\n if (m.get(nums[i] % space))\n m.set(nums[i] % space, m.get(nums[i] % space) + 1);\n else \n m.set(nums[i] % space, 1);\n if (cnt < m.get(nums[i] % space)){\n cnt = m.get(nums[i] % space);\n } \n }\n\n for (let i = 0; i < nums.length; i++){\n if (m.get(nums[i] % space) === cnt){\n res = nums[i];\n break;\n }\n }\n \n return res;\n};\n```
0
0
['Hash Table', 'JavaScript']
0
length-of-longest-v-shaped-diagonal-segment
[Python] DP
python-dp-by-lee215-gtub
ExplanationDFS with memo. Current position (i, j), the value to search x, where x = 0,1,2 the direction indice d, where direction is [[1,1],[1,-1],[-1,-1],[-1,1
lee215
NORMAL
2025-02-16T04:19:09.755926+00:00
2025-02-16T06:27:57.122333+00:00
1,917
false
# **Explanation** DFS with memo. Current position `(i, j)`, the value to search `x`, where `x = 0,1,2` the direction indice `d`, where direction is `[[1,1],[1,-1],[-1,-1],[-1,1]]` and `k` is the time to turn. # **Complexity** Time and Space `O(m * n * 3 * 4 * 2)` <br> ```py [Python3] def lenOfVDiagonal(self, g: List[List[int]]) -> int: @cache def dp(i,j,x,d,k): if not (0 <= i < n and 0 <= j < m): return 0 if g[i][j] != x: return 0 res = dp(i + ds[d][0], j + ds[d][1], nx[x], d, k) + 1 if k > 0: d2 = (d + 1) % 4 res2 = dp(i + ds[d2][0], j + ds[d2][1], nx[x], d2, 0) + 1 res = max(res, res2) return res ds = [[1,1],[1,-1],[-1,-1],[-1,1]] nx = [2,2,0] res = 0 n, m = len(g), len(g[0]) for i in range(n): for j in range(m): if g[i][j] == 1: cur = max(dp(i, j, 1, d, 1) for d in range(4)) res = max(res, cur) return res ``` # More DP problems Here is small DP problem list. Good luck and have fun. - [3459. Length of Longest V-Shaped Diagonal Segment](https://leetcode.com/problems/length-of-longest-v-shaped-diagonal-segment/solutions/6427839/python-dp/) - [3363. Find the Maximum Number of Fruits Collected](https://leetcode.com/problems/find-the-maximum-number-of-fruits-collected/discuss/6075890/JavaC%2B%2BPython-First-child-go-diagonal) - [3352. Count K-Reducible Numbers Less Than N](https://leetcode.com/problems/count-k-reducible-numbers-less-than-n/discuss/6028638/JavaC%2B%2BPython-DP) - [3351. Sum of Good Subsequences](https://leetcode.com/problems/sum-of-good-subsequences/discuss/6028686/JavaC%2B%2BPython-DP) - [3336. Find the Number of Subsequences With Equal GCD](https://leetcode.com/problems/find-the-number-of-subsequences-with-equal-gcd/discuss/5973616/JavaC%2B%2BPython-2D-DP) - [3335. Total Characters in String After Transformations I](https://leetcode.com/problems/total-characters-in-string-after-transformations-i/discuss/5973021/Python-DP) - [3316. Find Maximum Removals From Source String](https://leetcode.com/problems/find-maximum-removals-from-source-string/discuss/5904277/JavaC%2B%2BPython-DP) - [3202. Find the Maximum Length of Valid Subsequence II](https://leetcode.com/problems/find-the-maximum-length-of-valid-subsequence-ii/discuss/5389350/JavaC%2B%2BPython-1d-DP) - [3193. Count the Number of Inversions](https://leetcode.com/problems/count-the-number-of-inversions/discuss/5353127/Python-DP) - [3177. Find the Maximum Length of a Good Subsequence II](https://leetcode.com/problems/find-the-maximum-length-of-a-good-subsequence-ii/discuss/5280172/JavaC%2B%2BPython-DP-Solution) - [3148. Maximum Difference Score in a Grid](https://leetcode.com/problems/maximum-difference-score-in-a-grid/discuss/5145704/JavaC%2B%2BPython-Minimum-on-Top-Left) - [3147. Taking Maximum Energy From the Mystic Dungeon](https://leetcode.com/problems/taking-maximum-energy-from-the-mystic-dungeon/discuss/5145723/JavaC%2B%2BPython-DP) - [2920. Maximum Points After Collecting Coins From All Nodes](https://leetcode.com/problems/maximum-points-after-collecting-coins-from-all-nodes/discuss/4220643/JavaC%2B%2BPython-DP) - [2919. Minimum Increment Operations to Make Array Beautiful](https://leetcode.com/problems/minimum-increment-operations-to-make-array-beautiful/discuss/4220717/JavaC%2B%2BPython-Easy-and-Concise-DP-O(1)-Space) - [2896. Apply Operations to Make Two Strings Equal](https://leetcode.com/problems/apply-operations-to-make-two-strings-equal/discuss/4144041/JavaC%2B%2BPython-DP-One-Pass-O(1)-Space) - [2830. Maximize the Profit as the Salesman](https://leetcode.com/problems/maximize-the-profit-as-the-salesman/discuss/3934188/JavaC%2B%2BPython-DP) - [2008. Maximum Earnings From Taxi](https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1470941/JavaC%2B%2BPython-DP-solution) - [1751. Maximum Number of Events That Can Be Attended II](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/discuss/1052581/Python-DP) - [1235. Maximum Profit in Job Scheduling](https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/409009/Python-DP-Solution)
15
0
['Dynamic Programming', 'Depth-First Search', 'Python3']
2
length-of-longest-v-shaped-diagonal-segment
simple DP solution in c++:
simple-dp-solution-in-c-by-vijay_15-bijq
IntuitionApproachComplexity Time complexity: Space complexity: Code
vijay_15
NORMAL
2025-02-16T05:33:55.683373+00:00
2025-02-17T09:16:31.098205+00:00
1,174
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 ```cpp [] class Solution { public: int dp[501][501][2][2][5]; int n , m; int solve(int r , int c , int turn , int curr , int dir , vector<vector<int>>& grid){ if(r == n || c == m || r < 0 || c < 0)return 0; if(dp[r][c][turn][curr][dir] != -1)return dp[r][c][turn][curr][dir]; if(curr && grid[r][c] != 2)return 0; if(!curr && grid[r][c] != 0)return 0; int ans = 0; // 1 - top right , 2 - bottom right , 3 - bottom left , 4 - top left if(dir == 1){ ans = 1 + solve(r - 1 , c + 1 , turn , !curr , 1 , grid); if(!turn)ans = max(ans ,1 + solve(r + 1 , c + 1 , 1 , !curr , 2 , grid)); } if(dir == 2){ ans = 1 + solve(r + 1 , c + 1 , turn , !curr , 2 , grid); if(!turn)ans = max(ans ,1 + solve(r + 1 , c - 1 , 1 , !curr , 3 , grid)); } if(dir == 3){ ans = 1 + solve(r + 1 , c - 1 , turn , !curr , 3 , grid); if(!turn)ans = max(ans ,1 + solve(r - 1 , c - 1 , 1 , !curr , 4 , grid)); } if(dir == 4){ ans = 1 + solve(r - 1 , c - 1 , turn , !curr , 4 , grid); if(!turn)ans = max(ans ,1 + solve(r - 1 , c + 1 , 1 , !curr , 1 , grid)); } return dp[r][c][turn][curr][dir] = ans; } int lenOfVDiagonal(vector<vector<int>>& grid) { n = grid.size() , m = grid[0].size(); memset(dp , -1 ,sizeof(dp)); int ans = 0; for(int i = 0 ; i < n ; i++){ for(int j = 0 ; j < m ; j++){ if(grid[i][j] == 1){ ans = max(ans , 1+ solve(i + 1 , j + 1 , 0 , 1 , 2 , grid)); ans = max(ans , 1+ solve(i - 1 , j + 1 , 0 , 1 , 1 , grid)); ans = max(ans , 1+ solve(i + 1 , j - 1 , 0 , 1 , 3 , grid)); ans = max(ans , 1+ solve(i - 1 , j - 1 , 0 , 1 , 4 , grid)); } } } return ans; } }; ```
10
1
['Dynamic Programming', 'C++']
2
length-of-longest-v-shaped-diagonal-segment
Concise Java DFS
concise-java-dfs-by-czahie-kc9z
Code
czahie
NORMAL
2025-02-16T04:25:36.652131+00:00
2025-02-16T04:28:21.012794+00:00
639
false
# Code ```java [] class Solution { int[][] dirs = new int[][]{{-1, 1}, {1, 1}, {1, -1}, {-1, -1}}; int[][] grid; int m, n; public int lenOfVDiagonal(int[][] grid) { m = grid.length; n = grid[0].length; this.grid = grid; int res = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) { res = Math.max(res, 1); res = Math.max(res, dfs(i, j, 0, 2, false)); res = Math.max(res, dfs(i, j, 1, 2, false)); res = Math.max(res, dfs(i, j, 2, 2, false)); res = Math.max(res, dfs(i, j, 3, 2, false)); } } } return res; } public int dfs(int i, int j, int dir, int target, boolean turned) { int x = i + dirs[dir][0], y = j + dirs[dir][1]; if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] != target) { return 1; } int straight = 1 + dfs(x, y, dir, target == 2 ? 0 : 2, turned); int turn = 0; if (!turned) { turn = 1 + dfs(x, y, (dir + 1) % 4, target == 2 ? 0 : 2, true); } return Math.max(straight, turn); } } ```
6
0
['Depth-First Search', 'Java']
2
length-of-longest-v-shaped-diagonal-segment
It's Not Hard..!
its-not-hard-by-senorita143-49va
IntuitionThe approach uses DFS with memoization to explore "V" shaped paths starting from each 1 in the grid, alternating between 2 and 0 at each step. It recur
senorita143
NORMAL
2025-02-16T06:07:28.472672+00:00
2025-02-16T06:07:28.472672+00:00
377
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The approach uses DFS with memoization to explore "V" shaped paths starting from each 1 in the grid, alternating between 2 and 0 at each step. It recursively checks all four diagonal directions while ensuring only one turn is made, maximizing the length of valid paths. # Approach <!-- Describe your approach to solving the problem. --> 1. Start DFS from Every 1 in the Grid - Try forming a "V" shape using diagonal movements. 2. Use DFS with Memoization - Move diagonally, alternating between 2 and 0. - Allow one direction change to form a "V". - Store results to avoid redundant calculations. 3. Explore Four Diagonal Directions - Top-left, top-right, bottom-left, bottom-right. - Continue in the same direction or turn once. 4. Track the Maximum Length - Keep updating the longest valid "V" path found. 5. Return the Longest Path Length - The final result is the longest "V" found in the grid. # Complexity - Time complexity: O(n*m) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n*m) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: n, m = len(grid), len(grid[0]) # Get the dimensions of the grid @cache # Memoization to optimize recursive calls def dfs(row, col, turn, direction, target): # Base case: Check boundaries and if the cell matches the target value if row not in range(n) or col not in range(m) or grid[row][col] != target: return 0 # Toggle the target between 2 and 0 after each step target = 0 if grid[row][col] == 2 else 2 # Move diagonally based on the direction if direction == 0: # Top-left diagonal if turn: return 1 + max(dfs(row - 1, col - 1, turn, 0, target), dfs(row - 1, col + 1, False, 1, target)) return 1 + dfs(row - 1, col - 1, turn, 0, target) elif direction == 1: # Top-right diagonal if turn: return 1 + max(dfs(row - 1, col + 1, turn, 1, target), dfs(row + 1, col + 1, False, 2, target)) return 1 + dfs(row - 1, col + 1, turn, 1, target) elif direction == 2: # Bottom-right diagonal if turn: return 1 + max(dfs(row + 1, col + 1, turn, 2, target), dfs(row + 1, col - 1, False, 3, target)) return 1 + dfs(row + 1, col + 1, turn, 2, target) else: # Bottom-left diagonal if turn: return 1 + max(dfs(row + 1, col - 1, turn, 3, target), dfs(row - 1, col - 1, False, 0, target)) return 1 + dfs(row + 1, col - 1, turn, 3, target) longest_v = 0 # Variable to store the longest V-diagonal length # Iterate through the grid to find starting points (cells with value 1) for i in range(n): for j in range(m): if grid[i][j] == 1: # Start DFS in all four diagonal directions longest_v = max(longest_v, 1 + max(dfs(i - 1, j - 1, True, 0, 2), # Top-left dfs(i - 1, j + 1, True, 1, 2), # Top-right dfs(i + 1, j + 1, True, 2, 2), # Bottom-right dfs(i + 1, j - 1, True, 3, 2))) # Bottom-left return longest_v ``` **Clean Code:** ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: n,m = len(grid), len(grid[0]) @cache def dfs(row,col,turn, direction,target): if(row not in range(n) or col not in range(m) or grid[row][col]!=target): return 0 if(grid[row][col]==2): target=0 else: target = 2 if(direction==0): if(turn): return 1+max(dfs(row-1, col-1, turn, 0, target) , dfs(row-1, col+1, False, 1,target)) return 1+dfs(row-1,col-1, turn,0, target) elif(direction == 1): if(turn): return 1+max(dfs(row-1, col+1, turn, 1, target), dfs(row+1, col+1, False,2, target )) return 1+dfs(row-1, col+1, turn , 1, target) elif(direction == 2): if(turn): return 1+max(dfs(row+1, col+1, turn, 2, target), dfs(row+1, col-1, False,3, target )) return 1+dfs(row+1, col+1, turn , 2, target) else: if(turn): return 1+max(dfs(row+1, col-1, turn, 3, target), dfs(row-1, col-1, False,0, target )) return 1+dfs(row+1, col-1, turn , 3, target) longest_v=0 for i in range(n): for j in range(m): if(grid[i][j] == 1): longest_v = max(longest_v, 1+max( dfs(i-1,j-1, True, 0, 2), dfs(i-1,j+1, True, 1,2 ) , dfs(i+1,j+1, True, 2,2) , dfs(i+1,j-1, True, 3,2)) ) return longest_v ``` ![upvote3.jpg](https://assets.leetcode.com/users/images/08825581-6bc2-4bd8-8343-d3f4f1152228_1739685184.4720724.jpeg)
5
0
['Dynamic Programming', 'Depth-First Search', 'Python3']
0
length-of-longest-v-shaped-diagonal-segment
🔥Using DP Clever Explanation
using-dp-clever-explanation-by-sapilol-xfjp
🚀 Approach: We use 4 DP matrices (a, b, c, d) to track the length of diagonal segments in 4 directions: a: top-left ↖️ bottom-right (↘️) b: top-right ↗️ b
LeadingTheAbyss
NORMAL
2025-02-16T04:14:06.171994+00:00
2025-02-16T15:34:21.400341+00:00
480
false
# 🚀 Approach: - We use 4 DP matrices `(a, b, c, d)` to track the length of diagonal segments in 4 directions: - `a`: top-left ↖️ bottom-right (↘️) - `b`: top-right ↗️ bottom-left (↙️) - `c`: bottom-left ↙️ top-right (↗️) - `d`: bottom-right ↘️ top-left (↖️) - For each cell (if `value ≠ 1`), we extend the diagonal segment if the previous cell in that direction has the complementary value `(2 - current value)`. - In the final loop, we combine two segments at a turning point (where the segment turns 90° clockwise) if the turning cell is `1`, forming a V-shape. - The maximum combined length across all such V-shaped segments is our answer. --- ``` # Implementation class Solution { public: int lenOfVDiagonal(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); vector<vector<int>> a(m, vector<int>(n, 1)), b(m, vector<int>(n, 1)), c(m, vector<int>(n, 1)), d(m, vector<int>(n, 1)); int res = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int v = grid[i][j]; if (v == 1) { res = 1; continue; } if (i > 0 && j > 0 && grid[i-1][j-1] == 2 - v) { a[i][j] = a[i-1][j-1] + 1; } if (i > 0 && j + 1 < n && grid[i-1][j+1] == 2 - v) { b[i][j] = b[i-1][j+1] + 1; } } } for (int i = m - 1; i >= 0; --i) { for (int j = 0; j < n; ++j) { int v = grid[i][j]; if (v == 1) { continue; } if (i + 1 < m && j > 0 && grid[i+1][j-1] == 2 - v) { c[i][j] = c[i+1][j-1] + 1; } if (i + 1 < m && j + 1 < n && grid[i+1][j+1] == 2 - v) { d[i][j] = d[i+1][j+1] + 1; } } } for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int v = grid[i][j]; if (v == 1) { continue; } if ((a[i][j] % 2 == 0 && v == 0) || (a[i][j] % 2 == 1 && v == 2)) { int ki = i - a[i][j]; int kj = j - a[i][j]; if (ki >= 0 && kj >= 0 && ki < m && kj < n && grid[ki][kj] == 1) { int mVal = c[i][j]; res = max(res, mVal + a[i][j]); } } if ((b[i][j] % 2 == 0 && v == 0) || (b[i][j] % 2 == 1 && v == 2)) { int ki = i - b[i][j]; int kj = j + b[i][j]; if (ki >= 0 && kj >= 0 && ki < m && kj < n && grid[ki][kj] == 1) { int mVal = a[i][j]; res = max(res, mVal + b[i][j]); } } if ((c[i][j] % 2 == 0 && v == 0) || (c[i][j] % 2 == 1 && v == 2)) { int ki = i + c[i][j]; int kj = j - c[i][j]; if (ki >= 0 && kj >= 0 && ki < m && kj < n && grid[ki][kj] == 1) { int mVal = d[i][j]; res = max(res, mVal + c[i][j]); } } if ((d[i][j] % 2 == 0 && v == 0) || (d[i][j] % 2 == 1 && v == 2)) { int ki = i + d[i][j]; int kj = j + d[i][j]; if (ki >= 0 && kj >= 0 && ki < m && kj < n && grid[ki][kj] == 1) { int mVal = b[i][j]; res = max(res, mVal + d[i][j]); } } } } return res; } };
5
0
['Graph', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
[Python3] dp
python3-dp-by-ye15-tmnw
IntuitionThis is DP problem. Define state space as (i, j, di, dj, turn) where (i, j) is the current location in the grid, (di, dj) represent the direction and t
ye15
NORMAL
2025-02-16T04:01:12.960235+00:00
2025-02-16T04:14:57.914443+00:00
578
false
# Intuition This is DP problem. Define state space as `(i, j, di, dj, turn)` where `(i, j)` is the current location in the grid, `(di, dj)` represent the direction and `turn` is a boolean indicating if a clockwise rotate is allowed. # Approach It is noticed that grid with value 1 can only be followed by 2, 2 can only be followed by 0 and 0 can only be followed by 2. With the aforementioned state, we can check if following the current direction `(di, dj)` the next value is a match in the grid. If so, that provides a candidate. In the meantime, if it is allowed to turn at the current position, always check this possibility rotating `(di, dj)` to `(dj, -di)`. # Complexity - Time complexity: `O(MN)` - Space complexity: `O(MN)` # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: n, m = len(grid), len(grid[0]) match = {0 : 2, 1 : 2, 2 : 0} @cache def fn(i, j, di, dj, turn): """Return """ ans = 1 comb = [(di, dj, turn)] if turn: comb.append((dj, -di, 0)) for di, dj, turn in comb: ii, jj = i+di, j+dj if 0 <= ii < n and 0 <= jj < m and grid[ii][jj] == match[grid[i][j]]: ans = max(ans, 1 + fn(ii, jj, di, dj, turn)) return ans ans = 0 for i in range(n): for j in range(m): for di, dj in (-1, -1), (-1, 1), (1, -1), (1, 1): if grid[i][j] == 1: ans = max(ans, fn(i, j, di, dj, 1)) return ans ```
5
0
['Python3']
1
length-of-longest-v-shaped-diagonal-segment
Super easy recursive + memeo solution. Top Down.
super-easy-recursive-memeo-solution-top-l4rr4
Code
Michael_Teng6
NORMAL
2025-02-16T06:10:10.052803+00:00
2025-02-16T06:10:10.052803+00:00
259
false
# Code ```cpp [] class Solution { public: int m,n; int dp[500][500][2][4]; int dfs(vector<vector<int>>& grid,int row,int col,bool canchange,int dir) { if(row<0||col<0||row==m||col==n||grid[row][col]==1) return 0; if(dp[row][col][canchange][dir]!=-1) return dp[row][col][canchange][dir]; int ans1=-10000,ans2=-10000; if(dir==0) { int previous=grid[row+1][col+1]; if(previous!=1&&previous==grid[row][col]) return 0; ans1=dfs(grid,row-1,col-1,canchange,dir); if(canchange) ans2=dfs(grid,row-1,col+1,0,1); } else if(dir==1) { int previous=grid[row+1][col-1]; if(previous!=1&&previous==grid[row][col]) return 0; ans1=dfs(grid,row-1,col+1,canchange,dir); if(canchange) ans2=dfs(grid,row+1,col+1,0,2); } else if(dir==2) { int previous=grid[row-1][col-1]; if(previous!=1&&previous==grid[row][col]) return 0; ans1=dfs(grid,row+1,col+1,canchange,dir); if(canchange) ans2=dfs(grid,row+1,col-1,0,3); } else { int previous=grid[row-1][col+1]; if(previous!=1&&previous==grid[row][col]) return 0; ans1=dfs(grid,row+1,col-1,canchange,dir); if(canchange) ans2=dfs(grid,row-1,col-1,0,0); } return dp[row][col][canchange][dir]=1+max(ans1,ans2); } int lenOfVDiagonal(vector<vector<int>>& grid) { m=grid.size(); n=grid[0].size(); int ans=0; memset(dp,-1,sizeof(dp)); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(grid[i][j]==1) { ans=max(ans,1); if(i-1>=0&&j-1>=0&&grid[i-1][j-1]==2) ans=max(ans,1+dfs(grid,i-1,j-1,1,0)); if(i-1>=0&&j+1<n&&grid[i-1][j+1]==2) ans=max(ans,1+dfs(grid,i-1,j+1,1,1)); if(i+1<m&&j+1<n&&grid[i+1][j+1]==2) ans=max(ans,1+dfs(grid,i+1,j+1,1,2)); if(i+1<m&&j-1>=0&&grid[i+1][j-1]==2) ans=max(ans,1+dfs(grid,i+1,j-1,1,3)); } } } return ans; } }; ```
4
0
['Recursion', 'Memoization', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
[Python] Memoize DP
python-memoize-dp-by-awice-ejmu
Let dp(r, c, dr, dc, expected, turned) be the length of a path starting at (r, c), going in direction (dr, dc), which expects a current value of A[r][c] == expe
awice
NORMAL
2025-02-16T10:58:05.208128+00:00
2025-02-16T10:58:05.208128+00:00
206
false
Let `dp(r, c, dr, dc, expected, turned)` be the length of a path starting at `(r, c)`, going in direction `(dr, dc)`, which expects a current value of `A[r][c] == expected`, and `turned` represents whether we have done a clockwise turn yet. # Code ```python3 [] class Solution: def lenOfVDiagonal(self, A: List[List[int]]) -> int: R, C = len(A), len(A[0]) @cache def dp(r, c, dr, dc, expected, turned): if not (0 <= r < R and 0 <= c < C) or A[r][c] != expected: return 0 if expected == 1: return 1 + max( dp(r + dr, c + dc, dr, dc, 2, 0) for dr, dc in [[1, -1], [-1, 1], [-1, -1], [1, 1]] ) ans = 1 + dp(r + dr, c + dc, dr, dc, 2 - expected, turned) if not turned: ans = max(ans, 1 + dp(r + dc, c - dr, dc, -dr, 2 - expected, True)) return ans return max(dp(r, c, 0, 0, 1, 0) for r in range(R) for c in range(C)) ```
3
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
DFS with a Twist: Longest V-Diagonals 🚀🔥
dfs-with-a-twist-longest-v-diagonals-by-efixi
IntuitionStart from each cell with a 1 and explore diagonals in all 4 directions (top-right, top-left, bottom-right, bottom-left). 2. For each direction, use DF
sahil241202
NORMAL
2025-02-17T20:00:12.757987+00:00
2025-02-17T20:01:41.872539+00:00
82
false
# Intuition Start from each cell with a 1 and explore diagonals in all 4 directions (top-right, top-left, bottom-right, bottom-left). 2. For each direction, use DFS to explore valid alternating patterns of 1 → 2 → 0. 3. At each step, check the maximum valid sequence—either continue straight or take one allowed turn to form the "V" or zigzag pattern. 4. The solution aims to find the longest valid alternating diagonal sequence by combining recursive exploration and pattern matching. for 6 seconds **Starting Point**: For every cell with a value of 1, the algorithm initiates a search in all four diagonal directions. **Pattern Matching**: It follows a strict alternating pattern (expecting 2, then 0, then 2, and so on) to form a valid sequence. **DFS Exploration**: At each step, the DFS can either continue straight or make one allowed turn to maximize the path length. **Result Aggregation**: The maximum length of these valid "V" diagonal paths is recorded and returned as the solution. # Complexity - Time complexity: $$O(N* M *min(N,M))$$ - Space complexity: *$$O(N * M)$$* <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: //create grid, n, m, directions global so that we don't need to //pass again and again in the recursive function vector<vector<int>> grid; vector<vector<int>> directions = {{-1,1},{1,1},{1,-1},{-1,-1}}; int n; int m; int lenOfVDiagonal(vector<vector<int>>& grid) { //calculate number of rows and columns in the grid n = grid.size(); m = grid[0].size(); this->grid = grid; int res = 0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ //Only start travaersing from the grid element having value equals to 1 if(grid[i][j]==1){ res = max(res,1); //traverse in the four diagonal directions from the starting point res = max(res,dfs(i,j,0,2,false)); res = max(res,dfs(i,j,1,2,false)); res = max(res,dfs(i,j,2,2,false)); res = max(res,dfs(i,j,3,2,false)); } } } return res; } int dfs(int i,int j,int dir,int target,int turned){ int x = i+directions[dir][0]; int y = j+directions[dir][1]; //if we go out of bound or we didn't get our expected target if(x<0 || y<0 || x>=n || y>=m || grid[x][y]!=target){ return 1; } int straight = 1 + dfs(x,y,dir,target==2?0:2,turned); //this turn variable is used to calculate the length of segment if we take a 90 degree turn int turn = 1; if(!turned){ turn = 1 + dfs(x,y,(dir+1)%4,target==2?0:2,true); } //at each point we have two choices to go straight in the // same diagonal direction or to take a 90 degree turn so we // always return the maximum segment we get after considering // all possible ways return max(straight,turn); } }; ```
2
0
['Depth-First Search', 'Recursion', 'C++']
1
length-of-longest-v-shaped-diagonal-segment
Brute Force Using BFS
brute-force-using-bfs-by-conganhhcmus-ahdn
Approach Use BFS to compute values starting from each point (i,j) where grid[i][j] = 1, Return the maximum value obtained from all starting points. The maximum
conganhhcmus
NORMAL
2025-02-16T11:35:40.945330+00:00
2025-02-16T11:35:40.945330+00:00
130
false
# Approach - Use BFS to compute values starting from each point `(i,j)` where `grid[i][j] = 1`, - Return the maximum value obtained from all starting points. - The maximum possible answer is `Max(n,m)`. - If there is only one occurrence of this maximum value, return it immediately to optimize performance. # Complexity - Time complexity: $$O(n*m*4*n*m)$$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```csharp [] public class Solution { public int LenOfVDiagonal(int[][] grid) { int n = grid.Length, m = grid[0].Length; int ans = 0; int[][] dirs = [[1, 1], [1, -1], [-1, -1], [-1, 1]]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { Queue<(int x, int y, int pX, int pY, int d, bool canTurn)> queue = []; for (int d = 0; d < dirs.Length; d++) { int nX = i + dirs[d][0], nY = j + dirs[d][1]; if (nX < 0 || nY < 0 || nX >= n || nY >= m || grid[nX][nY] != 2) continue; queue.Enqueue((nX, nY, i, j, d, true)); } int count = 1; while (queue.Count > 0) { int size = queue.Count; for (int k = 0; k < size; k++) { var (x, y, pX, pY, d, canTurn) = queue.Dequeue(); for (int t = 0; t < dirs.Length; t++) { if (t == d) { int nX = x + dirs[t][0], nY = y + dirs[t][1]; if (nX < 0 || nY < 0 || nX >= n || nY >= m || grid[nX][nY] == 1 || (nX == pX && nY == pY)) continue; if (grid[x][y] != grid[nX][nY]) { queue.Enqueue((nX, nY, x, y, t, canTurn)); } } else if (t == (d + 1) % dirs.Length && canTurn) { int nX = x + dirs[t][0], nY = y + dirs[t][1]; if (nX < 0 || nY < 0 || nX >= n || nY >= m || grid[nX][nY] == 1 || (nX == pX && nY == pY)) continue; if (grid[x][y] != grid[nX][nY]) { queue.Enqueue((nX, nY, x, y, t, false)); } } } } count++; } ans = Math.Max(ans, count); if (ans == Math.Max(n, m)) return ans; } } } return ans; } } ```
2
0
['Breadth-First Search', 'C#']
0
length-of-longest-v-shaped-diagonal-segment
DP Soln | beats 100%
dp-soln-beats-100-meow-meow-by-drunkencl-2412
IntuitionThis problem involves finding the longest valid 'V' or diagonal path in the grid. We use dynamic programming to efficiently compute diagonal lengths in
drunkencloud9
NORMAL
2025-02-16T05:05:50.141834+00:00
2025-02-16T05:14:11.907408+00:00
212
false
# Intuition This problem involves finding the longest valid 'V' or diagonal path in the grid. We use dynamic programming to efficiently compute diagonal lengths in all four diagonal directions and then combine them. # Approach We use a dp array `dp[i][j][d]` stores the length of the longest valid diagonal path ending at `(i, j)` in direction `d`. The four diagonal directions are: 1. `↖` (top-left to bottom-right) 2. `↘` (bottom-right to top-left) 3. `↙` (bottom-left to top-right) 4. `↗` (top-right to bottom-left) We iterate over the grid and compute the diagonal lengths in a bottom-up manner. For each `1` in the grid, we check its possible extensions along valid diagonal paths and update the maximum length found. # Complexity - **Time complexity:** - We iterate through all `n × m` grid cells and update the `dp` values, leading to a complexity of **O(n × m)**. - In the worst case, we traverse some paths multiple times while checking connections, but this still remains within **O(n × m)**. - In the final part where we find the `maxV`, we see that we go through each diagonal in each 4 corners, worst case is we go until the end in each, so say **O(k x (n+m))** where k is number of 1s, this still bounds within **O(n x m)** when you check it. - **Space complexity:** - The `dp` array has dimensions `n × m × 4`, leading to a space complexity of **O(n × m)**. # Code ```cpp class Solution { public: // Helper function to determine the next diagonal direction int getNext(int d) { if (d == 0) return 3; // ↖ (top-left) -> ↗ (top-right) if (d == 1) return 2; // ↘ (bottom-right) -> ↙ (bottom-left) if (d == 2) return 0; // ↙ (bottom-left) -> ↖ (top-left) return 1; // ↗ (top-right) -> ↘ (bottom-right) } // Helper function to determine the current diagonal direction int getCurr(int d) { if (d == 0) return 1; // ↖ (top-left) -> ↘ (bottom-right) if (d == 1) return 0; // ↘ (bottom-right) -> ↖ (top-left) if (d == 2) return 3; // ↙ (bottom-left) -> ↗ (top-right) return 2; // ↗ (top-right) -> ↙ (bottom-left) } int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); // DP array to store diagonal lengths in four directions vector<vector<array<int, 4>>> dp(n, vector<array<int, 4>>(m, {0, 0, 0, 0})); // Directions for diagonal traversal: ↖, ↘, ↙, ↗ vector<pair<int, int>> dirs = {{-1,-1}, {1,1}, {1,-1}, {-1,1}}; // Compute DP values for ↖ (top-left to bottom-right) for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { if (grid[i][j] != 1 && grid[i - 1][j - 1] != 1 && grid[i - 1][j - 1] != grid[i][j]) { dp[i][j][0] = dp[i - 1][j - 1][0] + 1; } } } // Compute DP values for ↘ (bottom-right to top-left) for (int i = n - 2; i >= 0; i--) { for (int j = m - 2; j >= 0; j--) { if (grid[i][j] != 1 && grid[i + 1][j + 1] != 1 && grid[i + 1][j + 1] != grid[i][j]) { dp[i][j][1] = dp[i + 1][j + 1][1] + 1; } } } // Compute DP values for ↙ (bottom-left to top-right) for (int i = n - 2; i >= 0; i--) { for (int j = 1; j < m; j++) { if (grid[i][j] != 1 && grid[i + 1][j - 1] != 1 && grid[i + 1][j - 1] != grid[i][j]) { dp[i][j][2] = dp[i + 1][j - 1][2] + 1; } } } // Compute DP values for ↗ (top-right to bottom-left) for (int i = 1; i < n; i++) { for (int j = m - 2; j >= 0; j--) { if (grid[i][j] != 1 && grid[i - 1][j + 1] != 1 && grid[i - 1][j + 1] != grid[i][j]) { dp[i][j][3] = dp[i - 1][j + 1][3] + 1; } } } int maxV = 0; // Maximum valid diagonal length // Iterate over each cell in the grid for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] != 1) continue; // Skip cells that are not 1 maxV = max(maxV, 1); // Check diagonal connections for (int d = 0; d < 4; d++) { int nextDir = getNext(d); // the next possible dir which is in clockwise direction. int currDir = getCurr(d); // the current dir which is opposite to d since we see from the other side to 1. auto& dir = dirs[d]; int ci = i + dir.first, cj = j + dir.second; if (ci < 0 || cj < 0 || ci >= n || cj >= m || grid[ci][cj] != 2) continue; // Expand along the diagonal while conditions are met while (ci >= 0 && cj >= 0 && ci < n && cj < m && grid[ci][cj] != grid[ci-dir.first][cj-dir.second] && grid[ci][cj] != 1) { maxV = max(maxV, dp[ci][cj][nextDir] + dp[ci][cj][currDir] + 2); // We can get off by not checking a straight diagonal since it will come under this case as well due to the while loop. ci += dir.first; cj += dir.second; } } } } return maxV; // Return the maximum diagonal length found } }; ```
2
0
['Dynamic Programming', 'C++']
2
length-of-longest-v-shaped-diagonal-segment
Brute Force | C++
brute-force-c-by-nilay_c-8f5e
store the length of the sequence starting at each 0 and 2 in all four directions, this gives you the additional length you get if you turn to that index. from t
nilay_c
NORMAL
2025-02-16T04:06:12.668637+00:00
2025-02-16T04:09:58.799246+00:00
52
false
store the length of the sequence starting at each 0 and 2 in all four directions, this gives you the additional length you get if you turn to that index. from there, you can simply brute force. from each 1, go in a direction and find what answer you can get if you turn at that point or continue forward. do this for all directions honestly its a bit too close to the TL, using vector instead of an array in the DP got TLE # Code ```cpp [] class Solution { public: int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); int dp[n][m][4]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ dp[i][j][0] = 0; dp[i][j][1] = 0; dp[i][j][2] = 0; dp[i][j][3] = 0; if(grid[i][j] == 0 || grid[i][j] == 2){ int tempi = i, tempj = j; int next = (grid[i][j])%4; int ans = 0; // down right while(tempi < n && tempj < m && grid[tempi][tempj] == next){ ans++; next = (grid[tempi][tempj] + 2)%4; tempi++; tempj++; } dp[i][j][0] = ans; tempi = i, tempj = j; next = (grid[i][j])%4; ans = 0; // up right while(tempi >= 0 && tempj < m && grid[tempi][tempj] == next){ ans++; next = (grid[tempi][tempj] + 2)%4; tempi--; tempj++; } dp[i][j][1] = ans; tempi = i, tempj = j; next = (grid[i][j] )%4; ans = 0; // down left while(tempi < n && tempj >= 0 && grid[tempi][tempj] == next){ ans++; next = (grid[tempi][tempj] + 2)%4; tempi++; tempj--; } dp[i][j][2] = ans; tempi = i, tempj = j; next = (grid[i][j])%4; ans = 0; // up left while(tempi >= 0 && tempj >= 0 && grid[tempi][tempj] == next){ ans++; next = (grid[tempi][tempj] + 2)%4; tempi--; tempj--; } dp[i][j][3] = ans; } } } // dr 0 ur 1 dl 2 ul 3 int ans = 0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(grid[i][j] == 1){ int next = 2; int tempi = i+1, tempj = j+1; int maxi = 0; int curr = 0; // down right -> ur, dl while(tempi < n && tempj < m && grid[tempi][tempj] == next){ curr++; if(tempi + 1 < n && tempj-1 >= 0 && grid[tempi+1][tempj-1] == ((next+2)%4)){ maxi = max(maxi, curr + dp[tempi+1][tempj-1][2]); } maxi = max(maxi, curr); next = (next+2)%4; tempi++; tempj++; } // ur -> ul, dr curr = 0; tempi = i-1; tempj = j+1; next = 2; while(tempi >= 0 && tempj < m && grid[tempi][tempj] == next){ curr++; if(tempi + 1 < n && tempj+1 < m && grid[tempi+1][tempj+1] == ((next+2)%4)){ maxi = max(maxi, curr + dp[tempi+1][tempj+1][0]); } maxi = max(maxi, curr); next = (next+2)%4; tempi--; tempj++; } // ul -> ur, dl curr = 0; tempi = i-1; tempj = j-1; next = 2; while(tempi >= 0 && tempj >= 0 && grid[tempi][tempj] == next){ curr++; if(tempi - 1 >= 0 && tempj+1 < m && grid[tempi-1][tempj+1] == ((next+2)%4)){ maxi = max(maxi, curr + dp[tempi-1][tempj+1][1]); } maxi = max(maxi, curr); next = (next+2)%4; tempi--; tempj--; } // dl -> ul, dr curr = 0; tempi = i+1; tempj = j-1; next = 2; while(tempi < n && tempj >= 0 && grid[tempi][tempj] == next){ curr++; if(tempi - 1 >= 0 && tempj-1 >= 0 && grid[tempi-1][tempj-1] == ((next+2)%4)){ maxi = max(maxi, curr + dp[tempi-1][tempj-1][3]); } maxi = max(maxi, curr); next = (next+2)%4; tempi++; tempj--; } ans = max(ans, maxi+1); // cout<<ans<<" and "; } } } return ans; } }; ```
2
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
[Python][DFS+Memoization]Easy to understand code
pythondfsmemoizationeasy-to-understand-c-mdft
IntuitionSimple dfs traversal whenever we spot a 1. DFS parameters are: r:= Current Row c:= Current Column d:= Current direction (see directions array in code,
buggy_d_clown
NORMAL
2025-03-01T09:33:44.717942+00:00
2025-03-01T09:33:44.717942+00:00
42
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Simple dfs traversal whenever we spot a 1. DFS parameters are: r:= Current Row c:= Current Column d:= Current direction (see directions array in code, its ordered in clockwise) hasTurned:= Wether we have turned for the Vertex of our v shape need2:= whether in this step we need a '2' or a '0' in the sequence. # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(MN*(M+N)) since we traverse each cell so M*N, and each of the paths we traverse a path of maximum length M+N. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(MN x 4 x 2 x 2) = O(16MN) = O(MN) # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: m,n = len(grid),len(grid[0]) directions = [(1,1),(1,-1),(-1,-1),(-1,1)] memo = {} def dfs(r,c,d,hasTurned,need2): tup = (r,c,d,hasTurned,need2) if tup in memo: return memo[tup] r_,c_ = r+directions[d][0],c+directions[d][1] expected = 2 if need2 else 0 if 0<=r_<m and 0<=c_<n and grid[r_][c_]==expected: best = dfs(r_,c_,d,hasTurned,not need2) if not hasTurned: d_ = (d+1)%len(directions) best = max(best,dfs(r_,c_,d_,True,not need2)) memo[tup] = best+1 return best+1 else: memo[tup]=0 return 0 ans = 0 for i in range(m): for j in range(n): if grid[i][j]==1: for d in range(len(directions)): ans = max(ans,1+dfs(i,j,d,False,2)) return ans ```
1
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
Python3 || dfs dp w/ cache || T/S: 90% / 31%
python3-dp-w-cache-ts-90-31-by-spaulding-mpwt
https://leetcode.com/problems/length-of-longest-v-shaped-diagonal-segment/submissions/1558544812/I could be wrong, but I think that time complexity is O(MN) and
Spaulding_
NORMAL
2025-02-28T20:40:48.735648+00:00
2025-02-28T20:42:15.481052+00:00
31
false
```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: @lru_cache(None) def dfs(row,col, dr,dc, element, hasTurned): if not (0 <= row < m and 0 <= col < n) or grid[row][col] != element: return 0 ans = dfs(row + dr, col + dc, dr, dc, element^2, hasTurned) if hasTurned: return ans + 1 length = dfs(row + dc, col - dr, dc, -dr, element^2, True) return max(ans,length) + 1 m, n = len(grid), len(grid[0]) ans, dr, dc, hasOne = 0, 1, 1, False for row in range(m): for col in range(n): if grid[row][col] == 1: hasOne = True for _ in range(4): dr, dc = -dc, dr vee = dfs(row + dr, col + dc, dr, dc, 2, False) ans = max(ans, vee) return ans + hasOne ``` [https://leetcode.com/problems/length-of-longest-v-shaped-diagonal-segment/submissions/1558544812/](https://leetcode.com/problems/length-of-longest-v-shaped-diagonal-segment/submissions/1558544812/) I could be wrong, but I think that time complexity is *O*(*MN*) and space complexity is *O*(*MN*), in which *M* , *N* ~ `m, n`.
1
0
['Python3']
0
length-of-longest-v-shaped-diagonal-segment
Very Clean DP code with memoization
very-clean-dp-code-with-memoization-by-s-5bq3
IntuitionApproachComplexity Time complexity: Space complexity: Code
Shaurya_Malhan
NORMAL
2025-02-17T19:19:24.505714+00:00
2025-02-17T19:19:24.505714+00:00
133
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 ```java [] class Solution { public static int n; public static int m; public static Integer[][][][][] dp; public static int[] x = {1, 1, -1, -1}; public static int[] y = {1, -1, -1, 1}; public int lenOfVDiagonal(int[][] g) { n = g.length; m = g[0].length; dp = new Integer[n][m][2][3][4]; int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (g[i][j] == 1) { for (int k = 0; k < 4; k++) { ans = Math.max(ans, 1 + solve(i + x[k], j + y[k], 0, 2, k, g)); } } } } return ans; } public static int solve(int i, int j, int turn, int curr, int dir, int[][] g) { if (i >= n || i < 0 || j >= m || j < 0 || g[i][j] != curr) return 0; if (dp[i][j][turn][curr][dir] != null) return dp[i][j][turn][curr][dir]; int ans = 1 + solve(i + x[dir], j + y[dir], turn, 2 - curr, dir, g); if (turn == 0) { ans = Math.max(ans, 1 + solve(i + x[(dir + 1) % 4], j + y[(dir + 1) % 4], 1, 2 - curr, (dir + 1) % 4, g)); } return dp[i][j][turn][curr][dir] = ans; } } ```
1
0
['Java']
0
length-of-longest-v-shaped-diagonal-segment
C++ | DP + Traversal
c-dp-traversal-by-kena7-05in
Code
kenA7
NORMAL
2025-02-17T04:13:57.422683+00:00
2025-02-17T04:13:57.422683+00:00
53
false
# Code ```cpp [] class Solution { public: int dp[501][501][4][2]; int m,n; int dx[4]={1,1,-1,-1}; int dy[4]={-1,1,-1,1}; int clockwise[4]={2,0,3,1}; bool valid(int i,int j) { return !(i<0 || j<0 || i>=m || j>=n); } int find(int i,int j,int dir,int turn,vector<vector<int>>& g) { int res=1; if(dp[i][j][dir][turn]!=-1) return dp[i][j][dir][turn]; int x=i+dx[dir],y=j+dy[dir]; if(valid(x,y) && g[x][y]!=1 && g[x][y]!=g[i][j]) res=max(res,1+find(x,y,dir,turn,g)); if(turn==0) { int k=clockwise[dir]; x=i+dx[k],y=j+dy[k]; if(valid(x,y) && g[x][y]!=1 && g[x][y]!=g[i][j]) res=max(res,1+find(x,y,k,1,g)); } return res; } int lenOfVDiagonal(vector<vector<int>>& grid) { memset(dp,-1,sizeof(dp)); m=grid.size(),n=grid[0].size(); int res=0; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(grid[i][j]==1) { res=max(res,1); for(int k=0;k<4;k++) { int x=i+dx[k],y=j+dy[k]; if(valid(x,y) && grid[x][y]==2) res=max(res,1+find(x,y,k,0,grid)); } } } } return res; } }; ```
1
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
Brute Force using DFS -> Travel all possible paths
brute-force-using-dfs-travel-all-possibl-rivr
IntuitionApproachComplexity Time complexity: Space complexity: Code
got_u
NORMAL
2025-02-16T17:22:40.298684+00:00
2025-02-16T17:22:40.298684+00:00
39
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 ```cpp [] class Solution { public: int travelDiag(int x, int y, int n ,int m, vector<vector<int>>& grid, int px, int py){ int nextx=x+px; int nexty=y+py; int ans=1; if(nextx>=0&&nexty>=0&&nextx<n&&nexty<m){ if((grid[x][y]==1&&grid[nextx][nexty]==2)||(grid[x][y]==2&&grid[nextx][nexty]==0)||(grid[x][y]==0&&grid[nextx][nexty]==2)){ ans+=travelDiag(nextx, nexty, n, m, grid, px, py); } } return ans; } void travelDiagAlongWithRotation(int x, int y, int n ,int m, vector<vector<int>>& grid, int cpx, int cpy, int px, int py, int &ans, int depth){ int nextx=x+px; int nexty=y+py; int d1=0; // Take Clockwise 90 and get the length if(grid[x][y]!=1){ d1=travelDiag(x, y, n, m, grid, cpx, cpy); } if(nextx>=0&&nexty>=0&&nextx<n&&nexty<m){ if((grid[x][y]==1&&grid[nextx][nexty]==2)||(grid[x][y]==2&&grid[nextx][nexty]==0)||(grid[x][y]==0&&grid[nextx][nexty]==2)){ travelDiagAlongWithRotation(nextx, nexty, n, m, grid, cpx, cpy, px, py, ans, depth+1); } } //maximize the ans currDepth + clockwise 90 length ans=max(ans, depth+max(0, d1-1)); } int lenOfVDiagonal(vector<vector<int>>& grid) { int n=grid.size(); int m=grid[0].size(); int ans=0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(grid[i][j]==1){ travelDiagAlongWithRotation(i, j, n, m, grid, 1, -1, 1, 1, ans, 1); travelDiagAlongWithRotation(i, j, n, m, grid, -1, -1, 1, -1, ans, 1); travelDiagAlongWithRotation(i, j, n, m, grid, -1, 1, -1, -1, ans, 1); travelDiagAlongWithRotation(i, j, n, m, grid, 1, 1, -1, 1, ans, 1); } } } return ans; } }; ```
1
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
Normal DFS + DP (for optimization)
normal-dfs-dp-for-optimization-by-rthaku-qbmd
IntuitionJust create a dp state which tells the maximum ans from this coordinate upto the end when the status of turn_taken is (used or unused).Code
rthakur2712
NORMAL
2025-02-16T12:38:28.383067+00:00
2025-02-16T12:38:28.383067+00:00
56
false
# Intuition Just create a dp state which tells the maximum ans from this coordinate upto the end when the status of turn_taken is (used or unused). # Code ```cpp [] class Solution { //direction are 1,2,3,4 or 0,1,2,3(preferred) /* directions are 0 1 2 3 */ public: int lenOfVDiagonal(vector<vector<int>>& grid) { int drow[4] = {-1,-1,1,1}; int dcol[4] = {-1,1,-1,1}; vector<int> adjDir; adjDir.push_back(1); adjDir.push_back(3); adjDir.push_back(0); adjDir.push_back(2); map<int,int> next; next[0]=2; next[1]=2; next[2]=0; int n = int(grid.size()); int m = int(grid[0].size()); int dp[505][505][4][2]; memset(dp, -1, sizeof(dp)); function<int(int,int,int,int)>f = [&](int row, int col, int dir, int turn_taken){ // stop //edges if( turn_taken == 0 && (row == 0 || col == 0 || row == n-1 || col == m-1) ){ return 1; } // corners if( turn_taken == 1 && ( (row==0 && col == 0&&dir==0) || (row == n-1 && col == m-1&&dir==3) || (row == n-1 && col == 0&&dir==2) && (row==0 && col == m-1&&dir==1) )){ return 1; } // no viable moves if( dp[row][col][dir][turn_taken] !=-1 )return dp[row][col][dir][turn_taken] ; // either continue or take a turn // continue int ele = grid[row][col]; int nrow = row + drow[dir]; int ncol = col + dcol[dir]; int ans = 1; if( nrow >=0 && ncol >=0 && nrow <n && ncol<m && grid[nrow][ncol] == next[ele] ){ ans = max(ans,1 + f( nrow, ncol, dir, turn_taken )); } // take a turn if( turn_taken == 1 ){ // turn is left // turn towards right int ndir = adjDir[dir]; nrow = row + drow[ndir]; ncol = col + dcol[ndir]; if( nrow >=0 && ncol >=0 && nrow<n && ncol<m && grid[nrow][ncol] == next[ele] ){ ans = max(ans,1 + f( nrow, ncol, ndir, 0 )); } } return dp[row][col][dir][turn_taken] = ans; }; // start dfs from every 1 int maxi = -1e9; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if( grid[i][j] == 1 ){ for(int dir=0; dir<4; dir++){ maxi = max(maxi, f(i,j,dir,1)); } } } } if( maxi < -1e8 ){ return 0; } return maxi; } }; ```
1
0
['Dynamic Programming', 'Depth-First Search', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
✅✅✅Easy To Understand C++ Code
easy-to-understand-c-code-by-codeblunder-ozn2
IntuitionStart at Every 1: Since every valid segment must start with 1, we only begin our search from cells with a 1.Try Every Diagonal: There are 4 diagonal di
codeblunderer
NORMAL
2025-02-16T08:36:17.613820+00:00
2025-02-16T08:36:17.613820+00:00
94
false
# Intuition Start at Every 1: Since every valid segment must start with 1, we only begin our search from cells with a 1. Try Every Diagonal: There are 4 diagonal directions, so we try all possibilities from each starting point. Follow the Pattern: Using the expected function, we know exactly which number should come next in the segment. Allow One Turn: The DFS function is designed to allow one 90° clockwise turn. This gives us the "V-shape"—a change in direction after starting along one diagonal. Return the Longest: By exploring every possible starting point and direction, we eventually know the maximum length of a V-shaped segment that can be found. # Code ```cpp [] class Solution { public: int dir[4][2] = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; int n, m; int expected(int step) { if (step == 0) return 1; return (step % 2 == 1) ? 2 : 0; } int dfs(vector<vector<int>>& grid, int r, int c, int step, bool turned, int d) { int exp = expected(step + 1); int ans = 1; int nr = r + dir[d][0], nc = c + dir[d][1]; if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] == exp) { ans = max(ans, 1 + dfs(grid, nr, nc, step + 1, turned, d)); } if (!turned) { pair<int, int> nDir = {dir[d][1], -dir[d][0]}; int nd = -1; for (int i = 0; i < 4; i++) { if (dir[i][0] == nDir.first && dir[i][1] == nDir.second) { nd = i; break; } } int nr2 = r + nDir.first, nc2 = c + nDir.second; if (nd != -1 && nr2 >= 0 && nr2 < n && nc2 >= 0 && nc2 < m && grid[nr2][nc2] == exp) { ans = max(ans, 1 + dfs(grid, nr2, nc2, step + 1, true, nd)); } } return ans; } int lenOfVDiagonal(vector<vector<int>>& grid) { n = grid.size(), m = grid[0].size(); int maxi = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { for (int d = 0; d < 4; d++) { maxi = max(maxi, dfs(grid, i, j, 0, false, d)); } } } } return maxi; } }; ```
1
0
['Depth-First Search', 'C++']
1
length-of-longest-v-shaped-diagonal-segment
Simple & Clear Solution | Intuitive Approach | DP | C++ 🚀
simple-clear-solution-intuitive-approach-mvqk
Approach DFS with Memoization (DP): For each cell with 1, explore all 4 diagonal directions. Track states using row, col, required number (1, 2, 0), direct
vedant115
NORMAL
2025-02-16T08:13:09.823248+00:00
2025-02-16T08:31:43.142676+00:00
54
false
# Approach - DFS with Memoization (DP): - For each cell with 1, explore all 4 diagonal directions. - Track states using row, col, required number (1, 2, 0), direction, and whether a turn has been made. - State Transitions: - Same Direction: Continue in the current direction. - Turn Once: Make a 90-degree turn if no prior turn. #### How `dir` Array Helps in Diagonal Movement - We use a `dir` array to efficiently traverse the four diagonal directions: `dir[0]` → Top-left (↖️) `(-1, -1)` `dir[1]` → Top-right (↗️) `(-1, 1)` `dir[2]` → Bottom-right (↘️) `(1, 1)` `dir[3]` → Bottom-left (↙️) `(1, -1)` - When moving along the same diagonal, we use `dir[d]` directly. - When making a 90° turn, we increase the direction index by `1` and take `mod 4` to cycle through: `0 (↖️)` → `1 (↗️)` `1 (↗️)` → `2 (↘️)` `2 (↘️)` → `3 (↙️)` `3 (↙️)` → `0 (↖️)` # Complexity - Time complexity: $$O(N*M)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(N*M)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { private: vector<vector<int>> dir = {{-1, -1}, {-1, 1}, {1, 1}, {1, -1}}; // 4 diagonal directions int dp[501][501][3][4][2]; // Memoization table int func(int row, int col, int numReq, int d, int turn, vector<vector<int>>& grid) { if (row < 0 || col < 0 || row >= grid.size() || col >= grid[0].size()) return 0; if (grid[row][col] != numReq) return 0; if (dp[row][col][numReq][d][turn] != -1) return dp[row][col][numReq][d][turn]; int newNumReq = (numReq == 2) ? 0 : 2; // Next required number // Continue in same direction int alongDiag = 1 + func(row + dir[d][0], col + dir[d][1], newNumReq, d, turn, grid); // Make a 90-degree turn (if not turned before) int rotateNinety = 0; if (!turn) { rotateNinety = 1 + func(row + dir[(d + 1) % 4][0], col + dir[(d + 1) % 4][1], newNumReq, (d + 1) % 4, 1, grid); } return dp[row][col][numReq][d][turn] = max(alongDiag, rotateNinety); } public: int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); memset(dp, -1, sizeof(dp)); int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { int maxSeg = 0; for (int d = 0; d < 4; d++) { // Check all 4 directions maxSeg = max(maxSeg, 1 + func(i + dir[d][0], j + dir[d][1], 2, d, 0, grid)); } res = max(res, maxSeg); } } } return res; } }; ```
1
0
['Dynamic Programming', 'Depth-First Search', 'Memoization', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
easy cpp solution to understand
easy-cpp-solution-to-understand-by-prati-vr28
IntuitionApproachComplexity Time complexity: Space complexity: Code
pratik5722
NORMAL
2025-02-16T06:39:10.405897+00:00
2025-02-16T06:39:10.405897+00:00
27
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 ```cpp [] #pragma GCC optimize("O3", "unroll-loops") const auto _ = std::cin.tie(nullptr)->sync_with_stdio(false); #define LC_HACK #ifdef LC_HACK const auto __ = []() { struct ___ { static void _() { std::ofstream("display_runtime.txt") << 0 << '\n'; } }; std::atexit(&___::_); return 0; }(); #endif class Solution { public: int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); vector<vector<vector<vector<int>>>> dp(4, vector<vector<vector<int>>>(n, vector<vector<int>>(m, vector<int>(3, 0)))); vector<pair<int, int>> dirs = {{1, 1}, {1, -1}, {-1, -1}, {-1, 1}}; for (int d = 0; d < 4; d++) { int di = dirs[d].first, dj = dirs[d].second; if (di == 1 && dj == 1) { for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { for (int e = 0; e < 3; e++) { if (grid[i][j] == e) { int ni = i + di, nj = j + dj; int ne = (e == 1) ? 2 : (e == 2 ? 0 : 2); dp[d][i][j][e] = 1 + ((ni >= 0 && ni < n && nj >= 0 && nj < m) ? dp[d][ni][nj][ne] : 0); } } } } } else if (di == 1 && dj == -1) { for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < m; j++) { for (int e = 0; e < 3; e++) { if (grid[i][j] == e) { int ni = i + di, nj = j + dj; int ne = (e == 1) ? 2 : (e == 2 ? 0 : 2); dp[d][i][j][e] = 1 + ((ni >= 0 && ni < n && nj >= 0 && nj < m) ? dp[d][ni][nj][ne] : 0); } } } } } else if (di == -1 && dj == -1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int e = 0; e < 3; e++) { if (grid[i][j] == e) { int ni = i + di, nj = j + dj; int ne = (e == 1) ? 2 : (e == 2 ? 0 : 2); dp[d][i][j][e] = 1 + ((ni >= 0 && ni < n && nj >= 0 && nj < m) ? dp[d][ni][nj][ne] : 0); } } } } } else { for (int i = 0; i < n; i++) { for (int j = m - 1; j >= 0; j--) { for (int e = 0; e < 3; e++) { if (grid[i][j] == e) { int ni = i + di, nj = j + dj; int ne = (e == 1) ? 2 : (e == 2 ? 0 : 2); dp[d][i][j][e] = 1 + ((ni >= 0 && ni < n && nj >= 0 && nj < m) ? dp[d][ni][nj][ne] : 0); } } } } } } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int d = 0; d < 4; d++) { if (grid[i][j] != 1) continue; int L = dp[d][i][j][1]; ans = max(ans, L); int d2 = (d + 1) % 4; int di = dirs[d].first, dj = dirs[d].second; int di2 = dirs[d2].first, dj2 = dirs[d2].second; for (int t = 1; t <= L; t++) { int r = i + (t - 1) * di, c = j + (t - 1) * dj; int nr = r + di2, nc = c + dj2; if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue; int exp = (t % 2 == 1) ? 2 : 0; int L2 = dp[d2][nr][nc][exp]; ans = max(ans, t + L2); } } } } return ans; } }; ```
1
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
Recursion (Dp optional for optimization) || O(n.m) || 100 % beat || Must check
recursion-dp-optional-for-optimization-o-n0a5
Complexity Time complexity: O(n.m) Space complexity: O(n.m)Code
Priyanshu_pandey15
NORMAL
2025-02-16T06:34:13.263408+00:00
2025-02-16T06:34:13.263408+00:00
64
false
# Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(n.m)$$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(n.m)$$ # Code ```java [] class Solution { static public int lenOfVDiagonal(int[][] arr) { int ans = 0, n = arr.length, m = arr[0].length, max = 0; Integer[][][][] dp = new Integer[n][m][5][2]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { if (arr[i][j] == 1) { ans = 1; if (i - 1 >= 0 && j - 1 >= 0) { if (arr[i - 1][j - 1] == 2) { ans = 1 + solve(i - 1, j - 1, arr, 1, 0, n, m, dp); max = Math.max(max, ans); } } if (i - 1 >= 0 && j + 1 < m) { if (arr[i - 1][j + 1] == 2) { ans = 1 + solve(i - 1, j + 1, arr, 2, 0, n, m, dp); max = Math.max(max, ans); } } if (i + 1 < n && j - 1 >= 0) { if (arr[i + 1][j - 1] == 2) { ans = 1 + solve(i + 1, j - 1, arr, 4, 0, n, m, dp); max = Math.max(max, ans); } } if (i + 1 < n && j + 1 < m) { if (arr[i + 1][j + 1] == 2) { ans = 1 + solve(i + 1, j + 1, arr, 3, 0, n, m, dp); max = Math.max(max, ans); } } max = Math.max(max, ans); } } } return max; } static int solve(int i, int j, int[][] arr, int option, int changes, int n, int m, Integer[][][][] dp) { int ans = 1, max = 0; if(dp[i][j][option][changes] != null) return dp[i][j][option][changes]; if (option == 1) { if (changes == 0) { if (i - 1 >= 0 && j - 1 >= 0) { if (!(arr[i - 1][j - 1] == 1)) { if (arr[i - 1][j - 1] != arr[i][j]) { ans = 1 + solve(i - 1, j - 1, arr, 1, 0, n, m, dp); max = Math.max(max, ans); } } } if (i - 1 >= 0 && j + 1 < m) { if (!(arr[i - 1][j + 1] == 1)) { if (arr[i][j] != arr[i - 1][j + 1]) { ans = 1 + solve(i - 1, j + 1, arr, 2, 1, n, m, dp); max = Math.max(max, ans); } } } } else { if (i - 1 >= 0 && j - 1 >= 0) { if (!(arr[i - 1][j - 1] == 1)) { if (arr[i - 1][j - 1] != arr[i][j]) { ans = 1 + solve(i - 1, j - 1, arr, 1, 1, n, m, dp); max = Math.max(max, ans); } } } } } else if (option == 2) { if (changes == 0) { if (i - 1 >= 0 && j + 1 < m) { if (!(arr[i - 1][j + 1] == 1)) { if (arr[i][j] != arr[i - 1][j + 1]) { ans = 1 + solve(i - 1, j + 1, arr, 2, 0, n, m, dp); max = Math.max(max, ans); } } } if (i + 1 < n && j + 1 < m) { if (!(arr[i + 1][j + 1] == 1)) { if (arr[i][j] != arr[i + 1][j + 1]) { ans = 1 + solve(i + 1, j + 1, arr, 3, 1, n, m, dp); max = Math.max(max, ans); } } } } else { if (i - 1 >= 0 && j + 1 < m) { if (!(arr[i - 1][j + 1] == 1)) { if (arr[i][j] != arr[i - 1][j + 1]) { ans = 1 + solve(i - 1, j + 1, arr, 2, 1, n, m, dp); max = Math.max(max, ans); } } } } } else if (option == 3) { if (changes == 0) { if (i + 1 < n && j - 1 >= 0) { if (!(arr[i + 1][j - 1] == 1)) { if (arr[i][j] != arr[i + 1][j - 1]) { ans = 1 + solve(i + 1, j - 1, arr, 4, 1, n, m, dp); max = Math.max(max, ans); } } } if (i + 1 < n && j + 1 < m) { if (!(arr[i + 1][j + 1] == 1)) { if (arr[i][j] != arr[i + 1][j + 1]) { ans = 1 + solve(i + 1, j + 1, arr, 3, 0, n, m, dp); max = Math.max(max, ans); } } } } else { if (i + 1 < n && j + 1 < m) { if (!(arr[i + 1][j + 1] == 1)) { if (arr[i][j] != arr[i + 1][j + 1]) { ans = 1 + solve(i + 1, j + 1, arr, 3, 1, n, m, dp); max = Math.max(max, ans); } } } } } else { if (changes == 0) { if (i + 1 < n && j - 1 >= 0) { if (!(arr[i + 1][j - 1] == 1)) { if (arr[i][j] != arr[i + 1][j - 1]) { ans = 1 + solve(i + 1, j - 1, arr, 4, 0, n, m, dp); max = Math.max(max, ans); } } } if (i - 1 >= 0 && j - 1 >= 0) { if (!(arr[i - 1][j - 1] == 1)) { if (arr[i][j] != arr[i - 1][j - 1]) { ans = 1 + solve(i - 1, j - 1, arr, 1, 1, n, m, dp); max = Math.max(max, ans); } } } } else { if (i + 1 < n && j - 1 >= 0) { if (!(arr[i + 1][j - 1] == 1)) { if (arr[i][j] != arr[i + 1][j - 1]) { ans = 1 + solve(i + 1, j - 1, arr, 4, 1, n, m, dp); max = Math.max(max, ans); } } } } } max = Math.max(max, ans); return dp[i][j][option][changes] = max; } } ```
1
0
['Dynamic Programming', 'Recursion']
1
length-of-longest-v-shaped-diagonal-segment
Simple recursive solution | turn or no turn
simple-recursive-solution-turn-or-no-tur-1rs2
IntuitionApproachWe will try to do exactly what we are told to. We will start from a cell containing '1', and explore 4 directions diagonally as long as pattern
Abhishek_Jain_18
NORMAL
2025-02-16T04:51:23.485099+00:00
2025-02-22T14:08:11.070178+00:00
56
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> We will try to do exactly what we are told to. We will start from a cell containing '1', and explore 4 directions diagonally as long as pattern is matched and we are allowed to take one turn (clockwise 90 degrees) which will change the direction. 1. Initialize global arrays di and dj, which will help to find next index diagonally. Notice that if we take a turn, direction index (dir) increases by one cyclically. 2. Traverse on grid, whenever we find '1' we call the helper function 'maxLenPath' which will find length of longest V path. 'maxLenPath' function: 1. If current index is out of bounds it returns 0. 2. If current cell does not matches the required pattern, it returns 0. 3. If turn is not zero, which means we are allowed to take a turn, we will explore both possibilities of turn or no turn and take maximum of both and return it plus one, because we know current cell will be a part of the path. 4. If turn is zero, we will just keep moving on the same diagonal direction and call the function recursively. # Code ```cpp [] class Solution { private: int maxLenPath(int i, int j, int dir, int turn, int pat, int n, int m, vector<vector<int>>& grid){ // cout << i << " " << j << endl; if(!(i < n && i >= 0 && j < m && j >= 0)){ return 0; } if(grid[i][j] != pat){ return 0; } if(turn){ // turn or no turn int nt = 1 + maxLenPath(i + di[dir], j +dj[dir], dir, turn, abs(pat-2),n,m,grid); dir = (dir+1)%4; int t = 1 + maxLenPath(i + di[dir], j +dj[dir], dir,0, abs(pat-2),n,m,grid); return max(nt,t); } else{ return (1 + maxLenPath(i + di[dir], j +dj[dir], dir, turn, abs(pat-2),n,m,grid)); } } public: int dj[4] = {-1,1,1,-1}, di[4] = {-1,-1,1,1}; int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); int ans = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(grid[i][j] == 1){ int maxi = 0; for(int dir = 0; dir < 4; dir++){ maxi = max(maxi,1+maxLenPath(i+di[dir], j+dj[dir], dir, 1, 2, n, m , grid)); } ans = max(ans,maxi); } } } return ans; } }; ```
1
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
|| ✅✅Easiest Solution && DP && #DAY_29th_Of_Daily_Coding🙏🙏 ||
easiest-solution-dp-day_29th_of_daily_co-x3mz
IntuitionApproachComplexity Time complexity: Space complexity: Code
Coding_With_Star
NORMAL
2025-02-16T04:06:05.035467+00:00
2025-02-16T04:06:05.035467+00:00
58
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 ```cpp [] class Solution { public: int lenOfVDiagonal(std::vector<std::vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); vector<vector<int>> ds = {{1, 1}, {1, -1}, {-1, -1}, {-1, 1}}; vector<vector<vector<vector<int>>>> v(4, vector<vector<vector<int>>>(n, vector<vector<int>>(m, vector<int>(3, 0)))); for (int d = 0; d < 4; d++) { int di = ds[d][0], dj = ds[d][1]; if (di == 1 && dj == 1) { for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { for (int e = 0; e < 3; e++) { if (grid[i][j] == e) { int ni = i + di, nj = j + dj; int ne = (e == 1) ? 2 : (e == 2 ? 0 : 2); v[d][i][j][e] = 1 + ((ni >= 0 && ni < n && nj >= 0 && nj < m) ? v[d][ni][nj][ne] : 0); } else { v[d][i][j][e] = 0; } } } } } else if (di == 1 && dj == -1) { for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < m; j++) { for (int e = 0; e < 3; e++) { if (grid[i][j] == e) { int ni = i + di, nj = j + dj; int ne = (e == 1) ? 2 : (e == 2 ? 0 : 2); v[d][i][j][e] = 1 + ((ni >= 0 && ni < n && nj >= 0 && nj < m) ?v[d][ni][nj][ne] : 0); } else { v[d][i][j][e] = 0; } } } } } else if (di == -1 && dj == -1) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int e = 0; e < 3; e++) { if (grid[i][j] == e) { int ni = i + di, nj = j + dj; int ne = (e == 1) ? 2 : (e == 2 ? 0 : 2); v[d][i][j][e] = 1 + ((ni >= 0 && ni < n && nj >= 0 && nj < m) ? v[d][ni][nj][ne] : 0); } else { v[d][i][j][e] = 0; } } } } } else { // di == -1 && dj == 1 for (int i = 0; i < n; i++) { for (int j = m - 1; j >= 0; j--) { for (int e = 0; e < 3; e++) { if (grid[i][j] == e) { int ni = i + di, nj = j + dj; int ne = (e == 1) ? 2 : (e == 2 ? 0 : 2); v[d][i][j][e] = 1 + ((ni >= 0 && ni < n && nj >= 0 && nj < m) ? v[d][ni][nj][ne] : 0); } else { v[d][i][j][e] = 0; } } } } } } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int d = 0; d < 4; d++) { if (grid[i][j] != 1) continue; int L = v[d][i][j][1]; ans = std::max(ans, L); int d2 = (d + 1) % 4; int di = ds[d][0], dj = ds[d][1]; int di2 = ds[d2][0], dj2 = ds[d2][1]; for (int t = 1; t <= L; t++) { int r = i + (t - 1) * di, c = j + (t - 1) * dj; int nr = r + di2, nc = c + dj2; if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue; int exp = (t % 2 == 1) ? 2 : 0; int L2 = v[d2][nr][nc][exp]; ans = std::max(ans, t + L2); } } } } return ans; } }; ```
1
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
DP keep track of direction and whether turned
dp-keep-track-of-direction-and-whether-t-kbvj
null
theabbie
NORMAL
2025-02-16T04:01:50.359870+00:00
2025-02-16T04:01:50.359870+00:00
130
false
```python3 [] class Solution: def lenOfVDiagonal(self, grid): m = len(grid) n = len(grid[0]) clock = {(1, 1): (1, -1), (1, -1): (-1, -1), (-1, -1): (-1, 1), (-1, 1): (1, 1)} @cache def dp(i, j, dx, dy, done, even): if not (0 <= i < m) or not (0 <= j < n): return 0 if grid[i][j] == 1: return 0 if even and grid[i][j] != 2: return 0 if not even and grid[i][j] != 0: return 0 cdx, cdy = clock[(dx, dy)] return 1 + max(dp(i + dx, j + dy, dx, dy, done, not even), dp(i + cdx, j + cdy, cdx, cdy, True, not even) if not done else 0) res = 0 for i in range(m): for j in range(n): if grid[i][j] == 1: for dx, dy in clock: res = max(res, 1 + dp(i + dx, j + dy, dx, dy, False, True)) return res ```
1
0
['Python3']
1
length-of-longest-v-shaped-diagonal-segment
Java DP solution
java-dp-solution-by-precel332-2d8l
IntuitionMantain dp array with the best score for every state of the sequence (4 direction before rotation and 4 directions after rotation). Perform Depth first
precel332
NORMAL
2025-03-20T17:18:33.692842+00:00
2025-03-20T17:18:33.692842+00:00
15
false
# Intuition Mantain dp array with the best score for every state of the sequence (4 direction before rotation and 4 directions after rotation). Perform Depth first traversal to compute dp array. # Complexity - Time complexity: $$O(n*m)$$ - Space complexity: $$O(n*m)$$ # Code ```java [] class Solution { int[][] grid; int[][][] dp; int[][] directions = { {-1, -1}, {1, -1}, {1, 1}, {-1, 1} }; public int lenOfVDiagonal(int[][] grid) { this.grid = grid; this.dp = new int[grid.length][grid[0].length][8]; int ans = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] == 1) { dfs(i, j, false, 0); dfs(i, j, false, 1); dfs(i, j, false, 2); dfs(i, j, false, 3); for (int k = 0; k < 8; k++) { ans = Math.max(ans, dp[i][j][k]); } } } } return ans; } private void dfs(int x, int y, boolean hasRotated, int dir) { dp[x][y][state(hasRotated, dir)] = 1; if ( inBounds(newX(x, dir), newY(y, dir)) && grid[newX(x, dir)][newY(y, dir)] == getNextSeq(grid[x][y]) ) { if (dp[newX(x, dir)][newY(y, dir)][state(hasRotated, dir)] == 0) { dfs(newX(x, dir), newY(y, dir), hasRotated, dir); } int val = dp[x][y][state(hasRotated, dir)]; int newVal = dp[newX(x, dir)][newY(y, dir)][state(hasRotated, dir)] + 1; dp[x][y][state(hasRotated, dir)] = Math.max(val, newVal); } if (!hasRotated && grid[x][y] != 1) { int newDir = rotate(dir); if ( inBounds(newX(x, newDir), newY(y, newDir)) && grid[newX(x, newDir)][newY(y, newDir)] == getNextSeq(grid[x][y]) ) { if (dp[newX(x, newDir)][newY(y, newDir)][state(true, newDir)] == 0) { dfs(newX(x, newDir), newY(y, newDir), true, newDir); } int val = dp[x][y][state(false, dir)]; int newVal = dp[newX(x, newDir)][newY(y, newDir)][state(true, newDir)] + 1; dp[x][y][state(false, dir)] = Math.max(val, newVal); } } } int rotate(int dir) { return (dir + 3) % 4; } boolean inBounds(int x, int y) { return x >= 0 && x < grid.length && y >= 0 && y < grid[0].length; } int getNextSeq(int s) { return s == 2 ? 0 : 2; } int state(boolean hasRotated, int direction) { return hasRotated ? 4 + direction : direction; } int newX(int x, int direction) { return x + directions[direction][0]; } int newY(int y, int direction) { return y + directions[direction][1]; } } ```
0
0
['Java']
0
length-of-longest-v-shaped-diagonal-segment
Simple Self-explanatory DP | Beats 100%
simple-self-explanatory-dp-beats-100-by-gzb5e
IntuitionAt every 1, we have 4 choices of directions. And at each further point, we have 2 choices (to continue in same dir or make a turn). This screams for a
pramodhv_28
NORMAL
2025-03-16T08:19:02.828659+00:00
2025-03-16T08:19:02.828659+00:00
14
false
# Intuition At every 1, we have 4 choices of directions. And at each further point, we have 2 choices (to continue in same dir or make a turn). This screams for a dp approach. While the intuition was simple, its quite hard to implement - Hence I feel the LC hard tag is justified. # Approach Dimensions defined - Row, column, current direction, bool to check whether turn has been taken # Complexity - Time complexity: O(4*n*m) - Space complexity: O(n*m) # Code ```cpp [] class Solution { public: int m,n; vector<vector<int>> dir = { {-1,-1}, {-1,1}, {1,1}, {1,-1} }; int dp[501][501][4][2]; int f(vector<vector<int>>& grid, int i,int j,int k,int turn,bool t){ if(i<0 || i>=n || j<0 || j>=m) return 0; if(dp[i][j][k][turn]!=-1) return dp[i][j][k][turn]; int val=(t)?0:2; if(grid[i][j]!=val) return 0; int ni=i+dir[k][0]; int nj=j+dir[k][1]; int p1=f(grid,ni,nj,k,turn,!t); int p2=0; if(turn<1){ int nk=(k+1)%4; int ni2=i+dir[nk][0],nj2=j+dir[nk][1]; p2=f(grid,ni2,nj2,nk,turn+1,!t); } return dp[i][j][k][turn]=1+max(p1,p2); } int lenOfVDiagonal(vector<vector<int>>& grid) { int res=0; n=grid.size(),m=grid[0].size(); memset(dp,-1,sizeof(dp)); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(grid[i][j]==1){ for(int k=0;k<4;k++) res=max(res,1+f(grid,i+dir[k][0],j+dir[k][1],k,0,0)); } } } return res; } }; ```
0
0
['Dynamic Programming', 'Memoization', 'Matrix', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
Python || Dynamic Programming || Faster than 94%
python-dynamic-programming-faster-than-9-f4wl
IntuitionApproachComplexity Time complexity: O(n * m) Space complexity: O(n * m)Code
vilaparthibhaskar
NORMAL
2025-03-06T23:23:36.813317+00:00
2025-03-06T23:23:53.077302+00:00
29
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)$$ --> O(n * m) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n * m) # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: def helper(grid): r, c = len(grid), len(grid[0]) dp1 = [[1 if grid[j][i] != 1 else 0 for i in range(c)] for j in range(r)] for i in range(r - 2, -1, -1): for j in range(c - 1, 0, -1): if grid[i][j] != 1: if grid[i][j] == 0: dp1[i][j] = 1 + (dp1[i + 1][j - 1] if grid[i + 1][j - 1] == 2 else 0) else: dp1[i][j] = 1 + (dp1[i + 1][j - 1] if grid[i + 1][j - 1] == 0 else 0) dp2 = [[dp1[j][i] for i in range(c)] for j in range(r)] for i in range(r - 2, -1, -1): for j in range(c - 2, -1, -1): if grid[i][j] != 1: if grid[i][j] == 0: dp2[i][j] = max(dp2[i][j], 1 + (dp2[i + 1][j + 1] if grid[i + 1][j + 1] == 2 else 0)) else: dp2[i][j] = max(dp2[i][j], 1 + (dp2[i + 1][j + 1] if grid[i + 1][j + 1] == 0 else 0)) ans = 0 if count == 0 else 1 for i in range(r - 2, -1, -1): for j in range(c - 2, -1, -1): if grid[i][j] == 1 and grid[i + 1][j + 1] == 2: ans = max(ans, 1 + dp2[i + 1][j + 1]) return ans def rotate(matrix): return [list(row) for row in zip(*matrix[::-1])] count = 0 mx = 0 for i in grid: for j in i: if j == 1: mx = 1 break for i in range(4): mx = max(mx, helper(grid)) grid = rotate(grid) return mx ```
0
0
['Dynamic Programming', 'Matrix', 'Python3']
0
length-of-longest-v-shaped-diagonal-segment
Self-explanatory DP
self-explanatory-dp-by-iofjuupasli-fss6
IntuitionThe first intuition was that it's either DP or just BFS brute force. For DP you have to try to iterate through the data and see if it's possible to get
iofjuupasli
NORMAL
2025-03-06T19:13:55.582328+00:00
2025-03-06T19:13:55.582328+00:00
19
false
# Intuition The first intuition was that it's either DP or just BFS brute force. For DP you have to try to iterate through the data and see if it's possible to get the new solution from already iterated results. BFS is easy to implement, but obviously the solution will be less effective, so I need to disprove the DP solution first to be sure that BFS is the most optimal. I found that it's possible to get a DP solution for one direction by iterating the matrix in the opposite direction. So to check the top-left direction from the starting point, you have to iterate the matrix from top-left to right-bottom, and at each point you have solutions from previous steps. This means that by iterating 4 times in different directions we can get the answer. So DP can be used. # Approach Once it's been proven that DP is possible, we need to understand what state we need at each step. For this task we need to keep in state: - Coordinates of the current cell - If we have already made a turn, or if we still have such an option - Which direction was the last one so that we know where to continue or where to turn. From this we construct the cache for DP with the correct size, and provide the logic within the DP step function. # Complexity - Time complexity: $$O(n*m)$$ We iterate each cell, and for each cell we check each direction at most once. The number of directions is constant, so it doesn't count in the complexity. - Space complexity: $$O(n*m)$$ We keep 8 values for each cell: step-available/no-step for each of the 4 directions. 8 is constant so we don't count it. # Code ```typescript [] type Matrix = Array<Array<number>>; class Coord { i: number; j: number; static directions: Array<Coord> = [ new Coord(-1, -1), // top-left new Coord(-1, 1), // top-right new Coord(1, 1), // bottom-right new Coord(1, -1), // bottom-left ]; constructor(i: number, j: number) { this.i = i; this.j = j; } add(delta: Coord): Coord { return new Coord(this.i + delta.i, this.j + delta.j); } invert(): Coord { return new Coord(-this.i, -this.j); } checkBounds(max: Coord): boolean { return this.i >= 0 && this.j >= 0 && this.i < max.i && this.j < max.j; } getValue(matrix: Matrix): number { return matrix[this.i][this.j]; } } function matrixMax(matrix: Matrix, mapFn: (value: number, coord: Coord) => number): number { const n = matrix.length; const m = matrix[0].length; let max = -Infinity; for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { const result = mapFn(matrix[i][j], new Coord(i, j)); max = Math.max(max, result); } } return max; } const NO_TURN = 0; const TURN = 1; const TURN_OPTIONS = 2; const DIRECTION_OPTIONS = Coord.directions.length; const START_VALUE = 1; const expectedValueMap = [ 2, // 2 after 0 2, // 2 after 1 0, // 0 after 2 ]; function clockwiseTurn(directionIndex: number): number { return (directionIndex + 1) % DIRECTION_OPTIONS; } function lenOfVDiagonal(grid: Matrix): number { const bounds = new Coord(grid.length, grid[0].length); function memo<T>(fn: T): T { const cache = new Array(bounds.i * bounds.j * TURN_OPTIONS * DIRECTION_OPTIONS); return (((c: Coord, turn: number, directionIndex: number) => { const hash = (c.i * bounds.j + c.j) * TURN_OPTIONS * DIRECTION_OPTIONS + turn * DIRECTION_OPTIONS + directionIndex; const value = cache[hash]; if (value !== undefined) { return value; } const result = (fn as any)(c, turn, directionIndex); cache[hash] = result; return result; }) as any) as T; } const dp = memo((coord: Coord, turn: number, directionIndex: number) => { const direction = Coord.directions[directionIndex]; const prevCoord = coord.add(direction.invert()); const prevValue = prevCoord.getValue(grid); const expectedValue = expectedValueMap[prevValue]; const value = coord.getValue(grid); if (value !== expectedValue) { return 0; } const nextCoord = coord.add(direction); const nextResult = nextCoord.checkBounds(bounds) ? 1 + dp(nextCoord, turn, directionIndex) : 1; let turnResult = 1; if (turn) { const turnDirectionIndex = clockwiseTurn(directionIndex); const turnCoord = coord.add(Coord.directions[turnDirectionIndex]); if (turnCoord.checkBounds(bounds)) { turnResult = 1 + dp(turnCoord, NO_TURN, turnDirectionIndex); } } return Math.max(nextResult, turnResult); }); return matrixMax(grid, (value, coord) => { if (value !== START_VALUE) { return 0; } return 1 + Math.max( ...Coord.directions.map((direction, i) => { const nextCoord = coord.add(direction); if (nextCoord.checkBounds(bounds)) { return dp(nextCoord, TURN, i); } return 0; }) ); }); }; ```
0
0
['Dynamic Programming', 'Memoization', 'Matrix', 'TypeScript', 'JavaScript']
0
length-of-longest-v-shaped-diagonal-segment
CPP || Recursion + Memo || 4D DP
cpp-recursion-memo-4d-dp-by-shubham_loha-aatt
Code
shubham_lohan
NORMAL
2025-02-24T18:33:41.070989+00:00
2025-02-24T18:33:41.070989+00:00
8
false
# Code ```cpp [] #include <bits/stdc++.h> using namespace std; class Solution { public: int n, m; int dp[501][501][4][2]; // DP table: [row][col][direction][turn] int dx[4] = {1, 1, -1, -1}; int dy[4] = {1, -1, -1, 1}; bool isValidTurn(int oldDir, int newDir) { return (newDir != oldDir) && ((oldDir + 1) % 4 == newDir); } int solve(int i, int j, int curr, int dir, int turn, vector<vector<int>>& grid) { if (i < 0 || i >= n || j < 0 || j >= m || grid[i][j] != curr) { return 0; } if (dp[i][j][dir][turn] != -1) { return dp[i][j][dir][turn]; } int maxLength = 1 + solve(i + dx[dir], j + dy[dir], 2 - curr, dir, turn, grid); if (turn == 0) { for (int newDir = 0; newDir < 4; newDir++) { if (isValidTurn(dir, newDir)) { maxLength = max(maxLength, 1 + solve(i + dx[newDir], j + dy[newDir], 2 - curr, newDir, 1, grid)); } } } return dp[i][j][dir][turn] = maxLength; } int lenOfVDiagonal(vector<vector<int>>& grid) { n = grid.size(); m = grid[0].size(); memset(dp, -1, sizeof(dp)); int maxLength = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { for (int dir = 0; dir < 4; dir++) { maxLength = max(maxLength, 1 + solve(i + dx[dir], j + dy[dir],2, dir, 0, grid)); } } } } return maxLength; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
DP + Memoization
dp-memoization-by-aadarshkt-5981
IntuitionSearch all the possiblities.ApproachFor every one go in four directions.Complexity Time complexity:O(n^2) Space complexity:O(n^2) Code
aadarshkt
NORMAL
2025-02-23T04:36:25.184626+00:00
2025-02-23T04:36:25.184626+00:00
4
false
# Intuition Search all the possiblities. # Approach For every one go in four directions. # Complexity - Time complexity: O(n^2) - Space complexity: O(n^2) # Code ```cpp [] class Solution { public: bool inrange(int i, int j, int n, int m){ if(i >= 0 && i < n && j >= 0 && j < m)return true; return false; } //fl2 - turned or not. //fl - 2 or 0 (1 - 2, 0 - 0) int dp[501][501][2][5][2]; int solve(vector<vector<int>>& g, int i, int j, int n, int m, int fl, int dir, int fl2){ if(!inrange(i, j, n, m))return 0; if(fl && g[i][j] != 2)return 0; if(!fl && g[i][j] != 0)return 0; if(dp[i][j][fl][dir][fl2] != -1)return dp[i][j][fl][dir][fl2]; int len; if(fl2){ if(dir == 1){ len = 1 + solve(g, i+1, j+1, n, m, !fl, 1, 1); } else if(dir == 2){ len = 1 + solve(g, i+1, j-1, n, m, !fl, 2, 1); } else if(dir == 3){ len = 1 + solve(g, i-1, j-1, n, m, !fl, 3, 1); } else if(dir == 4){ len = 1 + solve(g, i-1, j+1, n, m, !fl, 4, 1); } } else { if(dir == 1){ len = 1 + max(solve(g, i-1, j+1, n, m, !fl, 1, 0), solve(g, i+1, j+1, n, m, !fl, 1, 1)); } else if(dir == 2){ len = 1 + max(solve(g, i+1, j+1, n, m, !fl, 2, 0), solve(g, i+1, j-1, n, m, !fl, 2, 1)); } else if(dir == 3){ len = 1 + max(solve(g, i+1, j-1, n, m, !fl, 3, 0), solve(g, i-1, j-1, n, m, !fl, 3, 1)); } else if(dir == 4){ len = 1 + max(solve(g, i-1, j-1, n, m, !fl, 4, 0), solve(g, i-1, j+1, n, m, !fl, 4, 1)); } } return dp[i][j][fl][dir][fl2] = len; } int go_diag_give_max(vector<vector<int>>& g, int i, int j, int n, int m){ return max({solve(g, i-1, j+1, n, m, 1, 1, 0), solve(g, i+1, j+1, n, m, 1, 2, 0), solve(g, i+1, j-1, n, m, 1, 3, 0), solve(g, i-1, j-1, n, m, 1, 4, 0)}); } int lenOfVDiagonal(vector<vector<int>>& g) { int n = g.size(), m = g[0].size(); memset(dp, -1, sizeof(dp)); int ans = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(g[i][j] == 1){ int val = go_diag_give_max(g, i, j, n, m); ans = max(ans, val+1); } } } return ans; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
Rust solution
rust-solution-by-abhineetraj1-qwxm
IntuitionThe problem asks for the longest length of a "V-shaped" diagonal in a given 2D grid, where cells are either 1 (part of a path) or 0 (empty). A "V-shape
abhineetraj1
NORMAL
2025-02-22T03:06:21.395311+00:00
2025-02-22T03:06:37.460079+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem asks for the longest length of a "V-shaped" diagonal in a given 2D grid, where cells are either 1 (part of a path) or 0 (empty). A "V-shaped" diagonal means starting from a 1 cell and moving in one of the four diagonal directions, followed by a possible switch to another diagonal direction at most once. The objective is to find the maximum length of such a path. # Approach <!-- Describe your approach to solving the problem. --> The problem is solved using dynamic programming (DP) with memoization. We maintain a 5-dimensional DP table to store the results of subproblems, where each entry represents the longest V-shaped diagonal starting from a specific cell (i, j) with a given direction (dir), turn state (turn), and current cell value (curr). The solve function recursively explores the grid, moving in one of the four diagonal directions and allowing a single direction switch, depending on the turn state. At each step, we either continue in the current direction or switch to a new direction, while caching intermediate results in the DP table to avoid redundant computations. The solution iterates through the grid, checking each 1 cell and attempting to find the longest diagonal path. The final answer is the longest diagonal found during these explorations. # Complexity - Time complexity: O(n * m * 4) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(N ∗ M ∗ 4 ∗ 3 ∗ 2) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```rust [] impl Solution { pub fn len_of_v_diagonal(grid: Vec<Vec<i32>>) -> i32 { let n = grid.len(); let m = grid[0].len(); let mut dp = vec![vec![vec![vec![vec![None; 4]; 3]; 2]; m]; n]; // DP table initialization let mut ans = 0; for i in 0..n { for j in 0..m { if grid[i][j] == 1 { for k in 0..4 { ans = ans.max(1 + Self::solve(i as i32 + Self::x()[k], j as i32 + Self::y()[k], 0, 2, k, &grid, &mut dp)); } } } } ans } fn solve(i: i32, j: i32, turn: i32, curr: i32, dir: usize, grid: &Vec<Vec<i32>>, dp: &mut Vec<Vec<Vec<Vec<Vec<Option<i32>>>>>>) -> i32 { let n = grid.len() as i32; let m = grid[0].len() as i32; if i < 0 || j < 0 || i >= n || j >= m || grid[i as usize][j as usize] != curr { return 0; } if let Some(val) = dp[i as usize][j as usize][turn as usize][curr as usize][dir] { return val; } let x = vec![1, 1, -1, -1]; // Direction vectors let y = vec![1, -1, -1, 1]; // Direction vectors let mut ans = 1 + Self::solve(i + x[dir], j + y[dir], turn, 2 - curr, dir, grid, dp); if turn == 0 { ans = ans.max(1 + Self::solve(i + x[(dir + 1) % 4], j + y[(dir + 1) % 4], 1, 2 - curr, (dir + 1) % 4, grid, dp)); } dp[i as usize][j as usize][turn as usize][curr as usize][dir] = Some(ans); ans } fn x() -> Vec<i32> { vec![1, 1, -1, -1] } fn y() -> Vec<i32> { vec![1, -1, -1, 1] } } ```
0
0
['Dynamic Programming', 'Memoization', 'Matrix', 'Rust']
0
length-of-longest-v-shaped-diagonal-segment
DFS | C++
dfs-c-by-siddharth96shukla-z037
Code
siddharth96shukla
NORMAL
2025-02-20T14:34:53.898756+00:00
2025-02-20T14:34:53.898756+00:00
7
false
# Code ```cpp [] class Solution { public: int m, n; bool chk(int i, int j){ return (i>=0 && j>=0 && i<n && j<m); } int dfs(vector<vector<int>>&A, int ri, int ci, int r, int c, bool ir){ int cv=A[r][c], ret=0; if(cv==2){ if(chk(r+ri, c+ci) && A[r+ri][c+ci]==0)ret=max(ret, dfs(A, ri, ci, r+ri, c+ci, ir)); if(ri==1 && ci==1){ if(chk(r+1, c-1) && A[r+1][c-1]==0 && !ir)ret=max(ret, dfs(A, 1, -1, r+1, c-1, !ir)); } else if(ri==-1 && ci==-1){ if(chk(r-1, c+1) && A[r-1][c+1]==0 && !ir)ret=max(ret, dfs(A, -1, 1, r-1, c+1, !ir)); } else if(ri==-1 && ci==1){ if(chk(r+1, c+1) && A[r+1][c+1]==0 && !ir)ret=max(ret, dfs(A, 1, 1, r+1, c+1, !ir)); } else{ if(chk(r-1, c-1) && A[r-1][c-1]==0 && !ir)ret=max(ret, dfs(A, -1, -1, r-1, c-1, !ir)); } } if(cv==0){ if(chk(r+ri, c+ci) && A[r+ri][c+ci]==2)ret=max(ret, dfs(A, ri, ci, r+ri, c+ci, ir)); if(ri==1 && ci==1){ if(chk(r+1, c-1) && A[r+1][c-1]==2 && !ir)ret=max(ret, dfs(A, 1, -1, r+1, c-1, !ir)); } else if(ri==-1 && ci==-1){ if(chk(r-1, c+1) && A[r-1][c+1]==2 && !ir)ret=max(ret, dfs(A, -1, 1, r-1, c+1, !ir)); } else if(ri==-1 && ci==1){ if(chk(r+1, c+1) && A[r+1][c+1]==2 && !ir)ret=max(ret, dfs(A, 1, 1, r+1, c+1, !ir)); } else{ if(chk(r-1, c-1) && A[r-1][c-1]==2 && !ir)ret=max(ret, dfs(A, -1, -1, r-1, c-1, !ir)); } } return ret+1; } int lenOfVDiagonal(vector<vector<int>>& A) { int ans=0;bool iv=0; n=A.size();m=A[0].size(); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(A[i][j]==1){ iv=1; if(chk(i+1, j+1) && A[i+1][j+1]==2)ans=max(ans, dfs(A, 1, 1, i+1, j+1, 0)); if(chk(i-1, j-1) && A[i-1][j-1]==2)ans=max(ans, dfs(A, -1, -1, i-1, j-1, 0)); if(chk(i-1, j+1) && A[i-1][j+1]==2)ans=max(ans, dfs(A, -1, 1, i-1, j+1, 0)); if(chk(i+1, j-1) && A[i+1][j-1]==2)ans=max(ans, dfs(A, 1, -1, i+1, j-1, 0)); } } } return (ans==0)?iv:ans+1; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
C++ | Memoization | Beats 90% | Optimized Recursive Approach
c-memoization-beats-90-optimized-recursi-8s8i
IntuitionThe problem requires finding the longest valid diagonal path in the grid, following specific movement rules. The key observation is that a valid path m
Tarikcr7
NORMAL
2025-02-20T08:40:32.429970+00:00
2025-02-20T08:40:32.429970+00:00
16
false
# Intuition The problem requires finding the longest valid diagonal path in the grid, following specific movement rules. The key observation is that a valid path must start from cells containing `1`, continue through cells containing `2`, and follow diagonal directions. The direction can change under certain conditions, allowing exploration of different possible paths. By leveraging this observation, we can efficiently traverse the grid and determine the longest path while avoiding redundant calculations using memoization. # Approach 1. Iterate through the grid to find all occurrences of `1`, as these serve as starting points. 2. For each `1`, explore all four diagonal directions (`dx, dy` arrays) to check if the next cell contains `2`. 3. Use a recursive function with memoization (`dp` array) to explore the longest valid path in both the current direction and an alternate direction if a turn is possible. 4. Store results in `dp` to avoid recomputation. 5. Track and return the maximum path length found across all valid starting positions. # Complexity - Time complexity: O(n × m × 4 × 2) = O(n × m) - Space complexity: O(n × m × 4 × 2) = O(n × m) # Code ```cpp [] #pragma G++ optimize("o3") class Solution { public: int dx[4] = {1, -1, 1, -1}; int dy[4] = {1, -1, -1, 1}; int n, m; int nextDirLookup[4] = {2, 3, 1, 0}; int func(vector<vector<int>>& grid, int i, int j, int dir, bool turn, vector<int>& dp) { if (i < 0 || j < 0 || i >= n || j >= m) return 0; if (dp[i * m * 8 + j * 8 + dir + turn * 4] != -1) return dp[i * m * 8 + j * 8 + dir + turn * 4]; int makeTurn = 1, notMakeTurn = 1; int curr = grid[i][j]; if (!turn) { int newDir = nextDirLookup[dir]; int nx = i + dx[newDir], ny = j + dy[newDir]; if (nx >= 0 && ny >= 0 && nx < n && ny < m) { int nextVal = grid[nx][ny]; if (curr == (nextVal + 2) % 4) { makeTurn += func(grid, nx, ny, newDir, true, dp); } } } int nx = i + dx[dir], ny = j + dy[dir]; if (nx >= 0 && ny >= 0 && nx < n && ny < m) { int nextVal = grid[nx][ny]; if (curr == (nextVal + 2) % 4) { notMakeTurn += func(grid, nx, ny, dir, turn, dp); } } return dp[i * m * 8 + j * 8 + dir + turn * 4] = max(makeTurn, notMakeTurn); } int lenOfVDiagonal(vector<vector<int>>& grid) { cin.tie(nullptr)->sync_with_stdio(false); n = grid.size(); m = grid[0].size(); int ans = 0; vector<int> dp(n * m * 8, -1); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] != 1) continue; ans = max(ans, 1); for (int k = 0; k < 4; k++) { int nx = i + dx[k], ny = j + dy[k]; if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; if (grid[nx][ny] != 2) continue; ans = max(ans, 1 + func(grid, nx, ny, k, false, dp)); } } } dp.clear(); return ans; } }; ```
0
0
['Dynamic Programming', 'Memoization', 'Matrix', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
Easy DP Memoization solution with TC (n*m*4*2)
easy-dp-memoization-solution-with-tc-nm4-vikh
IntuitionApproachComplexity Time complexity: Space complexity: Code
vaibhav11022003
NORMAL
2025-02-20T07:26:34.449554+00:00
2025-02-20T07:26:34.449554+00:00
8
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 ```cpp [] class Solution { public: int dc[4]={-1,1,1,-1},dr[4]={-1,-1,1,1}; int n,m; int fun(int r,int c,int dir,int turn,vector<vector<int>>&grid,int dp[500][500][4][2]) { if(dp[r][c][dir][turn]!=-1)return dp[r][c][dir][turn]; int next=grid[r][c]==2?0:2; //not change int notchange=0; int nr=r+dr[dir],nc=c+dc[dir]; if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]==next)notchange=fun(nr,nc,dir,turn,grid,dp); //change int change=0; if(turn>0) { int newdir=(dir+1)%4; nr=r+dr[newdir],nc=c+dc[newdir]; if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]==next)change=fun(nr,nc,newdir,turn-1,grid,dp); } return dp[r][c][dir][turn]=max(change,notchange)+1; } int lenOfVDiagonal(vector<vector<int>>& grid) { n=grid.size(); m=grid[0].size(); int dp[500][500][4][2]; memset(dp, -1, sizeof(dp)); int ans=0; for(int r=0;r<n;r++) { for(int c=0;c<m;c++) { if(grid[r][c]==1) { ans=max(ans,1); for(int i=0;i<4;i++) { int nr=r+dr[i],nc=c+dc[i]; if(nr>=0&&nr<n&&nc>=0&&nc<m&&grid[nr][nc]==2) { ans=max(ans,1+fun(nr,nc,i,1,grid,dp)); } } } } } return ans; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
OpenAI solution
openai-solution-by-dawninghu-3y7w
I was just curious whether OpenAI can solve it, I pasted the question, and choose answer with reasoning. Is data structure and algorithm an outdated skill?this
dawninghu
NORMAL
2025-02-20T07:22:40.087173+00:00
2025-02-20T07:22:40.087173+00:00
9
false
I was just curious whether OpenAI can solve it, I pasted the question, and choose answer with reasoning. Is data structure and algorithm an outdated skill? this is what I got: # Code ```cpp [] class Solution { public: int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); int best = 0; // For a V shape the allowed turn is a 90° clockwise turn. // For a given diagonal d₀, its clockwise rotation d₁ is computed as (dy, -dx). // We consider the four diagonal directions: // d₀ = (-1,-1) -> d₁ = (-1, 1) // d₀ = (-1, 1) -> d₁ = (1, 1) // d₀ = (1, 1) -> d₁ = (1, -1) // d₀ = (1, -1) -> d₁ = (-1,-1) vector<pair<pair<int,int>, pair<int,int>>> dirPairs = { {{-1,-1}, {-1,1}}, {{-1, 1}, { 1,1}}, {{ 1, 1}, { 1,-1}}, {{ 1,-1}, {-1,-1}} }; // Iterate over all cells; a valid segment must start at a cell containing 1. for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] != 1) continue; for (auto &p : dirPairs) { auto d0 = p.first; auto d1 = p.second; // Simulate the straight arm along d₀ starting at (i,j) with sequence index 0. // (The sequence is: index 0: 1, index 1: 2, index 2: 0, index 3: 2, index 4: 0, …) auto candidates = simulateArmCandidates(grid, i, j, d0.first, d0.second, 0); // Each candidate is a tuple: (x, y, seqIndex, lengthSoFar) for (auto &cand : candidates) { int cx, cy, seq, len; tie(cx, cy, seq, len) = cand; best = max(best, len); // option with no turn // Option with turn: extend further in the clockwise direction d₁. int extra = simulateTurn(grid, cx, cy, d1.first, d1.second, seq); best = max(best, len + extra); } } } } return best; } private: // Simulate the straight arm in a given direction. // Returns a vector of candidates: each candidate is (x, y, current sequence index, length so far). // The starting cell (x,y) is assumed to satisfy the sequence (with startIndex). vector<tuple<int,int,int,int>> simulateArmCandidates(const vector<vector<int>>& grid, int x, int y, int dx, int dy, int startIndex) { int n = grid.size(), m = grid[0].size(); vector<tuple<int,int,int,int>> res; res.push_back({x, y, startIndex, 1}); int curX = x, curY = y; int curSeq = startIndex; int curLen = 1; while (true) { int newX = curX + dx, newY = curY + dy; int nextSeq = curSeq + 1; int expected = (nextSeq % 2 == 1) ? 2 : 0; // index0=1, index1=2, index2=0, etc. if (newX < 0 || newX >= n || newY < 0 || newY >= m) break; if (grid[newX][newY] != expected) break; curX = newX; curY = newY; curSeq = nextSeq; curLen++; res.push_back({curX, curY, curSeq, curLen}); } return res; } // From the current candidate (which has been reached with sequence index 'currentSeq'), // simulate extension in the turned direction (dx, dy). // Return the number of additional cells we can add (not counting the candidate cell itself). int simulateTurn(const vector<vector<int>>& grid, int x, int y, int dx, int dy, int currentSeq) { int n = grid.size(), m = grid[0].size(); int add = 0; int curX = x, curY = y; int seq = currentSeq; while (true) { int newX = curX + dx, newY = curY + dy; int nextSeq = seq + 1; int expected = (nextSeq % 2 == 1) ? 2 : 0; if (newX < 0 || newX >= n || newY < 0 || newY >= m) break; if (grid[newX][newY] != expected) break; add++; curX = newX; curY = newY; seq = nextSeq; } return add; }}; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
My Solutions
my-solutions-by-hope_ma-qdw0
null
hope_ma
NORMAL
2025-02-18T10:31:31.545999+00:00
2025-02-18T10:31:31.545999+00:00
7
false
``` /** * Time Complexity: O(rows * cols) * Space Complexity: O(rows * cols) * where `rows` is the number of the rows of the matrix `grid` * `cols` is the number of the columns of the matrix `grid` */ class Solution { private: static constexpr int directions[] = {1, 1, -1, -1, 1}; static constexpr int n_directions = 4; static constexpr int unmemorized = -1; static constexpr int turns = 2; using a1_t = array<int, turns>; using a2_t = array<a1_t, n_directions>; using v3_t = vector<a2_t>; using v4_t = vector<v3_t>; public: int lenOfVDiagonal(const vector<vector<int>> &grid) { constexpr int starting_value = 1; constexpr int first_value = 2; constexpr int initial_turns = 1; const int rows = static_cast<int>(grid.size()); const int cols = static_cast<int>(grid.front().size()); int ret = 0; v4_t memo( rows, v3_t( cols, a2_t{ a1_t{unmemorized, unmemorized}, a1_t{unmemorized, unmemorized}, a1_t{unmemorized, unmemorized}, a1_t{unmemorized, unmemorized} } ) ); for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { if (grid[r][c] == starting_value) { for (int d = 0; d < n_directions; ++d) { ret = max(ret, dfs(grid, r, c, d, initial_turns, first_value, memo)); } } } } return ret; } private: int dfs(const vector<vector<int>> &grid, const int r, const int c, const int d, const int turns, const int target_value, v4_t &memo) { int &ret = memo[r][c][d][turns]; if (ret != unmemorized) { return ret; } const int rows = static_cast<int>(grid.size()); const int cols = static_cast<int>(grid.front().size()); const int nr = r + directions[d]; const int nc = c + directions[d + 1]; ret = 0; if (nr > -1 && nr < rows && nc > -1 && nc < cols && grid[nr][nc] == target_value) { ret = dfs(grid, nr, nc, d, turns, target_value ^ 2, memo); if (turns > 0) { ret = max(ret, dfs(grid, nr, nc, (d + 1) % n_directions, turns - 1, target_value ^ 2, memo)); } } return ++ret; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
Brute Force using Memoization DP in C++ || Easy to Understand
brute-force-using-memoization-dp-in-c-ea-efvv
IntuitionApproachComplexity Time complexity: Space complexity: Code
sumitgarg380
NORMAL
2025-02-18T09:40:31.798290+00:00
2025-02-18T09:40:31.798290+00:00
12
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 ```cpp [] #include <iostream> #include <vector> #include <unordered_map> using namespace std; class Solution { public: vector<vector<int>> dirs = {{1, 1}, {1, -1}, {-1, -1}, {-1, 1}}; int n, m; vector<vector<vector<vector<int>>>> memo; // Memoization table int dfs(int row, int col, int dir, bool turned, vector<vector<int>>& grid, int idx) { if (row < 0 || row >= n || col < 0 || col >= m) return 0; int prevRow = row - dirs[dir][0], prevCol = col - dirs[dir][1]; if (idx == 1 && grid[row][col] == 0) return 0; if (idx > 0 && (prevRow < 0 || prevRow >= n || prevCol < 0 || prevCol >= m || grid[prevRow][prevCol] == grid[row][col] || grid[row][col] == 1)) { return 0; } if (memo[row][col][dir][turned] != -1) return memo[row][col][dir][turned]; int sameDir = 1 + dfs(row + dirs[dir][0], col + dirs[dir][1], dir, turned, grid, idx + 1); int turnDir = 0; if (!turned) { int newDir = (dir + 1) % 4; turnDir = 1 + dfs(row + dirs[newDir][0], col + dirs[newDir][1], newDir, true, grid, idx + 1); } return memo[row][col][dir][turned] = max(sameDir, turnDir); } int lenOfVDiagonal(vector<vector<int>>& grid) { n = grid.size(), m = grid[0].size(); memo.assign(n, vector<vector<vector<int>>>(m, vector<vector<int>>(4, vector<int>(2, -1)))); int maxLength = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { for (int d = 0; d < 4; d++) { maxLength = max(maxLength, dfs(i, j, d, false, grid, 0)); } } } } return maxLength; } }; ```
0
0
['C++']
0
length-of-longest-v-shaped-diagonal-segment
Python Top-Down DP
python-top-down-dp-by-danieljhkim-y7de
Intuitionfor each 1's -> go DFS -> return max distance traveledComplexity Time complexity: O(n∗m) Space complexity: O(n∗m) Code
danieljhkim
NORMAL
2025-02-18T00:53:10.422058+00:00
2025-02-18T00:53:10.422058+00:00
35
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> for each 1's -> go DFS -> return max distance traveled # Complexity - Time complexity: $$O(n * m)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(n * m)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def lenOfVDiagonal(self, grid: List[List[int]]) -> int: R = len(grid) C = len(grid[0]) directions = { (-1, 1): (1, 1), (1, -1): (-1, -1), (1, 1): (1, -1), (-1, -1): (-1, 1), } @cache def dp(r, c, turned, dir): res = 0 cur = grid[r][c] nxt = 2 if cur == 2: nxt = 0 nr = dir[0] + r nc = dir[1] + c if 0 <= nr < R and 0 <= nc < C: if nxt == grid[nr][nc]: res = dp(nr, nc, turned, dir) if not turned: dirs = directions[dir] nr = dirs[0] + r nc = dirs[1] + c if 0 <= nr < R and 0 <= nc < C: if nxt == grid[nr][nc]: res = max(dp(nr, nc, True, dirs), res) return res + 1 res = 0 for r in range(R): for c in range(C): if grid[r][c] == 1: for k in directions.keys(): res = max(res, dp(r, c, False, k)) return res ```
0
0
['Dynamic Programming', 'Memoization', 'Python3']
0
length-of-longest-v-shaped-diagonal-segment
DP (n x m x 4 states) | No Memorization | 111ms | Beats 100%
dp-no-memorization-111ms-beats-100-by-xp-hreh
IntuitionDP: Let f(x,y,d) denote the largest length after the turn, where x,y are the coordinates, d is the direction, and x∈[0..n), y∈[0..m), d∈[0..3].Approach
xpycc
NORMAL
2025-02-17T20:23:14.891385+00:00
2025-02-17T21:41:58.940956+00:00
20
false
# Intuition DP: Let $$f(x, y, d)$$ denote the largest length after the turn, where $$x, y$$ are the coordinates, $$d$$ is the direction, and $$x \in [0..n)$$, $$y \in [0..m)$$, $$d \in [0..3]$$. # Approach We solve it by 2 steps: 1. We first calculate $$g(x,y,d)$$ which is the largest lenth before the turn. This can be done by expanding all cells of `1` to 4 diagonal directions following sequence of `2, 0, 2, 0, ...`. It can be proved that each state $$g(x,y,d)$$ will be visited at most once, so the time for this part is $$O(n \times m \times 4)$$. Note: Actually $$f(x,y,d) = g(x,y,(d+1)\mod4), \text{if} \space grid(x, y) \neq 1 $$, so no need to store $$g(x,y,d)$$ for extra space. 1. We then calculate $$f(x,y,d)$$, with the transition of ` f[x+dx[d]][y+dy[d]][d] = max(f[x+dx[d]][y+dy[d]][d], f[x][y][d] + 1);`. Now, how do we ensure the correct order? The picture below shows the order for the direction `d` to the top-right, where we start from bottom-left, and advance one step following the blue line in each round of a red line: ![Screenshot_20250217_115129.png](https://assets.leetcode.com/users/images/24c38dd4-9538-4af5-9ee6-63f5f54cf931_1739821922.0741668.png) So, we got the observation that it's always from one diagonal vertex to the opposite diagonal vertex, row by row in the orthogonal direction. And it applies for the other 3 directions as well. We got pseudocode below: ``` cpp for (int d = 0; d < 4; ++d) { int [ox, oy] = get_start_xy(d); int [ex, ey] = get_ending_xy(d); for ( ; ox != ex; ox += dx[d]) { int d2 = get_row_iteration_dir(d, oy); /* Loop diagonal row. */ } for ( ; oy != ey; oy += dy[d]) { int d2 = get_row_iteration_dir(d, ox); /* Loop diagonal row. */ } } ``` Going from one diagonal vertex to the opposite diagonal vertex, it does not matter whether to deal with `ox` or `oy` first, so same order works for all directions. And you will find the code of `/* Loop diagonal row. */` is actually identical for both inner for loops. Note: I use a macro for `/* Loop diagonal row. */`, because LC does not do many optimizations for lambdas. In real coding, a lambda expression should be preferred. Still, a lambda gives results of ~150ms, which also beats 100% :) # Complexity - Time complexity: $$O(n \times m \times 4)$$ - Space complexity: $$O(n \times m \times 4)$$ # Code ```cpp [] class Solution { static constexpr int dx[] = {-1, 1, 1,-1}; static constexpr int dy[] = { 1, 1,-1,-1}; public: int lenOfVDiagonal(vector<vector<int>>& grid) { const int n = grid.size(), m = grid[0].size(); vector<vector<array<int, 4>>> f(n, vector<array<int, 4>>(m, {0})); int ans = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) if (grid[i][j] == 1) { const int U = max({i, n - 1 - i, j, m - 1 - j}); ans = max(ans, 1); for (int d = 0; d < 4; ++d) { const int nd = (d + 1) % 4; for (int k = 1; k <= U; ++k) { const int nx = i + k * dx[d], ny = j + k * dy[d]; if (nx < 0 || nx >= n || ny < 0 || ny >= m || grid[nx][ny] != k % 2 * 2) break; f[nx][ny][nd] = k + 1; ans = max(ans, k + 1); } } } auto get_xy = [n, m](int d) { return make_pair(dx[d] == 1 ? 0 : n - 1, dy[d] == 1 ? 0 : m - 1); }; #define LOOP_DIAG \ for (int x = ox, y = oy; \ 0 <= x && x < n && 0 <= y && y < m; \ x += dx[d2], y += dy[d2]) { \ const int nx = x + dx[d], ny = y + dy[d]; \ if (nx < 0 || nx >= n || ny < 0 || ny >= m) \ continue; \ if (f[x][y][d] == 0) continue;\ if (f[x][y][d] % 2 * 2 != grid[nx][ny]) \ continue; \ f[nx][ny][d] = max(f[nx][ny][d], f[x][y][d] + 1); \ ans = max(ans, f[nx][ny][d]); \ } for (int d = 0; d < 4; ++d) { auto [ox, oy] = get_xy(d); auto [ex, ey] = get_xy(d ^ 2); for ( ; ox != ex; ox += dx[d]) { int d2 = (d + 1) % 4; if (oy == 0 ^ dy[d2] == 1) d2 ^= 2; LOOP_DIAG; } for ( ; oy != ey; oy += dy[d]) { int d2 = (d + 1) % 4; if (ox == 0 ^ dx[d2] == 1) d2 ^= 2; LOOP_DIAG; } } return ans; } }; ```
0
0
['Dynamic Programming', 'C++']
0
length-of-longest-v-shaped-diagonal-segment
Simple JAVA DFS solution
simple-java-dfs-solution-by-vinay_p2-2lu1
Code
vinay_p2
NORMAL
2025-02-17T15:44:56.187766+00:00
2025-02-17T15:44:56.187766+00:00
64
false
# Code ```java [] class Solution { int n, m; int[] dx = {-1, -1, 1, 1}; int[] dy = {-1, 1, 1, -1}; public int lenOfVDiagonal(int[][] grid) { n = grid.length; m = grid[0].length; List<int[]> list = new ArrayList<>(); for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ if (grid[i][j]==1){ list.add(new int[]{i, j}); } } } int size = list.size(); int max = 0; for (int i=0; i<size; i++){ max = Math.max(max, getMaxV(list.get(i), grid)); } return max; } public int getMaxV(int[] points, int[][] grid){ int max = 1; for (int i=0; i<4; i++){ int x = points[0]+dx[i]; int y = points[1]+dy[i]; if (x<0 || y<0 || x>=n || y>=m ) continue; max = Math.max(max, dfs(x, y, 2, i, grid, false)); } return max; } public int dfs(int x, int y,int next, int dir, int[][] grid, boolean turned){ if (x<0 || y< 0 || x>=n || y>=m || grid[x][y]!=next) return 1; int sameDirection = 1 + dfs(x+dx[dir], y+dy[dir],2-next, dir, grid, turned); int changeDirection = 0; if (!turned){ dir = (dir+1)%4; changeDirection = 1 + dfs(x+dx[dir], y+dy[dir],2-next, dir, grid, true); } return Math.max(sameDirection, changeDirection); } } ```
0
0
['Depth-First Search', 'Java']
0
length-of-longest-v-shaped-diagonal-segment
Easiest Solution || Java || Beats 100%
easiest-solution-java-beats-100-by-adiii-ywmo
IntuitionThis code finds the longest valid diagonal path between cells of a 2D grid. The grid contains two types of cells, marked by 1 and 2. A valid diagonal p
adiiityaambekar
NORMAL
2025-02-17T10:33:39.084539+00:00
2025-02-17T10:33:39.084539+00:00
66
false
# Intuition This code finds the longest valid diagonal path between cells of a 2D grid. The grid contains two types of cells, marked by 1 and 2. A valid diagonal path is one where you can move between cells marked with 1 and 2 by stepping through diagonals. The key to solving this problem lies in the use of depth-first search (DFS) to explore all possible diagonal paths while ensuring valid moves and respecting turn restrictions. # Approach The code uses DFS to find the longest diagonal path between cells in a grid. It checks diagonals between 1 and 2, allowing one direction change. The rowHelper and colHelper arrays define the 4 diagonal directions, and relative helps switch directions after a turn. The isValid function ensures the cell is within grid bounds. The dfs function explores diagonals recursively, moving to cells that contain the opposite value (1 to 2 or 2 to 1) and allows one direction change. It returns the longest diagonal path found. In the main function, it iterates over the grid, starting DFS from any 1 with adjacent 2 cells. It updates the maximum path length and returns the result after exploring all potential paths. # Complexity - Time complexity:$$O(m*n)$$ - Space complexity: $$O(m*n)$$ # Code ```java [] class Solution { public static int[] rowHelper = {1, -1, -1, 1}; public static int[] colHelper = {1, -1, 1, -1}; public static int[] relative = {3, 2, 0, 1}; public boolean isValid(int i , int j, int n, int m) { return i >= 0 && j >= 0 && i < n && j < m; } public int dfs(int i, int j, int[][] grid, boolean turned, int turnIndex, int n, int m) { int maxLength = 1; int rd = i + rowHelper[turnIndex], cd = j + colHelper[turnIndex]; if(isValid(rd, cd, n, m)) { if(grid[rd][cd] == (2-grid[i][j])) { maxLength = Math.max(maxLength, 1 + dfs(rd, cd, grid, turned, turnIndex, n, m)); } } if(!turned) { int dir = relative[turnIndex]; int rd2 = i + rowHelper[dir], cd2 = j + colHelper[dir]; if(isValid(rd2, cd2, n, m) && grid[rd2][cd2] == (2-grid[i][j])) { maxLength = Math.max(maxLength, 1+dfs(rd2, cd2, grid, true, dir, n, m)); } } return maxLength; } public int lenOfVDiagonal(int[][] grid) { int n = grid.length, m = grid[0].length; int ans = 0; for(int i = 0 ; i < n; i++) { for(int j = 0; j < m; j++) { if(grid[i][j] == 1) { ans = Math.max(ans, 1); for(int k = 0; k < 4; k++) { int rd = i + rowHelper[k], cd = j + colHelper[k]; if(isValid(rd, cd, n, m)) { if(grid[rd][cd] == 2) { System.out.println(rd + " " + cd + " " + k); ans = Math.max(ans, 1 + dfs(rd ,cd, grid, false, k, n, m)); } } } } } } return ans; } } ```
0
0
['Java']
0
length-of-longest-v-shaped-diagonal-segment
2D matrix DP
2d-matrix-dp-by-rsysz-6y0z
Intuitionsimilar problem: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/description/Approachfind all 8 state for each grid[i][j] then we can
rsysz
NORMAL
2025-02-17T08:11:47.710395+00:00
2025-02-17T08:11:47.710395+00:00
12
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> similar problem: https://leetcode.com/problems/longest-increasing-path-in-a-matrix/description/ # Approach <!-- Describe your approach to solving the problem. --> find all 8 state for each grid[i][j] then we can leverage dp arr to reduce time complexity # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $O(n * m * 4 * 2)$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $O(n * m * 4 * 2)$ # Code ```cpp [] /* T: O(n * m * 2 * 4) 1->2 0->2 2->0 */ class Solution { public: vector<pair<int, int>> dirs{{-1, -1}, {-1, 1}, {1, 1}, {1, -1}}; int lenOfVDiagonal(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(); vector<vector<vector<vector<int>>>> dp(n, vector<vector<vector<int>>>(m, vector<vector<int>>(4, vector<int>(2, -1)))); // dp[i][j][d][t] is len of longest diagonal segment start from (i, j) to direction[d] with t{0:no turn, 1:turn}; auto check = [&](int i, int j, int r, int c) -> bool { if (r < 0 || r >= n || c < 0 || c >= m) return false; if ((grid[i][j] == 1 && grid[r][c] == 2) || (grid[i][j] == 0 && grid[r][c] == 2) || (grid[i][j] == 2 && grid[r][c] == 0)) return true; return false; }; function<int(int, int, int, int)> dfs = [&](int i, int j, int d, int t) { if (dp[i][j][d][t] != -1) return dp[i][j][d][t]; int maxlen = 0; if (check(i, j, i + dirs[d].first, j + dirs[d].second)) maxlen = dfs(i + dirs[d].first, j + dirs[d].second, d, t); int newd = (d + 1) % 4; if (t != 0 && check(i, j, i + dirs[newd].first, j + dirs[newd].second)) maxlen = max(maxlen, dfs(i + dirs[newd].first, j + dirs[newd].second, newd, t - 1)); return dp[i][j][d][t] = maxlen + 1; }; int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) { res = max({res, dfs(i, j, 0, 1), dfs(i, j, 1, 1), dfs(i, j, 2, 1), dfs(i, j, 3, 1)}); } } } return res; } }; ```
0
0
['C++']
0