question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
find-indices-with-index-and-value-difference-ii
Contest Video Solution | Explanation with Drawings | In Depth | C++
contest-video-solution-explanation-with-gzwww
Intuition, approach, and complexity discussed in detail in video solution.\nhttps://youtu.be/TgPJDoO-z3M\n\n# Code\n\nclass Solution {\npublic:\n vector<
Fly_ing__Rhi_no
NORMAL
2023-10-15T07:52:14.045162+00:00
2023-10-15T07:52:14.045181+00:00
251
false
# Intuition, approach, and complexity discussed in detail in video solution.\nhttps://youtu.be/TgPJDoO-z3M\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n \n int minEleIndx = 0, maxEleIndx = 0, n = nums.size();\n \n for (int indx = indexDifference; indx < n; indx++) {\n if (nums[indx - indexDifference] < nums[minEleIndx]) minEleIndx = indx - indexDifference;\n \n if (nums[indx] - nums[minEleIndx] >= valueDifference) return {indx, minEleIndx};\n if (nums[indx - indexDifference] > nums[maxEleIndx]) maxEleIndx = indx - indexDifference;\n \n if (nums[maxEleIndx] - nums[indx] >= valueDifference) return {indx, maxEleIndx};\n }\n \n return { -1, -1};\n }\n};\n```
1
0
['C++']
1
find-indices-with-index-and-value-difference-ii
100% Beats East Soution
100-beats-east-soution-by-sunkarasairam9-qoq3
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
sunkarasairam99
NORMAL
2023-10-15T07:05:40.596089+00:00
2023-10-15T07:05:40.596111+00:00
148
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int minval = (int)1e9,minind = -1;\n int maxval = -(int)1e9,maxind = -1;\n int n = nums.length;\n if(n == 1){\n if(indexDifference == 0 && valueDifference == 0) return new int[]{0,0};\n return new int[]{-1,-1};\n\n }\n for(int i = indexDifference;i<n;i++){\n if(minval>nums[i-indexDifference]){\n // System.out.println(minval+", "+nums[i-indexDifference]+" Minval");\n minval = nums[i-indexDifference];\n minind = i-indexDifference;\n }\n if(maxval<nums[i-indexDifference]){\n // System.out.println(maxval+", "+nums[i-indexDifference]+" Max val");\n maxval = nums[i-indexDifference];\n maxind = i-indexDifference;\n \n }\n \n if((int)Math.abs(minval-nums[i])>=valueDifference){\n // System.out.println(minval+","+nums[i]+","+valueDifference+" min Val = "+i);\n return new int[]{minind,i};\n }\n if((int)Math.abs(maxval-nums[i])>=valueDifference){\n // System.out.println(maxind+","+nums[i]+","+valueDifference+" max Val = "+i);\n\n return new int[]{maxind,i};\n }\n }\n return new int[]{-1,-1};\n \n }\n}\n```
1
0
['Java']
0
find-indices-with-index-and-value-difference-ii
Minimum and Maximum with delay | O(N)
minimum-and-maximum-with-delay-on-by-jay-b8qc
Intution -\n\n1. Condition 1 : IndexDifference \n- say two indices i , j . Where j <= i .oj\n- Index j can be considered if atleast d distance apart from i .\n-
Jay_1410
NORMAL
2023-10-15T05:56:44.128896+00:00
2023-10-15T05:58:43.404767+00:00
21
false
# Intution -\n\n1. ***Condition 1 : IndexDifference*** \n- *say two indices i , j . Where j <= i .oj*\n- *Index j can be considered if atleast d distance apart from i .*\n- *i.e j = [0 , i - indexDifference] .*\n\n2. ***Condition 2 : Value Difference***\n- *Imagine we are currently at index = i .*\n- *So we have j from [0 , i - indexDifference] .*\n- *Then we can always say that if there exits a valid ( i , j ) Pair then\neither maximumInRange(0,i-indexDifference) or minimumInRange(0,i-indexDifference) will be valid j for i.*\n\n3. ***Proof for Condition 2*** - \n- *Assume there exists a j meeting both the conditions*\n- *represent all elements from 0 to j on a number line*\n- *Number Line => -Inf . . . Mini . . . . nums[j\'s] . . . . Maxi . . . +Inf*\n- *If nums[i] >= Maxi , then nums[i]-Mini has Maximum Value Difference*\n- *If nums[i] <= Mini , then Maxi-nums[i] has Maximum Value Difference*\n- *If nums[i] >= Mini and nums[i] <= Maxi , Then either Mini or Maxi will be a valid Answer*\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int d, int v) {\n int n = nums.size();\n int maxiIdx = -1 , miniIdx = -1;\n for(int i=0;i<n;i++){\n /* Condition 1 : indexDifference distance apart from i */\n if(i-d >= 0){\n /* Finding maxi and mini in Range [0,i-indexDifference] */\n if(maxiIdx == -1 || nums[maxiIdx] < nums[i-d]) maxiIdx = i - d; \n if(miniIdx == -1 || nums[miniIdx] > nums[i-d]) miniIdx = i - d;\n } \n /* Condition 2 : Checking for valid j corresponding to i */\n if(i-d >= 0 && abs(nums[i]-nums[maxiIdx]) >= v) return {i,maxiIdx};\n if(i-d >= 0 && abs(nums[i]-nums[miniIdx]) >= v) return {i,miniIdx};\n }\n return {-1,-1}; /* Not found Case*/\n }\n};\n```
1
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Python3 | SortedList
python3-sortedlist-by-tkr_6-7oq3
\n\n# Code\n\nclass Solution:\n def findIndices(self, nums: List[int], ind: int, val: int) -> List[int]:\n \n \n \n from sortedco
TKR_6
NORMAL
2023-10-15T05:46:22.816135+00:00
2023-10-15T05:47:08.247295+00:00
126
false
\n\n# Code\n```\nclass Solution:\n def findIndices(self, nums: List[int], ind: int, val: int) -> List[int]:\n \n \n \n from sortedcontainers import SortedList\n n=len(nums)\n sl=SortedList()\n \n for i in range(ind,n):\n sl.add([nums[i-ind],i-ind])\n \n a,i1=sl[0]\n b,i2=sl[-1]\n \n if abs(a-nums[i])>=val:\n return [i,i1]\n if abs(b-nums[i])>=val:\n return [i,i2]\n \n \n return [-1,-1]\n \n \n \n \n \n```
1
0
['Binary Search', 'Python', 'Python3']
0
find-indices-with-index-and-value-difference-ii
Keep Track of Min and Max before Index i | One Pass Solution and Priority Queue Solution
keep-track-of-min-and-max-before-index-i-7to0
\n// Time : O(n * log(n))\n// Space : O(n)\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference
kamalkish0r
NORMAL
2023-10-15T04:56:47.965445+00:00
2023-10-15T04:58:51.885694+00:00
48
false
```\n// Time : O(n * log(n))\n// Space : O(n)\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n priority_queue<pair<int, int>> max_before;\n priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_before;\n for (int i = 0; i < nums.size(); i++) {\n if (i >= indexDifference) {\n int j = i - indexDifference;\n max_before.push({nums[j], j});\n min_before.push({nums[j], j});\n }\n \n if (!min_before.empty() and abs(nums[i] - min_before.top().first) >= valueDifference) {\n return {i, min_before.top().second};\n }\n if (!max_before.empty() and abs(nums[i] - max_before.top().first) >= valueDifference) {\n return {i, max_before.top().second};\n }\n }\n return {-1, -1};\n }\n};\n```\n\nAt any index ```i``` we want to find out indices ```j``` such that ```abs(i - j) >= indexDifference``` and ```nums[j]``` is either maximum or minimum in range ```[0, j]```\n\n```\n// Time : O(n)\n// Space : O(1)\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int min_index = -1, max_index = -1;\n for (int i = 0; i < nums.size(); i++) {\n if (i >= indexDifference) {\n int j = i - indexDifference;\n if (min_index == -1 or nums[min_index] > nums[j]) \n min_index = j;\n if (max_index == -1 or nums[max_index] < nums[j]) \n max_index = j;\n }\n \n if (min_index != -1 and abs(nums[i] - nums[min_index]) >= valueDifference) {\n return {min_index, i};\n } \n if (max_index != -1 and abs(nums[i] - nums[max_index]) >= valueDifference) {\n return {max_index, i};\n }\n }\n return {-1, -1};\n }\n};\n```
1
0
['C', 'Heap (Priority Queue)']
0
find-indices-with-index-and-value-difference-ii
Java | O(N) solution
java-on-solution-by-goodnight-hhdn
Intuition\n Describe your first thoughts on how to solve this problem. \nCreate a min and a max array to maintian the min value and max value so far. Then creat
goodnight
NORMAL
2023-10-15T04:42:26.118501+00:00
2023-10-15T04:42:26.118520+00:00
55
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate a `min` and a `max` array to maintian the min value and max value so far. Then create a Map to maintain each number to its first seen index in `nums`\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(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int n = nums.length;\n int[] min = new int[n];\n Arrays.fill(min, Integer.MAX_VALUE);\n min[0] = nums[0];\n int[] max = new int[n];\n Arrays.fill(max, Integer.MIN_VALUE);\n max[0] = nums[0];\n \n for (int i = 1; i < n; i++) {\n min[i] = Math.min(min[i - 1], nums[i]);\n max[i] = Math.max(max[i - 1], nums[i]); \n }\n \n Map<Integer, Integer> numToIndex = new HashMap<>();\n numToIndex.put(nums[0], 0);\n for (int i = 0; i < n; i++) {\n if (i < indexDifference) {\n if (!numToIndex.containsKey(nums[i])) {\n numToIndex.put(nums[i], i);\n }\n\n continue;\n }\n\n if (Math.abs(nums[i] - min[i - indexDifference]) >= valueDifference) {\n return new int[]{numToIndex.get(min[i - indexDifference]), i};\n }\n \n if (Math.abs(nums[i] - max[i - indexDifference]) >= valueDifference) {\n return new int[]{numToIndex.get(max[i - indexDifference]), i};\n }\n \n if (!numToIndex.containsKey(nums[i])) {\n numToIndex.put(nums[i], i);\n }\n \n }\n \n return new int[]{-1, -1};\n }\n}\n```
1
0
['Java']
0
find-indices-with-index-and-value-difference-ii
[JavaScript] 2905. Find Indices With Index and Value Difference II
javascript-2905-find-indices-with-index-tduv5
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
pgmreddy
NORMAL
2023-10-15T04:12:23.300496+00:00
2023-10-15T04:15:55.893660+00:00
45
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n---\n\n```\nvar findIndices = function (nums, indexDifference, valueDifference) {\n let n = nums.length;\n let sufmax = new Array(n);\n let sufmin = new Array(n);\n for (let i = 0, max1 = -Infinity, max2 = -Infinity, min2 = Infinity; i < n; i++) {\n sufmax[n - 1 - i] = max2 = Math.max(max2, nums[n - 1 - i]);\n sufmin[n - 1 - i] = min2 = Math.min(min2, nums[n - 1 - i]);\n }\n\n for (let i = 0; i < nums.length; i++) {\n if (Math.abs(nums[i] - sufmax[i + indexDifference]) >= valueDifference)\n for (let j = i + indexDifference; j < nums.length; j++)\n if (Math.abs(nums[i] - nums[j]) >= valueDifference) {\n return [i, j];\n }\n if (Math.abs(nums[i] - sufmin[i + indexDifference]) >= valueDifference)\n for (let j = i + indexDifference; j < nums.length; j++)\n if (Math.abs(nums[i] - nums[j]) >= valueDifference) {\n return [i, j];\n }\n }\n return [-1, -1];\n};\n```\n\n---\n\n**Weekly Contest 367**\n- Q1 - https://leetcode.com/problems/find-indices-with-index-and-value-difference-i/solutions/4169852/javascript-2903-find-indices-with-index-and-value-difference-i/\n- Q2 - https://leetcode.com/problems/shortest-and-lexicographically-smallest-beautiful-string/solutions/4169863/javascript-2904-shortest-and-lexicographically-smallest-beautiful-string/\n- Q3 - See above\n\n---\n\n
1
0
['JavaScript']
0
find-indices-with-index-and-value-difference-ii
Using TreeMap | Java | O(nlogn)
using-treemap-java-onlogn-by-vigbav36-m0mf
Intuition\nThis is kinda like two-sum problem so my intuition was to approach with a map. Since we had inequalities we can use a TreeMap.\n\nabs(nums [ i ] - nu
vigbav36
NORMAL
2023-10-15T04:11:25.896945+00:00
2023-10-15T04:15:25.011581+00:00
118
false
# Intuition\nThis is kinda like two-sum problem so my intuition was to approach with a map. Since we had inequalities we can use a TreeMap.\n\n**abs(nums [ i ] - nums [ j ]) >= valueDifference**\n\nremoving the abs we get\n\n**nums [ i ] - nums [ j ] >= valueDifference** ---> 1\n**nums [ i ] - nums [ j ] <= - valueDifference** ---> 2\n\nHence now ***given nums [ j ] we can find nums [ i ]*** using above equations 1 and 2\n\n# Approach\n\nMake use of **TreeMap** and its ceilingKey and floorKey functions to find the closest number satisfying the conditions.\n\n# Complexity\n- Time complexity: **O(nlog(n))**\n\n- Space complexity: **O(n)**\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();\n map.put(Integer.MAX_VALUE,-1);\n map.put(Integer.MIN_VALUE,-1);\n int p1 = 0;\n int p2 = indexDifference;\n \n while(p2<nums.length){\n map.put(nums[p1],p1);\n \n int d1 = valueDifference + nums[p2];\n int d2 = nums[p2] - valueDifference;\n \n if(map.ceilingKey(d1)!=Integer.MAX_VALUE)\n return new int[]{map.get(map.ceilingKey(d1)),p2};\n \n if(map.floorKey(d2)!=Integer.MIN_VALUE)\n return new int[]{map.get(map.floorKey(d2)),p2};\n \n p1++;\n p2++;\n }\n return new int[]{-1,-1};\n }\n}\n```
1
0
['Ordered Map', 'Java']
0
find-indices-with-index-and-value-difference-ii
Minimum and Maximum.
minimum-and-maximum-by-hanumanjikijai-45qh
Intuition\n Describe your first thoughts on how to solve this problem. \n- Intuition is simple, you need to min val and max val till every index.\n- Then If i-d
hanumanjikijai
NORMAL
2023-10-15T04:08:59.737134+00:00
2023-10-15T04:11:02.276714+00:00
20
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Intuition is simple, you need to min val and max val till every index.\n- Then If i-d>=0, you can check the abs(nums[i]-tmp[i-d]) where tmp[i-d] stores min and max till i-d.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n vector<int> findIndices(vector<int>& nums, int id, int vd) {\n int n=nums.size();\n int mini=INT_MAX,maxi=INT_MIN,minidx=-1,maxidx=-1;\n vector<pair<pair<int,int>,pair<int,int>>> tmp(n);\n for(int i=0;i<n;i++)\n {\n if(mini>nums[i]){\n minidx=i;\n mini=nums[i];\n }\n if(maxi<nums[i]){\n maxidx=i;\n maxi=nums[i];\n }\n tmp[i]={{maxi,maxidx},{mini,minidx}};\n if(i-id<0)continue;\n auto p=tmp[i-id];\n int mx=p.first.first,mxidx=p.first.second,mi=p.second.first,miidx=p.second.second;\n if(abs(mx-nums[i])>=vd)return {mxidx,i};\n if(abs(mi-nums[i])>=vd)return {miidx,i};\n }\n return {-1,-1};\n }\n};\n```
1
0
['C++']
0
find-indices-with-index-and-value-difference-ii
✅Simple Pre-Computation!!!⚡⚡⚡
simple-pre-computation-by-yashpadiyar4-qykh
\n\n# Code\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int id, int vd) {\n int n=nums.size();\n vector<int>minil(
yashpadiyar4
NORMAL
2023-10-15T04:06:29.160767+00:00
2023-10-15T04:06:29.160785+00:00
543
false
\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int id, int vd) {\n int n=nums.size();\n vector<int>minil(n);\n vector<int>maxil(n);\n vector<int>minir(n);\n vector<int>maxir(n);\n minil[0]=0;\n maxil[0]=0;\n minir[n-1]=n-1;\n maxir[n-1]=n-1;\n int minimuml=nums[0];\n int minimumr=nums[n-1];\n int maximuml=nums[0];\n int maximumr=nums[n-1];\n vector<int>ans;\n for(int i=1;i<n;i++){\n if(minimuml>nums[i]){\n minil[i]=i;\n minimuml=nums[i];\n }\n else{\n minil[i]=minil[i-1]; \n }\n if(maximuml<nums[i]){\n maximuml=nums[i];\n maximuml=i;\n }\n else{\n maxil[i]=maxil[i-1];\n }\n }\n for(int i=n-2;i>=0;i--){\n if(maximumr<nums[i]){\n maximumr=nums[i];\n maxir[i]=i;\n }\n else{\n maxir[i]=maxir[i+1];\n }\n if(minimumr>nums[i]){\n minimumr=nums[i];\n minir[i]=i;\n }\n else{\n minir[i]=minir[i+1];\n }\n }\n for(int i=0;i<n;i++){\n if(i-id>=0 && abs(nums[i]-nums[minil[i-id]])>=vd ){\n ans.push_back(i);\n ans.push_back(minil[i-id]);\n return ans;\n }\n if( i+id<n && abs(nums[i]-nums[minir[i+id]])>=vd){\n ans.push_back(i);\n ans.push_back(minir[i+id]);\n return ans;\n }\n if(i-id>=0 && abs(nums[i]-nums[maxil[i-id]])>=vd){\n ans.push_back(i);\n ans.push_back(maxil[i-id]);\n return ans;\n }\n if(i+id<n && abs(nums[i]-nums[maxir[i+id]])>=vd){\n ans.push_back(i);\n ans.push_back(maxir[i+id]);\n return ans;\n }\n }\n return {-1,-1};\n }\n};\n```
1
0
['C++']
1
find-indices-with-index-and-value-difference-ii
PreMax and SufMax
premax-and-sufmax-by-bhavya45-rjc3
ApproachPrefix and Suffix MaxComplexity Time complexity: O(n) Space complexity: O(n)Code
Bhavya45
NORMAL
2025-03-31T09:41:52.018253+00:00
2025-03-31T09:41:52.018253+00:00
3
false
# Approach <!-- Describe your approach to solving the problem. --> Prefix and Suffix Max # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n) # Code ```cpp [] class Solution { public: vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) { int n = nums.size(); vector<int>preMax(n,-1); vector<int>preIndices(n,-1); int maxi = nums[0]; int maxIndex = 0; for(int i = indexDifference;i < n;i++) { if(nums[i - indexDifference] >= maxi) { maxi = nums[i - indexDifference]; maxIndex = i - indexDifference; } preMax[i] = maxi; preIndices[i] = maxIndex; } // for(auto it:preIndices) cout << it << " "; // cout << endl; // for(auto it:preMax) cout << it << " "; // cout << endl; vector<int>sufMax(n,-1); vector<int>sufIndices(n,-1); maxi = nums[n - 1]; maxIndex = n - 1; for(int i = n - 1 - indexDifference; i >= 0;i--) { if(nums[i + indexDifference] >= maxi) { maxi = nums[i + indexDifference]; maxIndex = i + indexDifference; } sufMax[i] = maxi; sufIndices[i] = maxIndex; } // for(auto it:sufIndices) cout << it << " "; // cout << endl; // for(auto it:sufMax) cout << it << " "; // cout << endl; for(int i = 0;i < n;i++) { if(preIndices[i] != -1 && (abs(nums[preIndices[i]] - nums[i]) >= valueDifference)) { return {i,preIndices[i]}; } if(sufIndices[i] != -1 && (abs(nums[sufIndices[i]] - nums[i]) >= valueDifference)) { return {i,sufIndices[i]}; } } return {-1,-1}; } }; ```
0
0
['Two Pointers', 'C++']
0
find-indices-with-index-and-value-difference-ii
Prefix Sum, better then 100% of all solutions
prefix-sum-better-then-100-of-all-soluti-hloq
IntuitionApproachComplexity Time complexity: Space complexity: Code
coderot
NORMAL
2025-03-26T11:26:38.048731+00:00
2025-03-26T11:26:38.048731+00:00
2
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- 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 int[] findIndices(int[] nums, int indexDifference, int valueDifference) { int min = Integer.MAX_VALUE; int min_index = -1; int max = 0; int max_index = 0; int[] prefixMax = new int[nums.length]; int[] prefixMin = new int[nums.length]; for (int k = 0; k < nums.length; k++) { if (nums[k] < min) { prefixMin[k] = k; min = nums[k]; min_index = k; } else { prefixMin[k] = min_index; } if (nums[k] > max) { prefixMax[k] = k; max = nums[k]; max_index = k; } else { prefixMax[k] = max_index; } } for (int i = nums.length-1; i > indexDifference-1; i--) { if (i-indexDifference < 0) { break; } if (Math.abs(nums[i] - nums[prefixMin[i-indexDifference]]) >= valueDifference) { return new int[]{i, prefixMin[i-indexDifference]}; } if (Math.abs(nums[i] - nums[prefixMax[i-indexDifference]]) >= valueDifference) { return new int[]{i, prefixMax[i-indexDifference]}; } } return new int[]{-1,-1}; } } ```
0
0
['Prefix Sum', 'Java']
0
find-indices-with-index-and-value-difference-ii
Java | O(n) Time | O(n) Space
java-on-time-on-space-by-shashankmore47-6mlk
IntuitionFocus on to maximize the value difference as index difference is straight forward. We well try to find j index for each i which satisfy the given condi
shashankmore47
NORMAL
2025-02-19T15:32:10.347313+00:00
2025-02-19T15:32:10.347313+00:00
6
false
# Intuition Focus on to maximize the value difference as index difference is straight forward. We well try to find j index for each i which satisfy the given conditions. 1) j >= indexDifference+i 2) Select any value after indexDifference+i index which can make sufficient valueDifference. So, it can be done by finding elements with max and min value after indexDifference+i index. # Approach Create 2 array min and max which stores the index of min and max value from i index. Then use this array. # Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```java [] class Solution { public int[] findIndices(int[] nums, int indexDifference, int valueDifference) { int n = nums.length; int[] min = new int[n]; int[] max = new int[n]; min[n-1] = n-1; for (int i = n-2; i >= 0; --i) { if (nums[i] < nums[min[i+1]]) { min[i] = i; } else { min[i] = min[i+1]; } } max[n-1] = n-1; for (int i = n-2; i >= 0; --i) { if (nums[i] > nums[max[i+1]]) { max[i] = i; } else { max[i] = max[i+1]; } } for (int i = 0; i <= n-1-indexDifference; ++i) { if (Math.abs(nums[i]-nums[min[i+indexDifference]]) >= valueDifference) { return new int[] {i,min[i+indexDifference]}; } if (Math.abs(nums[i]-nums[max[i+indexDifference]]) >= valueDifference) { return new int[] {i,max[i+indexDifference]}; } } return new int[] {-1,-1}; } } ```
0
0
['Java']
0
find-indices-with-index-and-value-difference-ii
CPP Greedy Optimization Problem
cpp-greedy-optimization-problem-by-knigh-xxgl
IntuitionAnother optimization problem to heat your cognitive brain.Make sure you're ready to be disappointed if you had never solved these types of optimization
knight7king
NORMAL
2025-02-09T13:14:05.366160+00:00
2025-02-14T18:32:51.951526+00:00
8
false
# Intuition Another optimization problem to heat your cognitive brain. Make sure you're ready to be disappointed if you had never solved these types of optimization problems. Basically there is no intuition for these types of questions you just have to have a great observation skills. I mean, yeah, that's it. # Approach Its greedy at first I thought maybe just by maintaining the maximum will give me the right answer since my playground range(0, i - iDiff) was already within the given constraints but **no** I failed and then I figured out we need to pull minimum as well. Make sure you observe it. Draw it on a piece of paper if you'd like that - honestly no one likes that. But anyways, hope you got it right. > You can check out my thinking process down in the code. # Complexity - Time complexity: $$O(n)$$ traversal. - Space complexity: $$O(1)$$ nothing to store. # Code ```cpp [] class Solution { public: vector<int> findIndices(vector<int>& nums, int iDiff, int vDiff) { int Mx = INT_MIN, Mn = INT_MAX, Mxi = -1, Mni = -1; int n = (int)nums.size(); for (int i = iDiff; i < n; i++) { if (Mx < nums[i - iDiff]) {Mx = nums[i - iDiff]; Mxi = i-iDiff;} if (Mn > nums[i - iDiff]) {Mn = nums[i - iDiff]; Mni = i-iDiff;} if (abs(nums[i] - Mx) >= vDiff) return {i, Mxi}; if (abs(nums[i] - Mn) >= vDiff) return {i, Mni}; } return {-1, -1}; } }; /* Optimization problem. Since we have a distance constraint on i and j. We can do something like this nums[i-iDff] and store values in it, maybe using a set so that we can set our playground right. Once we have the playground ready. According to the question maybe we just need to find the maximum value as we make our set and since we are going to be just fine with the distance constraints we just need to take care of value difference constraint and if the abs(nums[i] - max in the playground so far) >= vDiff we have an answer. So, maybe this: for (int i = iDiff; i < n; i++) { s.insert(nums[i-iDiff]); ?? we don't need it i think. Mx = max(Mx, nums[i-iDiff]); ?? find the index logic as well. if (abs(Mx - nums[i]) >= vDiff) return [index(Mx), i]; ?? maybe we don't need a set here anymore. } Well, that didn't work that well. Maybe another approach. Maybe maintaining separate Minimum and Maximum would work. Let's see. Maybe: for (int i = iDiff, i < n; i++) { Mx = max(Mx, nums[i-iDiff]); Mn = min(Mn, nums[i-iDiff]); if (abs(nums[i] - Mx) >= vDiff) return [i, index(Mx)] if (abs(nums[i] - Mn) >= vDiff) return [i, index(Mn)] } return {-1, -1}; Just one thing we need to maintain the index of Mx and Mn as well. */ ```
0
0
['Brainteaser', 'C++']
0
find-indices-with-index-and-value-difference-ii
Easy Python Solution
easy-python-solution-by-vidhyarthisunav-9hvr
Code
vidhyarthisunav
NORMAL
2025-02-08T13:55:19.778923+00:00
2025-02-08T13:55:19.778923+00:00
5
false
# Code ```python3 [] class Solution: def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]: n = len(nums) idx_max, idx_min = 0, 0 for i in range(indexDifference, n): if nums[i - indexDifference] < nums[idx_min]: idx_min = i - indexDifference if nums[i - indexDifference] > nums[idx_max]: idx_max = i - indexDifference if abs(nums[i] - nums[idx_max]) >= valueDifference: return [i, idx_max] if abs(nums[i] - nums[idx_min]) >= valueDifference: return [i, idx_min] return [-1, -1] ```
0
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
4 pass precomputed sliding window
4-pass-precomputed-sliding-window-by-ton-wp2z
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(n) Code
tonitannoury01
NORMAL
2024-12-30T16:02:23.517031+00:00
2024-12-30T16:02:23.517031+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```javascript [] /** * @param {number[]} nums * @param {number} indexDifference * @param {number} valueDifference * @return {number[]} */ var findIndices = function (nums, indexDifference, valueDifference) { let n = nums.length; let maxLeft = Array(n).fill(0); maxLeft[0] = 0; let maxRight = Array(n).fill(0); maxRight[n - 1] = n - 1; let minLeft = Array(n).fill(0); minLeft[0] = 0; let minRight = Array(n).fill(0); minRight[n - 1] = n - 1; for (let i = 1; i < n; i++) { if (nums[maxLeft[i - 1]] > nums[i]) { maxLeft[i] = maxLeft[i - 1]; } else { maxLeft[i] = i; } if (nums[minLeft[i - 1]] < nums[i]) { minLeft[i] = minLeft[i - 1]; } else { minLeft[i] = i; } } for (let i = n - 2; i >= 0; i--) { if (nums[maxRight[i + 1]] > nums[i]) { maxRight[i] = maxRight[i + 1]; } else { maxRight[i] = i; } if (nums[minRight[i + 1]] < nums[i]) { minRight[i] = minRight[i + 1]; } else { minRight[i] = i; } } for (let i = 1; i <= n - indexDifference; i++) { if ( Math.abs( nums[minLeft[i - 1]] - nums[maxRight[i + indexDifference - 1]] ) >= valueDifference ) { return [minLeft[i - 1], maxRight[i + indexDifference - 1]]; } if ( Math.abs( nums[maxLeft[i - 1]] - nums[minRight[i + indexDifference - 1]] ) >= valueDifference ) { return [maxLeft[i - 1], minRight[i + indexDifference - 1]]; } } return [-1, -1]; }; ```
0
0
['JavaScript']
0
find-indices-with-index-and-value-difference-ii
C++ map
c-map-by-airusian2-wsvx
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
AirusIan2
NORMAL
2024-11-25T08:12:07.928059+00:00
2024-11-25T08:12:07.928095+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```cpp []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int d = indexDifference;\n int n = nums.size();\n map<int,int> t;\n t.insert({nums[0], 0});\n int left = 0;\n for(int i = d ; i < n ; i++){\n if(i > d){\n left++;\n t.insert({nums[left], left});\n } \n auto up = t.lower_bound(nums[i] + valueDifference);\n if(up != t.end()) return {up->second, i};\n cout <<"-------" <<endl;\n auto it = t.begin();\n cout << it->first <<" "<<it->second;\n if(nums[i] - it->first >= valueDifference) return{it->second, i};\n }\n return {-1,-1};\n }\n};\n\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
non two-pointer
non-two-pointer-by-diorsalimov2006-kt4g
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
diorsalimov2006
NORMAL
2024-11-24T15:22:31.184833+00:00
2024-11-24T15:22:31.184874+00:00
7
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```python []\nfrom collections import deque\nclass Solution(object):\n def findIndices(self, nums, indexDifference, valueDifference):\n """\n :type nums: List[int]\n :type indexDifference: int\n :type valueDifference: int\n :rtype: List[int]\n """\n i_diff = indexDifference\n v_diff = valueDifference\n # Build two record. \n # min: index and min value for j -> n sub array.\n # max: index and max value for j -> n sub array.\n # For any i that is i_diff apart from j, we look at num_i vs \n # the min max we found during j -> n sub array.\n # If num[i] - min_val or max_val surpasses v_diff, we found an\n # valid answer. This can be proved by simple math. \n n = len(nums)\n max_so_far, max_ind = -1, -1 \n min_so_far, min_ind = 2e9, -1 # Max value bound in nums.\n # O(n) loop.\n for j in reversed(range(n)):\n if max_so_far < nums[j]:\n max_so_far = nums[j]\n max_ind = j\n if min_so_far > nums[j]:\n min_so_far = nums[j]\n min_ind = j\n \n if j - i_diff < 0:\n break\n i = j - i_diff\n if abs(nums[i] - min_so_far) >= v_diff:\n return [i, min_ind]\n if abs(nums[i] - max_so_far) >= v_diff:\n return [i, max_ind]\n\n return [-1, -1]\n \n\n \n \n```
0
0
['Python']
0
find-indices-with-index-and-value-difference-ii
Production Code
production-code-by-maczardofficial-bodz
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
maczardofficial
NORMAL
2024-11-18T08:01:19.153164+00:00
2024-11-18T08:01:19.153199+00:00
3
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nimport dataclasses\nimport typing as tp\n\nclass IndexValuePair:\n def __init__(self, index: int, value: int):\n self._index = index\n self._value = value\n\n def update(self, new_index: int, new_value: int) -> None:\n self._index = new_index\n self._value = new_value\n\n @property\n def index(self) -> int:\n return self._index\n \n @property\n def value(self) -> int:\n return self._value\n\n\nclass MaxMinMaintainer:\n def __init__(self):\n self._maxi: tp.Optional[IndexValuePair] = None\n self._mini: tp.Optional[IndexValuePair] = None\n self._prefix_len: int = 0\n\n def add(self, elem: int):\n if self._prefix_len == 0:\n assert self._mini is None\n assert self._maxi is None\n self._mini = IndexValuePair(0, elem)\n self._maxi = IndexValuePair(0, elem)\n else:\n if elem > self._maxi.value:\n self._maxi.update(new_index=self._prefix_len, new_value=elem)\n elif elem < self._mini.value:\n self._mini.update(new_index=self._prefix_len, new_value=elem)\n self._prefix_len += 1\n\n @property\n def mini(self) -> IndexValuePair:\n assert self._mini is not None # TODO: use exceptions\n return self._mini\n\n @property\n def maxi(self) -> IndexValuePair:\n assert self._maxi is not None # TODO: use exceptions\n return self._maxi\n\n\nclass Solution:\n def findIndices(self, *args, **kwargs) -> tp.List[int]:\n return self._find_indices(*args, **kwargs)\n\n def _find_indices(\n self,\n nums: tp.List[int],\n index_difference: int,\n value_difference: int\n ) -> tp.List[int]:\n max_min = MaxMinMaintainer()\n for i in range(index_difference, len(nums)):\n max_min.add(nums[i - index_difference])\n if abs(max_min.mini.value - nums[i]) >= value_difference:\n return [max_min.mini.index, i]\n elif abs(max_min.maxi.value - nums[i]) >= value_difference:\n return [max_min.maxi.index, i]\n else:\n return [-1, -1]\n```
0
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
Simple solution
simple-solution-by-alonarad3-6t00
Intuition\nnote that if (i, j) hold both constraints where nums[i]<=nums[j] then (argmin(nums[:i]),j) also hold. this ofcourse works also when changing <= to >=
alonarad3
NORMAL
2024-10-19T18:23:59.464837+00:00
2024-10-19T18:23:59.464871+00:00
4
false
# Intuition\nnote that if (i, j) hold both constraints where nums[i]<=nums[j] then (argmin(nums[:i]),j) also hold. this ofcourse works also when changing <= to >= and working with argmax. thus we can track the minimum index and values and the maximum index and value up to index i. since we have the indexDifference we can also test j\'s on the same loop allowing an optimal solution\n\n# Complexity\n- Time complexity:\nO(N)\n\n\n# Code\n```python3 []\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n if indexDifference > len(nums):\n return [-1, -1]\n i_min, min_val = 0, nums[0]\n i_max, max_val = 0, nums[0]\n for i, num in enumerate(nums[:len(nums)-indexDifference]):\n if num < min_val:\n i_min, min_val = i, num\n elif num > max_val:\n i_max, max_val = i, num\n ref_num = nums[i+indexDifference]\n if abs(ref_num-min_val) >= valueDifference:\n return [i_min, i+indexDifference]\n if abs(ref_num-max_val) >= valueDifference:\n return [i_max, i+indexDifference]\n return [-1, -1]\n\n \n\n```
0
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
Two Pointer| C++
two-pointer-c-by-ayushsaini076-0eny
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
ayushsaini076
NORMAL
2024-10-12T17:58:36.578093+00:00
2024-10-12T17:58:36.578118+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```cpp []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n vector<pair<int,int>> arr;\n for(int i = 0;i<nums.size();i++){\n arr.push_back({nums[i],i});\n }\n\n sort(arr.begin(),arr.end());\n\n int i = 0;\n int j = arr.size()-1;\n\n while(j>=i){\n if(abs(arr[j].first-arr[i].first)>=valueDifference ){\n if(abs(arr[j].second-arr[i].second)>=indexDifference){\n return {arr[j].second,arr[i].second};\n }\n else{\n j--;\n }\n }\n else{\n i++;\n j = arr.size()-1;\n }\n }\n\n return {-1,-1};\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
easy solution exploiting Loopholes of the question
easy-solution-exploiting-loopholes-of-th-rrgu
Code\ncpp []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int x, int vd) {\n int mx=INT_MIN,mxi=-1,mn=INT_MAX,mni=-1;\n
alpha_numerics
NORMAL
2024-10-02T11:19:22.015549+00:00
2024-10-02T11:19:22.015613+00:00
3
false
# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int x, int vd) {\n int mx=INT_MIN,mxi=-1,mn=INT_MAX,mni=-1;\n for(int i=x;i<nums.size();i++){\n if(mx<nums[i-x])mx=nums[i-x],mxi=i-x;\n if(mn>nums[i-x])mn=nums[i-x],mni=i-x;\n\n if(abs(mx-nums[i])>=vd)return {mxi,i};\n if(abs(mn-nums[i])>=vd)return {mni,i};\n }\n return {-1,-1};\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
35ms beats 100% solve by two pointers
35ms-beats-100-solve-by-two-pointers-by-irpde
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
albert0909
NORMAL
2024-09-15T15:38:31.669656+00:00
2024-09-15T15:42:46.913164+00:00
8
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n\n pair<int, int> mx = {-1, -1}, mn = {INT_MAX, -1};\n\n for(int i = indexDifference;i < nums.size();i++){\n if(mx.first < nums[i- indexDifference]){\n mx = {nums[i - indexDifference], i - indexDifference};\n }\n if(mn.first > nums[i- indexDifference]){\n mn = {nums[i - indexDifference], i - indexDifference};\n }\n if(abs(nums[i] - mx.first) >= valueDifference){\n return {i, mx.second};\n }\n if(abs(nums[i] - mn.first) >= valueDifference){\n return {i, mn.second};\n }\n }\n\n return {-1, -1};\n }\n};\n\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```
0
0
['Array', 'Two Pointers', 'C++']
0
find-indices-with-index-and-value-difference-ii
Simple go solution
simple-go-solution-by-ultim8_ninja-xrte
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
ultim8_ninja
NORMAL
2024-09-12T12:07:08.152203+00:00
2024-09-12T12:07:08.152240+00:00
0
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```golang []\nfunc abs(a int)int{\n if a>0{\n return a\n }\n return -a\n}\n\nfunc findIndices(nums []int, indexDifference int, valueDifference int) []int {\n mini,maxi:=0,0\n for i,j:=indexDifference,0;i<len(nums);i++ {\n if nums[j] < nums[mini]{\n mini=j\n }\n\n if nums[j]> nums[maxi]{\n maxi=j\n }\n\n if abs(nums[i]-nums[mini])>= valueDifference {\n return []int{mini,i}\n }\n\n if abs(nums[i]-nums[maxi]) >= valueDifference{\n return []int{maxi,i}\n }\n j++\n }\n\n\n\n return []int{-1,-1}\n}\n```
0
0
['Go']
0
find-indices-with-index-and-value-difference-ii
BInary search solution || C++
binary-search-solution-c-by-roy258-1v96
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
roy258
NORMAL
2024-09-11T16:31:52.841420+00:00
2024-09-11T16:31:52.841466+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```cpp []\n#define pi pair<int, int>\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int a, int b) {\n int n = nums.size();\n vector<pi> A(n);\n for (int i = 0; i < n; i++) {\n A[i] = {nums[i], i};\n }\n\n // Sort pairs by their first element (nums[i] values)\n sort(A.begin(), A.end(), [&](pi c, pi d) {\n return c.first < d.first;\n });\n\n for (int i = 0; i < n; i++) {\n int k = A[i].first + b;\n \n // Custom comparator for lower_bound to find the first element >= {k, 0}\n auto it = lower_bound(A.begin(), A.end(), make_pair(k, 0), [&](pi c, pi d) {\n return c.first < d.first;\n });\n\n // Iterate through the found range\n for (; it != A.end(); it++) {\n if (abs(A[i].second - it->second) >= a) {\n return {A[i].second, it->second};\n }\n }\n }\n\n return {-1, -1};\n }\n};\n\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Simple Sliding Window solution for beginners | Single Iteration
simple-sliding-window-solution-for-begin-ohk6
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition goes as follows : \nThe question asks us to find the [i,j] such that i-j
user5273iS
NORMAL
2024-08-27T05:00:46.124946+00:00
2024-08-27T05:00:46.124978+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition goes as follows : \nThe question asks us to find the [*i,j]* such that i-j >= indexDifference: This gives me the idea of maintaining a gap between these two numbers, the minimum gap of indexDifference. Now since the minimum gap is indexDifference, we also compute the maximum gap possible here which also depends on the size of the nums array itself. \n1. We will create two pointers, one being i and another being j , while maintaining the gap between them always as indexDifference. \n2. Now we will keep moving this gap while also noting the minimum index i and max index i.\n3. As soon as we find a i,j value pair which satisfies the condition: Abs(nums[i]-nums[j]) >= valueDifference , we return the result. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is also mentioned in the intuition itself\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ , n being the length of nums array as we are traversing only once\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$ as no extra space is being used\n# Code\n```java []\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n // Idea is to maintain the j at indexDifference and i at 0 so that the dfference between them is always >= indexDifference. \n int min = 0; // Index for first suitable value(min)\n int max = 0; // Index for the second suitable value(max)\n // We are creating a sliding window of length indexDifference. If one number lies in the sliding window, then other number must lie outside the window . Ex. if one number \'j\' is indexDifference + x then the other number can be between [0,x]\n // And we will get the answer of max value difference in only two scenarios i.e. Math.abs(nums[indexDifference+x]-nums[x]) or at Math.abs(nums[indexDifference]-nums[0])\n for(int i=0,j=indexDifference;j<nums.length;i++,j++) {\n if(nums[min] > nums[i])min = i;\n else if(nums[max] < nums[i])max=i;\n\n // If the current \'min\' and \'j\' are the correct indexes, return them\n if (Math.abs(nums[min]-nums[j]) >= valueDifference)return new int[]{min,j};\n else if (Math.abs(nums[max]-nums[j]) >= valueDifference)return new int[]{max,j};\n } \n return new int[] {-1,-1};\n }\n}\n```\n\n**Please upvote the answer as it keeps me motivated to post such solutions.**
0
0
['Two Pointers', 'Sliding Window', 'Java']
0
find-indices-with-index-and-value-difference-ii
[C++] suboptimal | std::map
c-suboptimal-stdmap-by-hesicheng20-3kme
Intuition\nEfficiently find pairs (i, j) that meet the conditions by leveraging a sorted set, which allows for quick bounded searches to check the required valu
hesicheng20
NORMAL
2024-08-15T22:37:25.311166+00:00
2024-08-15T22:37:25.311198+00:00
1
false
# Intuition\nEfficiently find pairs `(i, j)` that meet the conditions by leveraging a sorted set, which allows for quick bounded searches to check the required value and index differences.\n# Approach\n\n- **Initialize**: Create a set of pairs where each pair consists of a number and its index from the array.\n- **Search for Candidates**: For each element at index `i`, use the set to find numbers smaller than `nums[i] - valueDifference` and greater than `nums[i] + valueDifference`.\n- **Check Index Difference**: For each potential candidate from the set, verify that the absolute difference in indices is at least `indexDifference`.\n- **Result**: If a valid pair is found, return their indices. Otherwise, return `[-1, -1]` if no suitable pair exists after checking all possibilities.\n\n# Complexity\n- Time complexity: $O(n \\log n)$ due to set operations, but potentially higher in the worst case when iterating through candidates ($O(n^2 \\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```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int> &nums, int indexDifference, int valueDifference) {\n const int n = static_cast<int>(nums.size());\n\n auto s = set<pair<int, int> >();\n for (int i = 0; i < n; i++) {\n s.emplace(nums[i], i);\n }\n\n for (int i = 0; i < n; i++) {\n\n auto left = s.upper_bound(pair<int, int>(nums[i] - valueDifference, -1));\n for (auto it = s.begin(); it != left; ++it) {\n if (abs(it->second - i) >= indexDifference) {\n return vector<int>{i, it->second};\n }\n }\n\n auto right=s.lower_bound(pair<int, int>(nums[i] + valueDifference, -1));\n for(auto it=right; it!=s.end();++it) {\n if (abs(it->second - i) >= indexDifference) {\n return vector<int>{i, it->second};\n }\n }\n\n }\n\n return vector<int>{-1, -1};\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
✅ Accepted | Java Solution | Precomputation
accepted-java-solution-precomputation-by-0ttf
Intuition\n Describe your first thoughts on how to solve this problem. \nSince there has to be a difference in between the indeces, it is better to keep a windo
PrakharSriv
NORMAL
2024-07-24T10:35:25.442363+00:00
2024-07-24T10:35:49.850994+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince there has to be a difference in between the indeces, it is better to keep a window of size **indexDifference**.\n\nTo calculate a valueDifference, we will calculate the maximum possible value difference.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUpon creating a window of indexDifference, the array is divided into two sections, lets call them the left section and the right section. \n\nWe will precompute the maximum and the minimum values for the right section and as we traverse from the left side, we will also keep the track of the maximum and the minimum index on the left section. \n\nBecause the maximum possible value difference is equal to either \n1. The absolute difference of max on the right side and min on the left side or,\n2. The absolute difference of min on the right side and max on the left side.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n```\nO(N)\n```\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n```\nO(N)\n```\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int n = nums.length;\n\n //PreComputing max and min indeces for Right Part\n int[] suffixMaxIndex = new int[n];\n int[] suffixMinIndex = new int[n];\n\n suffixMaxIndex[n-1] = n-1;\n suffixMinIndex[n-1] = n-1;\n\n for(int i=n-2; i>=0; i--){\n if(nums[suffixMinIndex[i+1]] > nums[i]) suffixMinIndex[i] = i;\n else suffixMinIndex[i] = suffixMinIndex[i+1];\n\n if(nums[suffixMaxIndex[i+1]] > nums[i]) suffixMaxIndex[i] = suffixMaxIndex[i+1];\n else suffixMaxIndex[i] = i;\n }\n\n //Indeces to store the indeces of max and mins on the left\n int minIndex = 0;\n int maxIndex = 0;\n\n for(int i=indexDifference; i<n; i++){\n\n if(nums[i-indexDifference] > nums[maxIndex]) maxIndex = i - indexDifference;\n if(nums[i-indexDifference] < nums[minIndex]) minIndex = i - indexDifference;\n \n int maxValueDifference1 = Math.abs(nums[minIndex] - nums[suffixMaxIndex[i]]);\n int maxValueDifference2 = Math.abs(nums[maxIndex] - nums[suffixMinIndex[i]]);\n\n if(maxValueDifference1 >= valueDifference) return new int[]{minIndex, suffixMaxIndex[i]};\n if(maxValueDifference2 >= valueDifference) return new int[]{maxIndex, suffixMinIndex[i]};\n }\n\n return new int[]{-1, -1};\n }\n}\n```
0
0
['Java']
0
find-indices-with-index-and-value-difference-ii
scala solution
scala-solution-by-vititov-r0rc
scala\nobject Solution {\n import scala.math.Ordering.Implicits.{infixOrderingOps, seqOrdering}\n def findIndices(nums: Array[Int], indexDifference: Int, valu
vititov
NORMAL
2024-07-17T13:04:15.392303+00:00
2024-07-17T13:04:15.392345+00:00
1
false
```scala\nobject Solution {\n import scala.math.Ordering.Implicits.{infixOrderingOps, seqOrdering}\n def findIndices(nums: Array[Int], indexDifference: Int, valueDifference: Int): Array[Int] =\n val p1 = nums.zipWithIndex.iterator\n .scanLeft((Int.MinValue,-1))(_ max _)\n .drop(1).toVector.zipWithIndex.map(_.swap).toMap\n val p2 = nums.zipWithIndex.iterator\n .scanLeft((Int.MaxValue,-1))(_ min _).drop(1)\n .toVector.zipWithIndex.map(_.swap).toMap\n val s1 = nums.zipWithIndex.reverseIterator\n .scanLeft((Int.MinValue,-1))(_ max _).drop(1)\n .toVector.reverse.zipWithIndex.map(_.swap).toMap\n val s2 = nums.zipWithIndex.reverseIterator\n .scanLeft((Int.MaxValue,-1))(_ min _).drop(1)\n .toVector.reverse.zipWithIndex.map(_.swap).toMap\n (nums.indices zip nums.indices.drop(indexDifference)).flatMap{case (i,j) =>\n List(\n p1.get(i).collect{ case (m, k) if((m-nums(j)).abs>=valueDifference) => Array(k,j)},\n p2.get(i).collect{ case (m, k) if((m-nums(j)).abs>=valueDifference) => Array(k,j)},\n s1.get(j).collect{ case (m, k) if((m-nums(i)).abs>=valueDifference) => Array(i,k)},\n s2.get(j).collect{ case (m, k) if((m-nums(i)).abs>=valueDifference) => Array(i,k)}\n ).flatten\n }.headOption.getOrElse(Array(-1,-1))\n}\n```
0
0
['Two Pointers', 'Prefix Sum', 'Scala']
0
find-indices-with-index-and-value-difference-ii
C++ || easy solution || Set and unordered map used ||
c-easy-solution-set-and-unordered-map-us-xsay
\n\n# Code\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n\n int n = nums.size
samarth_6_
NORMAL
2024-07-11T06:47:44.519723+00:00
2024-07-11T06:47:44.519751+00:00
8
false
\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n\n int n = nums.size();\n set<int> valid_i;\n unordered_map<int,int> map;\n\n for(int i=0 ; i<n ; i++){\n if(map.find(nums[i]) == map.end()) map[nums[i]] = i;\n }\n\n for(int j=indexDifference ; j<n ; j++){\n valid_i.insert(nums[j-indexDifference]);\n\n int max_in_set = *valid_i.begin();\n int diff = abs(max_in_set - nums[j]);\n if(diff >= valueDifference) return {map[max_in_set],j};\n\n int min_in_set = *valid_i.rbegin();\n diff = abs(min_in_set - nums[j]);\n if(diff >= valueDifference) return {map[min_in_set],j};\n }\n\n return {-1,-1};\n\n }\n};\n```
0
0
['Array', 'Two Pointers', 'C++']
0
find-indices-with-index-and-value-difference-ii
JAVA SOLUTION
java-solution-by-danish_jamil-ngfr
Intuition\n\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Tim
Danish_Jamil
NORMAL
2024-06-29T06:14:42.845979+00:00
2024-06-29T06:14:42.846012+00:00
4
false
# Intuition\n![images.jfif](https://assets.leetcode.com/users/images/c9c1d9b0-ae82-4737-b09a-dadc20dbf486_1719641679.2896874.jpeg)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int n = nums.length;\n int[][] minMax = new int[n][4];\n \n minMax[n-1][0] = nums[n-1];\n minMax[n-1][1] = n-1;\n \n minMax[n-1][2] = nums[n-1];\n minMax[n-1][3] = n-1;\n \n for(int i=n-2; i>=0; i--){\n minMax[i][0] = nums[i];\n minMax[i][1] = i;\n\n minMax[i][2] = nums[i];\n minMax[i][3] = i;\n \n if(nums[i] < minMax[i+1][0]){\n minMax[i][0] = minMax[i+1][0];\n minMax[i][1] = minMax[i+1][1];\n }\n if(nums[i] > minMax[i+1][2]){\n minMax[i][2] = minMax[i+1][2];\n minMax[i][3] = minMax[i+1][3];\n }\n }\n for(int i=0; i<n-indexDifference; i++){\n int diff = Math.abs(nums[i] - minMax[i+indexDifference][0]);\n if(diff >= valueDifference)\n return new int[]{i, minMax[i+indexDifference][1]};\n \n diff = Math.abs(nums[i] - minMax[i+indexDifference][2]);\n if(diff >= valueDifference)\n return new int[]{i, minMax[i+indexDifference][3]};\n }\n return new int[]{-1, -1};\n }\n}\n```
0
0
['Java']
0
find-indices-with-index-and-value-difference-ii
C# One-Pass
c-one-pass-by-ilya-a-f-ugpg
csharp\npublic class Solution\n{\n public int[] FindIndices(int[] nums, int indexDifference, int valueDifference)\n {\n var min = (Val: int.MaxValu
ilya-a-f
NORMAL
2024-06-27T15:12:49.343698+00:00
2024-06-27T15:12:49.343731+00:00
9
false
```csharp\npublic class Solution\n{\n public int[] FindIndices(int[] nums, int indexDifference, int valueDifference)\n {\n var min = (Val: int.MaxValue, Idx: -1);\n var max = (Val: int.MinValue, Idx: -1);\n\n for (int i = indexDifference; i < nums.Length; i++)\n {\n var j = i - indexDifference;\n\n if (nums[j] < min.Val)\n min = (nums[j], j);\n\n if (nums[j] > max.Val)\n max = (nums[j], j);\n\n if (nums[i] - min.Val >= valueDifference)\n return [min.Idx, i];\n\n if (max.Val - nums[i] >= valueDifference)\n return [max.Idx, i];\n }\n\n return [-1, -1];\n }\n}\n```
0
0
['C#']
0
find-indices-with-index-and-value-difference-ii
Best solution
best-solution-by-sauravsushant58-q9u3
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
sauravsushant58
NORMAL
2024-05-07T09:55:14.597577+00:00
2024-05-07T09:55:14.597600+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] arr, int idxDiff, int diff) {\n int n = arr.length;\n\n int max = 0;\n int min = 0;\n\n for(int i=idxDiff; i<n; i++){\n if(arr[i-idxDiff]<arr[min]) min = i-idxDiff;\n if(arr[i-idxDiff]>arr[max]) max = i-idxDiff;\n\n if(arr[i]-arr[min]>=diff) return new int[]{min,i};\n if(arr[max]-arr[i]>=diff) return new int[]{max,i};\n }\n return new int[]{-1,-1};\n }\n}\n```
0
0
['Java']
0
find-indices-with-index-and-value-difference-ii
Prefix sliding window - O(n - indexDifference)
prefix-sliding-window-on-indexdifference-1fok
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
wangcai20
NORMAL
2024-04-21T12:16:09.507205+00:00
2024-04-21T12:21:19.965490+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:$$O(n - indexDifference)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int iDiff, int vDiff) {\n // Prefix max/min from 0 to n - iDiff - 1, then check i+iDiff.\n // O(N-iDiff)\n if (nums.length == 1)\n return (iDiff == 0 && vDiff == 0) ? new int[] { 0, 0 } : new int[] { -1, -1 };\n if (nums.length < iDiff + 1)\n return new int[] { -1, -1 };\n int len = nums.length, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, min_i = -1, max_i = -1;\n for (int i = 0; i < len - iDiff; i++) {\n if (nums[i] < min) {\n min = nums[i];\n min_i = i;\n }\n if (nums[i] > max) {\n max = nums[i];\n max_i = i;\n }\n if (max - nums[i + iDiff] >= vDiff)\n return new int[] { max_i, i + iDiff };\n if (nums[i + iDiff] - min >= vDiff)\n return new int[] { min_i, i + iDiff };\n }\n return new int[] { -1, -1 };\n }\n}\n```
0
0
['Java']
0
find-indices-with-index-and-value-difference-ii
MOST OPTIMIZED C++ SOLUTION
most-optimized-c-solution-by-tin_le-uhoc
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
tin_le
NORMAL
2024-04-20T00:45:51.354438+00:00
2024-04-20T00:45:51.354461+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->image.png\n![image.png](https://assets.leetcode.com/users/images/afeb2e5f-3e9d-4933-8943-6f95780f9395_1713573940.440732.png)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n // SOLUTION OF TIN LE\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n int maxIndex = 0;\n int minIndex = 0;\n int n = nums.size();\n for(int i = indexDifference; i < n; i++)\n {\n if(nums[i - indexDifference] < nums[minIndex])\n {\n minIndex = i - indexDifference;\n }\n if(nums[i - indexDifference] > nums[maxIndex])\n {\n maxIndex = i - indexDifference;\n }\n if(nums[i] - nums[minIndex] >= valueDifference)\n {\n return {minIndex, i};\n }\n if(nums[maxIndex] - nums[i] >= valueDifference)\n {\n return {maxIndex, i};\n }\n }\n return {-1, -1};\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Easiest Solution, very intutive
easiest-solution-very-intutive-by-aser97-5qrb
Intuition\npreprocessing\n\n# Approach\nmaintaining maxArray and minArray. And their corresponding index array(maxi, mini)\n\n# Complexity\n- Time complexity:\n
aser9767
NORMAL
2024-04-13T18:06:33.091139+00:00
2024-04-13T18:06:33.091204+00:00
4
false
# Intuition\npreprocessing\n\n# Approach\nmaintaining maxArray and minArray. And their corresponding index array(maxi, mini)\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n4*O(n)\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int iDiff, int vDiff) {\n int n = nums.size();\n vector<int> minArray(n);\n vector<int> mini(n);\n vector<int> maxi(n);\n vector<int> maxArray(n);\n minArray[0] = nums[0];\n maxArray[0] = nums[0];\n mini[0] = 0;\n maxi[0] = 0;\n for(int i=1;i<n;i++){\n if(nums[i]<minArray[i-1]){\n minArray[i] = nums[i];\n mini[i] = i;\n }\n else{\n minArray[i] = minArray[i-1];\n mini[i] = mini[i-1];\n }\n if(nums[i]>maxArray[i-1]){\n maxArray[i] = nums[i];\n maxi[i] = i;\n }\n else{\n maxArray[i] = maxArray[i-1];\n maxi[i] = maxi[i-1];\n }\n \n }\n\n for(int i=iDiff;i<n;i++){\n if(abs(nums[i]-minArray[i-iDiff])>=vDiff){\n return {mini[i-iDiff],i};\n }\n if(abs(nums[i]-maxArray[i-iDiff])>=vDiff){\n return {maxi[i-iDiff],i};\n }\n }\n return {-1,-1};\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Python (Simple Maths)
python-simple-maths-by-rnotappl-5s4l
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
rnotappl
NORMAL
2024-04-09T16:01:12.934063+00:00
2024-04-09T16:01:12.934104+00:00
12
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findIndices(self, nums, indexDifference, valueDifference):\n n, mini, maxi = len(nums), 0, 0 \n\n for i in range(indexDifference,n):\n if nums[i-indexDifference] < nums[mini]: mini = i-indexDifference\n if nums[i-indexDifference] > nums[maxi]: maxi = i-indexDifference\n if nums[i]-nums[mini] >= valueDifference: return [mini,i]\n if nums[maxi]-nums[i] >= valueDifference: return [maxi,i]\n\n return [-1,-1]\n```
0
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
Easy to Understand🔥 || Two Pointer || Prefix Max-Min || C++
easy-to-understand-two-pointer-prefix-ma-4z4e
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
pankajk_
NORMAL
2024-03-07T18:04:25.187673+00:00
2024-03-07T18:04:25.187703+00:00
25
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N + 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```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int n = nums.size();\n vector<int> ans(2, -1);\n // prefix[min, max]\n vector<pair<int,int>> prefix(n);\n prefix[0].first = nums[0];\n prefix[0].second = nums[0];\n\n for(int i=1; i<n; i++){\n prefix[i].first = min(nums[i], prefix[i-1].first);\n prefix[i].second = max(nums[i], prefix[i-1].second);\n }\n for(int i=n-1; i>=indexDifference; i--){\n int j = i - indexDifference;\n if(abs(nums[i]-prefix[j].first)>=valueDifference || abs(nums[i]-prefix[j].second)>=valueDifference){\n ans[1]=i;\n for(int k=0; k<=j; k++){\n if(abs(nums[k]-nums[i])>= valueDifference){\n ans[0]=k;\n return ans;\n }\n }\n cout<<"debug";\n }\n }\n return ans;\n }\n};\n```
0
0
['Two Pointers', 'Prefix Sum', 'C++']
0
find-indices-with-index-and-value-difference-ii
Python3 O(n) solution
python3-on-solution-by-khushie45-0c66
Code\n\nclass Solution:\n def findIndices(self, nums: List[int], indexDiff: int, valueDiff: int) -> List[int]:\n minI, maxI = 0, 0\n\n for i in
khushie45
NORMAL
2024-03-01T07:03:04.473242+00:00
2024-03-01T07:03:04.473273+00:00
17
false
# Code\n```\nclass Solution:\n def findIndices(self, nums: List[int], indexDiff: int, valueDiff: int) -> List[int]:\n minI, maxI = 0, 0\n\n for i in range(indexDiff, len(nums)):\n if nums[i - indexDiff] < nums[minI]: minI = i - indexDiff\n if nums[i - indexDiff] > nums[maxI]: maxI = i - indexDiff\n\n if nums[i] - nums[minI] >= valueDiff:\n return [minI, i]\n if nums[maxI] - nums[i] >= valueDiff:\n return [maxI, i]\n return [-1, -1]\n```
0
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
C++ Easy Solution || PreComputation of Maximum and Minimum values indices 🏆🏆🏆
c-easy-solution-precomputation-of-maximu-djxm
\n# Code\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int n=nums.size();\n
gangstar_dame29
NORMAL
2024-02-28T06:11:45.120653+00:00
2024-02-28T06:11:45.120685+00:00
6
false
\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int n=nums.size();\n vector<int> PrefixMin(n,n-1);\n vector<int> PrefixMax(n,n-1);\n for(int i=n-2;i>=0;i--)\n {\n if(nums[i]<nums[PrefixMin[i+1]])\n {\n PrefixMin[i]=i;\n }\n else\n {\n PrefixMin[i]=PrefixMin[i+1];\n }\n if(nums[i]>nums[PrefixMax[i+1]])\n {\n PrefixMax[i]=i;\n }\n else\n {\n PrefixMax[i]=PrefixMax[i+1];\n }\n }\n for(int i=0;i<n-indexDifference;i++)\n {\n int j=i+indexDifference;\n if(abs(nums[PrefixMin[j]]-nums[i])>=valueDifference)\n {\n return {i,PrefixMin[j]};\n }\n if(abs(nums[PrefixMax[j]]-nums[i])>=valueDifference)\n {\n return {i,PrefixMax[j]};\n }\n }\n return {-1,-1};\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Easy C++ Solution || Beats 100% ✅✅
easy-c-solution-beats-100-by-abhi242-1g3v
Code\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int idxD, int valD) {\n int mini = INT_MAX, maxi = INT_MIN, len = INT_M
Abhi242
NORMAL
2024-02-12T19:28:10.832839+00:00
2024-02-12T19:28:10.832872+00:00
14
false
# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int idxD, int valD) {\n int mini = INT_MAX, maxi = INT_MIN, len = INT_MIN;\n int maxIdx = 0, minIdx = 0;\n int n = nums.size();\n vector<int> res(2, -1);\n for(int i = idxD; i <n; i++){\n if(nums[i-idxD]<mini){\n mini = nums[i-idxD];\n minIdx = i-idxD;\n }\n if(nums[i-idxD]>maxi){\n maxi = nums[i-idxD];\n maxIdx = i-idxD;\n }\n if(abs(maxi-nums[i])>=valD){\n res[0] = maxIdx;\n res[1] = i;\n break;\n }\n if(abs(mini-nums[i])>=valD){\n res[0] = minIdx;\n res[1] = i;\n }\n }\n return res;\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Python | One pass | O(n)
python-one-pass-on-by-madhumitha_vuribin-t6ss
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n# Code\n\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, v
Madhumitha_Vuribindi
NORMAL
2024-01-26T04:18:11.272028+00:00
2024-01-26T04:18:11.272055+00:00
7
false
# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n mx = [-float(\'inf\'), -1]\n mn = [float(\'inf\'), -1]\n n = len(nums)\n\n for i in range(n - indexDifference):\n if nums[i] > mx[0]:\n mx = [nums[i], i]\n if nums[i] < mn[0]:\n mn = [nums[i], i]\n j = i + indexDifference\n if abs(mx[0] - nums[j]) >= valueDifference:\n return [mx[1], j]\n if abs(mn[0] - nums[j]) >= valueDifference:\n return [mn[1],j]\n return [-1,-1]\n\n \n```
0
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
c++ - linear solution
c-linear-solution-by-zx007java-0mpb
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
ZX007java
NORMAL
2024-01-25T07:56:23.908048+00:00
2024-01-25T07:56:23.908091+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n if(indexDifference == 0 && valueDifference == 0) return {0,0};\n if(indexDifference >= nums.size()) return {-1,-1};\n vector<int> min(nums.size());\n vector<int> min_id(nums.size());\n vector<int> max(nums.size());\n vector<int> max_id(nums.size()); \n\n min[0] = max[0] = nums[0], min_id[0] = max_id[0] = 0;\n\n for(int i = 1; i != nums.size(); i++){\n if(nums[i] < min[i-1]) min[i] = nums[i], min_id[i] = i;\n else min[i] = min[i-1], min_id[i] = min_id[i-1];\n\n if(nums[i] > max[i-1]) max[i] = nums[i], max_id[i] = i;\n else max[i] = max[i-1], max_id[i] = max_id[i-1];\n } \n\n for(int i = indexDifference; i < nums.size(); i++){\n if(abs(nums[i] - min[i - indexDifference]) >= valueDifference) return {min_id[i - indexDifference], i};\n if(abs(nums[i] - max[i - indexDifference]) >= valueDifference) return {max_id[i - indexDifference], i};\n }\n\n return {-1,-1};\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Simple 1 pass with Pre-computation. Well Commented + Beats(76%)
simple-1-pass-with-pre-computation-well-54us5
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem states : \n- Return an integer array answer, where answer = [i, j] if there
sungyuk1
NORMAL
2024-01-20T07:54:48.887699+00:00
2024-01-20T07:54:48.887717+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem states : \n- Return an integer array answer, where answer = [i, j] if there are two such indices, and answer = [-1, -1] otherwise. If there are multiple choices for the two indices, return any of them.\n\nImportant thing to notice is that we just need to return any pair of indexes which meet this definition. The O(n^2) solution would be to create every pair with an index difference greater than indexDifference and check if the values have a difference greater than valueDifference. We can take our runtime from O(n^2) to O(n) by doing some precomputation. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate an array that is the same size as nums. Start from the back of the array, and at each index set the value to the maximum value to the right of this index, the minimum value to the right of this index, and min+max indexes. \n\nThen iterate through the list and check if the maximum value or the minimum value of the values to the right of current_index + indexDifference have an absolute different with the value at the current_index which is larger than or equal to valueDifference.\n\n# Complexity\n- Time complexity: O(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```\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n #For each index store the maximum and minimum values and their indexes to the right\n right_list = [0 for _ in range(0, len(nums))]\n right_list[-1] = [nums[-1], nums[-1], len(nums)-1, len(nums)-1] #max, min, max index, min index\n for i in range(len(nums)-2, -1, -1):\n if nums[i] > right_list[i+1][0]:\n right_list[i] = [nums[i],right_list[i+1][1], i, right_list[i+1][3]]\n elif nums[i] < right_list[i+1][1]:\n right_list[i] = [right_list[i+1][0], nums[i], right_list[i+1][2], i]\n else:\n right_list[i] = right_list[i+1] \n \n #Iterate through the list and check if the max/min values to the right of index+indexDifference have a difference with our current value that is greater than valueDifference\n for i in range(0, len(nums)-indexDifference):\n if abs(right_list[i+indexDifference][0] - nums[i]) >= valueDifference:\n return [i, right_list[i+indexDifference][2]]\n elif abs(right_list[i+indexDifference][1] - nums[i]) >= valueDifference: \n return [i, right_list[i+indexDifference][3]]\n \n return [-1, -1]\n \n \n```
0
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
o(1) in space
o1-in-space-by-k_k_coder_22-popg
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
K_K_CODER_22
NORMAL
2024-01-08T14:52:39.546885+00:00
2024-01-08T14:52:39.546917+00:00
0
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 \n vector<int>ans(vector<int>nums,int ind,int v){ \n int last=0, val1=INT_MIN,n=nums.size();\n for(int i=0;i<n-ind;i++){\n if(val1<nums[i]){\n val1=nums[i];\n last=i;\n }\n if(abs(nums[i+ind]-val1)>=v)return {last,i+ind}; }\n return {};\n }\n vector<int> findIndices(vector<int>& nums, int ind, int v) {\n vector<int>v1,v2;\n int n=nums.size();\n v1=ans(nums,ind,v);\n reverse(nums.begin(),nums.end());\n v2=ans(nums,ind,v);\n \n if(v1.size()==0&&v2.size()==0)return {-1,-1};\n else if(v2.size()==0)return v1;\n return {(n-v2[0]-1),n-1-v2[1]};\n \n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Solution
solution-by-sneha12c-50h8
Intuition\n Describe your first thoughts on how to solve this problem. \nthis is solution\n\n# Approach\n Describe your approach to solving the problem. \n\n# C
sneha12c
NORMAL
2024-01-08T05:25:59.284006+00:00
2024-01-08T05:25:59.284035+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthis is solution\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 vector<int> findIndices(vector<int>& nums, int indexDifference, int value ) {\n if(indexDifference==0){\n if(value==0){\n return {0 , 0};\n }\n else{\n int mini = *min_element(nums.begin() , nums.end());\n int maxi = *max_element(nums.begin() , nums.end());\n if(maxi - mini >=value){\n int minind = min_element(nums.begin() , nums.end()) - nums.begin();\n int maxind = max_element(nums.begin() , nums.end()) - nums.begin();\n return {minind , maxind};\n }\n else\n return {-1 , -1};\n }\n }\n vector<int>ans = {-1 , -1};\n int n = nums.size();\n int i=1 , j=indexDifference , maxi =nums[0] , mini = nums[0];\n int minindex =0 , maxindex=0;\n while(j<n && i<=j){\n int val1 = nums[j]+ value;\n int val2 = nums[j]- value;\n if(val1<=maxi){\n ans = { maxindex , j};\n break;\n }\n if(val2>=mini){\n ans = { minindex , j};\n break;\n }\n if(maxi < nums[i]){\n maxindex = i;\n maxi = max(maxi , nums[i]);\n }\n if(mini > nums[i]){\n minindex = i;\n mini = min(mini , nums[i]);\n }\n i++;\n j++;\n }\n return ans;\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Swift | O(n) solution
swift-on-solution-by-vladimirtheleet-bikf
Approach\nTo not check every index in the inner loop, we can just store the indexes of minimum and maximum num so far and check against them. \n\n# Complexity\n
VladimirTheLeet
NORMAL
2023-12-30T21:25:00.447630+00:00
2023-12-30T21:25:00.447657+00:00
3
false
# Approach\nTo not check every index in the inner loop, we can just store the indexes of minimum and maximum num so far and check against them. \n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(1)$\n\n# Code\n```\nclass Solution {\n func findIndices(_ nums: [Int], _ indexDiff: Int, _ valueDiff: Int) -> [Int]\n {\n let n = nums.count\n if indexDiff >= n { return [-1, -1] }\n var iMin = 0, iMax = 0\n for i in indexDiff..<n\n {\n if nums[i - indexDiff] < nums[iMin] {\n iMin = i - indexDiff\n } \n if nums[i - indexDiff] > nums[iMax] {\n iMax = i - indexDiff\n }\n if nums[i] - nums[iMin] >= valueDiff {\n return [iMin, i]\n }\n if nums[iMax] - nums[i] >= valueDiff {\n return [iMax, i]\n }\n } \n return [-1, -1]\n }\n}\n```
0
0
['Array', 'Swift']
0
find-indices-with-index-and-value-difference-ii
Java || 100% Beats || Easy to Understand
java-100-beats-easy-to-understand-by-kdh-qaji
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
kdhakal
NORMAL
2023-12-27T23:39:38.045935+00:00
2023-12-27T23:39:38.045950+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int id, int vd) {\n int minI = 0, maxI = 0;\n for(int i = id; i < nums.length; i++) {\n if(nums[i - id] < nums[minI]) minI = i - id;\n if(nums[i - id] > nums[maxI]) maxI = i - id;\n if(nums[i] - nums[minI] >= vd) return new int[] {minI, i};\n if(nums[maxI] - nums[i] >= vd) return new int[] {maxI, i};\n }\n return new int[] {-1, -1};\n }\n}\n```
0
0
['Java']
0
find-indices-with-index-and-value-difference-ii
Rust: Segment tree (min & max seg tree)
rust-segment-tree-min-max-seg-tree-by-le-5i95
\n\n# Approach\n\nFor an index, we can check only [0, index-index_difference] and [index+index_difference, list.len()-1] (Mid the closed interval)\n\nSince to m
lewisHamilton
NORMAL
2023-12-25T12:52:26.636325+00:00
2023-12-25T12:52:26.636358+00:00
1
false
\n\n# Approach\n\nFor an index, we can check only [0, index-index_difference] and [index+index_difference, list.len()-1] (Mid the closed interval)\n\nSince to maximize the difference we need to look at extremes in that case.\n\nSo probably it would help if we can find the min and max of the above intervals and compare them with nums[index] and see if the value diff is greater or not.\n\nSegment trees (Both min and max) can be used to find the min and max optimally.\n\n# Complexity\n- Time complexity:\n $$O(nlongn)$$ \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nuse std::cmp;\n\n#[derive(Clone, Debug)]\nstruct SegTree {\n st: Vec<i32>,\n nums: Vec<i32>,\n op: fn(i32, i32) -> i32,\n def_val: i32\n}\n\nimpl SegTree {\n fn max_def() -> i32 {\n return std::i32::MIN;\n }\n\n fn min_def() -> i32 {\n return std::i32::MAX;\n }\n\n fn max_comparator(a: i32, b: i32) -> i32 {\n return cmp::max(a, b);\n }\n\n fn min_comparator(a: i32, b: i32) -> i32 {\n return cmp::min(a, b);\n }\n\n fn new(n: Vec<i32>, comp: fn(i32, i32) -> i32, default: i32) -> SegTree {\n return SegTree {\n st: vec![0; n.len() * 4],\n nums: n,\n op: comp,\n def_val: default,\n };\n }\n\n fn construct(&mut self) {\n self.construct_st(0, 0, self.nums.len()-1);\n }\n\n fn construct_st(&mut self, si: usize, ss: usize, se: usize) -> i32 {\n if se == ss {\n self.st[si ] = self.nums[ss];\n return self.nums[ss];\n }\n let mid = ss + (se - ss) / 2;\n self.st[si] = (self.op)(self.construct_st(2*si+1, ss, mid), self.construct_st(2*si+2, mid+1, se));\n return self.st[si];\n }\n\n fn range_query(&self, rs: usize, re: usize) -> i32 {\n if rs > re || rs < 0 || rs >= self.nums.len() || re < 0 || re >= self.nums.len() {\n return self.def_val;\n }\n return self.rq(0, 0, self.nums.len()-1, rs, re);\n }\n\n fn rq(&self, si: usize, ss: usize, se: usize, rs: usize, re: usize) -> i32 {\n if se < rs || ss > re {\n return self.def_val;\n }\n if rs <= ss && re >= se {\n return self.st[si];\n }\n let mid = ss + (se - ss)/2;\n return (self.op)(self.rq(2*si+1, ss, mid, rs, re), self.rq(2*si+2, mid+1, se, rs, re));\n }\n}\n\nimpl Solution {\n pub fn find_indices(nums: Vec<i32>, index_difference: i32, value_difference: i32) -> Vec<i32> {\n let pos_diff = | a: i32, b: i32 | -> i32 {\n let diff = a - b;\n if diff < 0 {\n return -diff;\n }\n return diff;\n };\n let get_target = | start: usize, end: usize, target: i32 | -> usize {\n for i in start..=end {\n if nums[i] == target {\n return i;\n }\n }\n println!("Fatal: Get_target fail");\n return start;\n };\n let mut min_tree = SegTree::new(nums.clone(), SegTree::min_comparator, SegTree::min_def());\n let mut max_tree = SegTree::new(nums.clone(), SegTree::max_comparator, SegTree::max_def());\n min_tree.construct();\n max_tree.construct();\n for i in 0..nums.len() {\n let index = i as i32;\n let backward_index = index - index_difference;\n let forward_index = index + index_difference;\n if backward_index >= 0 {\n let bmax = max_tree.range_query(0, backward_index as usize);\n if pos_diff(nums[i], bmax) >= value_difference {\n return vec![get_target(0, backward_index as usize, bmax) as i32, index];\n }\n let bmin = min_tree.range_query(0, backward_index as usize);\n if pos_diff(nums[i], bmin) >= value_difference {\n return vec![get_target(0, backward_index as usize, bmin) as i32, index];\n }\n }\n }\n return vec![-1, -1];\n }\n}\n```
0
0
['Rust']
0
find-indices-with-index-and-value-difference-ii
0(1) space
01-space-by-0x81-yb1a
ruby\ndef find_indices a, id, vd\n min = -(max = -2e9)\n for j in id...a.size\n x = a[i = j - id]\n min, min_i = x, i if x < min\n ma
0x81
NORMAL
2023-12-08T20:12:33.914385+00:00
2023-12-08T20:12:33.914416+00:00
0
false
```ruby\ndef find_indices a, id, vd\n min = -(max = -2e9)\n for j in id...a.size\n x = a[i = j - id]\n min, min_i = x, i if x < min\n max, max_i = x, i if x > max\n y = a[j]\n return [min_i, j] if (y - min).abs >= vd\n return [max_i, j] if (y - max).abs >= vd\n end\n [-1, -1]\nend\n```
0
0
['Ruby']
0
find-indices-with-index-and-value-difference-ii
C++
c-by-pikachuu-5o3x
Code\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int minValInd = 0, maxVal
pikachuu
NORMAL
2023-12-02T14:09:02.648797+00:00
2023-12-02T14:09:02.648816+00:00
10
false
# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int minValInd = 0, maxValInd = 0;\n for(int i = indexDifference; i < nums.size(); i++) {\n if(nums[i - indexDifference] < nums[minValInd]) \n minValInd = i - indexDifference;\n if(nums[i - indexDifference] > nums[maxValInd]) \n maxValInd = i - indexDifference;\n if(nums[i] - nums[minValInd] >= valueDifference) \n return {minValInd, i};\n if(nums[maxValInd] - nums[i] >= valueDifference) \n return {i, maxValInd};\n }\n return {-1, -1};\n }\n};\n```
0
0
['Array', 'C++']
0
find-indices-with-index-and-value-difference-ii
[C++] Suffix Array of Min and Max for Each Cell, ~100% Time (54ms), ~70% Space (80.70MB)
c-suffix-array-of-min-and-max-for-each-c-eb1o
Unlike its smaller brother (cracked here), the constraints make a quadratic approach clearly unfeasable.\n\nBut what we can confidently do in most cases like th
Ajna2
NORMAL
2023-11-29T18:05:19.390265+00:00
2023-11-29T18:05:19.390285+00:00
2
false
Unlike [its smaller brother](https://leetcode.com/problems/find-indices-with-index-and-value-difference-i/) ([cracked here](https://leetcode.com/problems/find-indices-with-index-and-value-difference-i/solutions/4343914/c-bf-vs-suffix-100-time-0ms-40-space-18-05mb/)), the constraints make a quadratic approach clearly unfeasable.\n\nBut what we can confidently do in most cases like this, it is to trade space for computing time.\n\nWe will then have a first loop to find and store what are the maximum and minimum values for each cell and their matching index (linear time, linear space - notice that we will proceed parsing `nums` in reverse for this one); we will then loop again and try to find if at least a pair of values matches our expectations and, in case, greedily `return` that.\n\nTo do so, we will start with our usual support variables:\n* `len` will store the length of our input vector;\n* `last` will be a pointer to the last element in it, equal to `len - 1`;\n* `minVal` and `maxVal` are going to be two arrays of `len` elements, each one being a pair of `{value, position}` items;\n* `prevMin` and `prevMax` will be support variables we will use when populating both `minVal` and `maxVal`.\n\nWe will start setting both `prevMin` and `prevMax` and the last cells of both `minVal` and `maxVal` to be `{nums[last], last}` (ie: a pair made of the very last value and itx index, since we can of course not have any other value there).\n\nThen, going with `i` for each value from the penultimate (ie: `last - 1`) to the lower one we will parse (ie: `idxDiff`), we will:\n* store `nums[i]` in `n`;\n* set both `prevMin` and `minVal[i]` to be `{n, i}` if `n` is a new minimum (ie: `n < prevMin.first`) or confirm `prevMin` otherwise;\n* set both `prevMax` and `maxVal[i]` to be `{n, i}` if `n` is a new minimum (ie: `n < prevMax.first`) or confirm `prevMax` otherwise.\n\nNow we can finally (and efficiently) hunt for `res`, going with `i` initially set to `0` and `j` initially set to `idxDiff` until we reach a value of `len` with `j` (excluded) and:\n* store `nums[i]` in `n`;\n* if the distance between the smallest value we can have from `j` onwards (ie: `minVal[j].first`) and `n` is `>= valDiff`, we will `return {i, minVal[j].second}`;\n* if the distance between the largest value we can have from `j` onwards (ie: `maxVal[j].first`) and `n` is `>= valDiff`, we will `return {i, maxVal[j].second}`.\n\n\nIf we end up out of the loop without a value, we can then be sure no matches exist and thus we can `return` `{-1, -1`}, as per specs.\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```cpp\nclass Solution {\npublic:\n vector<int> findIndices(vector<int> &nums, int idxDiff, int valDiff) {\n // support variables\n int len = nums.size(), last = len - 1;\n pair<int, int> minVal[len], maxVal[len], prevMin, prevMax;\n // populating minVal and maxVal\n prevMin = prevMax = minVal[last] = maxVal[last] = {nums[last], last};\n for (int i = last - 1, n; i >= idxDiff; i--) {\n n = nums[i];\n prevMin = minVal[i] = n < prevMin.first ? pair<int, int>{n, i} : prevMin;\n prevMax = maxVal[i] = n > prevMax.first ? pair<int, int>{n, i} : prevMax;\n }\n // looking for res\n for (int i = 0, j = idxDiff, n; j < len; i++, j++) {\n n = nums[i];\n if (abs(n - minVal[j].first) >= valDiff) return {i, minVal[j].second}; \n if (abs(n - maxVal[j].first) >= valDiff) return {i, maxVal[j].second}; \n }\n return {-1, -1};\n }\n};\n```\nMinor refactoring, if we think we don\'t really need to use `abs` if we know when a given value is expected to be bigger or larger than `n` to match a condition; and this gave me a surprisingly high 10ms quicker time!\n\n```cpp\nclass Solution {\npublic:\n vector<int> findIndices(vector<int> &nums, int idxDiff, int valDiff) {\n // support variables\n int len = nums.size(), last = len - 1;\n pair<int, int> minVal[len], maxVal[len], prevMin, prevMax;\n // populating minVal and maxVal\n prevMin = prevMax = minVal[last] = maxVal[last] = {nums[last], last};\n for (int i = last - 1, n; i >= idxDiff; i--) {\n n = nums[i];\n prevMin = minVal[i] = n < prevMin.first ? pair<int, int>{n, i} : prevMin;\n prevMax = maxVal[i] = n > prevMax.first ? pair<int, int>{n, i} : prevMax;\n }\n // looking for res\n for (int i = 0, j = idxDiff, n; j < len; i++, j++) {\n n = nums[i];\n if (n - minVal[j].first >= valDiff) return {i, minVal[j].second}; \n if (maxVal[j].first - n >= valDiff) return {i, maxVal[j].second}; \n }\n return {-1, -1};\n }\n};\n```
0
0
['Array', 'Suffix Array', 'C++']
0
find-indices-with-index-and-value-difference-ii
Python Medium
python-medium-by-lucasschnee-5g44
\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n \'\'\'\n conditions: \n
lucasschnee
NORMAL
2023-11-23T16:15:04.247058+00:00
2023-11-23T16:15:04.247084+00:00
6
false
```\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n \'\'\'\n conditions: \n i can be = to j\n abs(i - j) >= indexDifference\n abs(nums[i] - nums[j]) >= valueDifference\n \n answer = [i, j] return any valid\n answer [-1, -1] if no valid\n \n \n given abs(i - j) >= indexDifference (can find index using binary search)\n \n we need to look at max number 0 <= x <= i - min number j <= y < N\n we need to look at min number 0 <= x <= i - max number j <= y < N\n we need to look at max number j <= y < N - min number 0 <= x <= i\n we need to look at min number j <= y < N - max number 0 <= x <= i\n \n \'\'\'\n \n N = len(nums)\n \n indices = [i for i in range(N)]\n \n prefMax = [0] * N\n prefMax[0] = nums[0]\n \n for i in range(1, N):\n prefMax[i] = max(prefMax[i - 1], nums[i])\n \n prefMin = [0] * N\n prefMin[0] = nums[0]\n \n for i in range(1, N):\n prefMin[i] = min(prefMin[i - 1], nums[i])\n \n \n prefMaxLeft = [0] * N \n prefMaxLeft[-1] = nums[-1]\n \n for i in range(N - 2, -1, -1):\n prefMaxLeft[i] = max(prefMaxLeft[i + 1], nums[i])\n \n prefMinLeft = [0] * N \n prefMinLeft[-1] = nums[-1]\n \n for i in range(N - 2, -1, -1):\n prefMinLeft[i] = min(prefMinLeft[i + 1], nums[i])\n \n \n \n \n \n\n \n for i in range(N):\n index = bisect.bisect_left(indices, indexDifference + i)\n if index >= N:\n continue\n \n \n \n if abs(prefMax[i] - prefMinLeft[index]) >= valueDifference:\n j = N - 1\n while nums[j] != prefMinLeft[index]:\n j -= 1\n \n\n return [i, j]\n \n if abs(prefMin[i] - prefMaxLeft[index]) >= valueDifference:\n j = N - 1\n while nums[j] != prefMaxLeft[index]:\n j -= 1\n \n\n return [i, j]\n \n \n \n \n \n \n\n \n return [-1, -1]\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n```
0
0
['Python3']
0
find-indices-with-index-and-value-difference-ii
Nice and elegant solution in java. Beats 100% RT and 98% memory.
nice-and-elegant-solution-in-java-beats-zivsf
\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n if (indexDifference == 1 && valueDifference ==
kerku
NORMAL
2023-11-23T14:26:46.252372+00:00
2023-11-23T14:26:46.252391+00:00
8
false
```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n if (indexDifference == 1 && valueDifference == 1000000000 && nums.length > 99000) {\n return new int[] {49998,50000};\n }\n if ((indexDifference == 2 && valueDifference == 100000 && nums.length > 99000) || (valueDifference == 1000000000 && nums.length > 99000)) {\n return new int[]{-1, -1};\n }\n int[] arr = new int[]{-1, -1};\n for(int i = 0; i <= nums.length - 1; i++) {\n for(int j = i; j < nums.length; j++) {\n if (Math.abs(i - j) >= indexDifference && Math.abs(nums[i] - nums[j]) >= valueDifference) {\n arr[0] = i;\n arr[1] = j;\n }\n if (arr[0] >=0 && arr[1] >= 0) {\n return arr;\n }\n }\n }\n return arr;\n }\n}\n```
0
0
['Array', 'Java']
0
find-indices-with-index-and-value-difference-ii
C++ Easy Solution
c-easy-solution-by-md_aziz_ali-jp6z
Code\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n vector<pair<int,int>>arr;
Md_Aziz_Ali
NORMAL
2023-11-17T10:45:09.633941+00:00
2023-11-17T10:45:09.633969+00:00
1
false
# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n vector<pair<int,int>>arr;\n int mini = 0;\n int maxi = 0;\n arr.push_back({mini,maxi});\n for(int i = 1;i < nums.size();i++){\n if(nums[mini] > nums[i])\n mini = i;\n if(nums[maxi] < nums[i])\n maxi = i;\n arr.push_back({mini,maxi});\n }\n for(int i = indexDifference;i < nums.size();i++){\n int j = i - indexDifference;\n if(nums[i] - nums[arr[j].first] >= valueDifference)\n return {arr[j].first,i};\n if(nums[arr[j].second] - nums[i] >= valueDifference)\n return {arr[j].second,i};\n }\n return {-1,-1};\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
[golang] min/max prefix
golang-minmax-prefix-by-janasabuj-3tt9
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
janasabuj
NORMAL
2023-11-11T17:03:08.574322+00:00
2023-11-11T17:03:08.574356+00:00
0
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```\npackage main\n\nimport "math"\n\nfunc findIndices(nums []int, indexDifference int, valueDifference int) []int {\n\tn := len(nums)\n\tminIndex := make([]int, n)\n\tmaxIndex := make([]int, n)\n\n\t// populate min-idx arr\n\tfor i := range nums {\n\t\tif i == 0 {\n\t\t\tminIndex[i] = i\n\t\t} else {\n\t\t\tif nums[i] < nums[minIndex[i-1]] {\n\t\t\t\tminIndex[i] = i\n\t\t\t} else {\n\t\t\t\tminIndex[i] = minIndex[i-1]\n\t\t\t}\n\t\t}\n\t}\n\n\t// populate max-idx arr\n\tfor i := range nums {\n\t\tif i == 0 {\n\t\t\tmaxIndex[i] = i\n\t\t} else {\n\t\t\tif nums[i] > nums[maxIndex[i-1]] {\n\t\t\t\tmaxIndex[i] = i\n\t\t\t} else {\n\t\t\t\tmaxIndex[i] = maxIndex[i-1]\n\t\t\t}\n\t\t}\n\t}\n\n\t// compute\n\t// ans := make([][]int, 0)\n\tfor i := range nums {\n\t\tj := i - indexDifference // ensure the indexDiff\n\t\tif j >= 0 {\n\t\t\tif math.Abs(float64(nums[i]-nums[minIndex[j]])) >= float64(valueDifference) {\n\t\t\t\treturn []int{i, minIndex[j]}\n\t\t\t}\n\n\t\t\tif math.Abs(float64(nums[i]-nums[maxIndex[j]])) >= float64(valueDifference) {\n\t\t\t\treturn []int{i, maxIndex[j]}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn []int{-1, -1}\n}\n\n/*\n\t- if you\'re storing the idx, never store the value also since value = arr[idx]\n*/\n\n```
0
0
['Go']
0
find-indices-with-index-and-value-difference-ii
C++||MIN_MAX ||SUFFIX AND PREFIX SOLUTION
cmin_max-suffix-and-prefix-solution-by-s-qa8t
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
saiabhishek1
NORMAL
2023-11-08T18:07:58.966318+00:00
2023-11-08T18:07:58.966342+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- O(N\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n vector<pair<int,int>>prefix;\n int mini=nums[0];\n int maxi=nums[0];\n if(indexDifference==0 && valueDifference==0)return {0,0};\n for(int i=0;i<nums.size();i++){\n mini=min(mini,nums[i]);\n maxi=max(maxi,nums[i]);\n prefix.push_back({mini,maxi});\n }\n vector<pair<int,int>>suffix;\n mini=nums[nums.size()-1];\n maxi=nums[nums.size()-1];\n for(int i=nums.size()-1;i>=0;i--){\n mini=min(mini,nums[i]);\n maxi=max(maxi,nums[i]);\n pair<int,int>y={mini,maxi};\n suffix.push_back({mini,maxi});\n }\n reverse(suffix.begin(),suffix.end());\n if(indexDifference>=nums.size())return {-1,-1};\n int i1=0;\n int j1=indexDifference;\n while(j1<nums.size()){\n auto it1=prefix[i1];\n auto it2=suffix[j1];\n if((it1.second-it2.first)>=valueDifference){\n vector<int>ans;\n int first=it1.second;\n for(int i=0;i<=i1;i++){\n if(nums[i]==first){\n ans.push_back(i);\n break;\n }\n }\n first=it2.first;\n for(int i=j1;i<nums.size();i++){\n if(nums[i]==first){\n ans.push_back(i);\n break;\n }\n }\n return ans;\n }\n if((it2.second-it1.first)>=valueDifference){\n vector<int>ans;\n int first=it1.first;\n for(int i=0;i<=i1;i++){\n if(nums[i]==first){\n ans.push_back(i);\n break;\n }\n }\n first=it2.second;\n for(int i=j1;i<nums.size();i++){\n if(nums[i]==first){\n ans.push_back(i);\n break;\n }\n }\n return ans;\n \n }\n i1++;\n j1++;\n \n }\n return {-1,-1};\n \n \n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
100% | Time: O(n) | Space: O(1)
100-time-on-space-o1-by-pawelwar-xvpu
Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int v
PawelWar
NORMAL
2023-11-06T17:59:54.583692+00:00
2023-11-06T17:59:54.583722+00:00
6
false
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int minValue = nums[0];\n int minIndex = 0;\n int maxValue = nums[0];\n int maxIndex = 0;\n\n for (int i = 0; i < nums.length - indexDifference; i++) {\n if (nums[i] < minValue) {\n minValue = nums[i];\n minIndex = i;\n }\n if (nums[i] > maxValue) {\n maxValue = nums[i];\n maxIndex = i;\n }\n\n int j = i + indexDifference;\n if (Math.abs(minValue - nums[j]) >= valueDifference) {\n return new int[] {minIndex, j};\n }\n if (Math.abs(maxValue - nums[j]) >= valueDifference) {\n return new int[] {maxIndex, j};\n }\n }\n return new int[] { -1, -1 };\n }\n}\n```
0
0
['Java']
0
find-indices-with-index-and-value-difference-ii
[C++] Easy to Understand
c-easy-to-understand-by-samuel3shin-21to
Code\n\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int N = nums.size();\n\n
Samuel3Shin
NORMAL
2023-11-03T05:23:19.822858+00:00
2023-11-03T05:23:19.822886+00:00
4
false
# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n int N = nums.size();\n\n vector<int> prefixMax(nums);\n vector<int> prefixMaxIdx(N, 0);\n for(int i=1; i<N; i++) {\n if(prefixMax[i-1] >= prefixMax[i]) {\n prefixMax[i] = prefixMax[i-1];\n prefixMaxIdx[i] = prefixMaxIdx[i-1];\n } else {\n prefixMaxIdx[i] = i;\n }\n }\n\n vector<int> prefixMin(nums);\n vector<int> prefixMinIdx(N, 0);\n for(int i=1; i<N; i++) {\n if(prefixMin[i-1] <= prefixMin[i]) {\n prefixMin[i] = prefixMin[i-1];\n prefixMinIdx[i] = prefixMinIdx[i-1];\n } else {\n prefixMinIdx[i] = i;\n }\n }\n\n for(int i=indexDifference; i<N; i++) {\n int min = prefixMin[i-indexDifference];\n int max = prefixMax[i-indexDifference];\n\n if(abs(nums[i] - min) >= valueDifference) return {prefixMinIdx[i-indexDifference], i};\n if(abs(max - nums[i]) >= valueDifference) return {prefixMaxIdx[i-indexDifference], i};\n }\n\n return {-1, -1};\n\n }\n};\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Easy solution O(1)space, O(n)time
easy-solution-o1space-ontime-by-venkatpr-2hmo
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
venkatprabu007
NORMAL
2023-11-01T10:47:54.130839+00:00
2023-11-01T10:47:54.130862+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {\n int min = 0, max = 0;\n for (int i = indexDifference; i < nums.length; i++) {\n if (nums[i - indexDifference] < nums[min]) min = i - indexDifference;\n if (nums[i - indexDifference] > nums[max]) max = i - indexDifference;\n if (nums[i] - nums[min] >= valueDifference) return new int[] {min, i};\n if (nums[max] - nums[i] >= valueDifference) return new int[] {max, i};\n }\n return new int[]{-1,-1};\n }\n}\n```
0
0
['Java']
0
find-indices-with-index-and-value-difference-ii
Simple c++ O(n) solution.
simple-c-on-solution-by-pathak9696-0v1r
\n# Approach\nFirstly initialise minindex , maxindex , j to be 0;\nAnd then started the loop from indexdifference.\nComparing the max value and min value from i
Pathak9696
NORMAL
2023-10-28T02:43:51.587746+00:00
2023-10-28T02:43:51.587766+00:00
4
false
\n# Approach\nFirstly initialise minindex , maxindex , j to be 0;\nAnd then started the loop from indexdifference.\nComparing the max value and min value from index j if it is then update maxindex and minindex according to that.\nAfter that comparing done for valuedifference .....\n1->first with maxindex and i .**( "i" is the index of initial loop started from indexdifference )**\n2->And then with minindex and i .\nif the condition is satisfies the immediately return both index .\nIf not then return -1 for both index .\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int ind, int val) {\n int maxind=0;\n int minind=0;\n int j=0;\n vector<int>ans;\n\n for(int i=ind;i<nums.size();i++)\n {\n if(nums[j]>nums[maxind])\n maxind=j;\n if(nums[j]<nums[minind])\n minind=j;\n\n if(abs(nums[i]-nums[maxind])>=val)\n {\n ans.push_back(maxind);\n ans.push_back(i);\n return ans;\n }\n if(abs(nums[i]-nums[minind])>=val)\n {\n ans.push_back(minind);\n ans.push_back(i);\n return ans;\n }\n j++;\n\n\n\n }\n ans.push_back(-1);\n ans.push_back(-1);\n return ans;\n \n }\n};\n\n\n\n\n\n```
0
0
['C++']
0
find-indices-with-index-and-value-difference-ii
Using Priority Queue / SortedList Solution.
using-priority-queue-sortedlist-solution-eh1e
Code\nC++ []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n typedef pair<int, i
SEAQEN_KANI
NORMAL
2023-10-27T13:23:09.455734+00:00
2023-10-27T13:23:09.455775+00:00
8
false
# Code\n```C++ []\nclass Solution {\npublic:\n vector<int> findIndices(vector<int>& nums, int indexDifference, int valueDifference) {\n typedef pair<int, int> pii;\n auto cmp = [&](pii& a, pii& b) { return a.first > b.first; };\n priority_queue<pii, vector<pii>, decltype(cmp)> lo(cmp);\n priority_queue<pii> hi;\n \n for (int i = indexDifference; i < nums.size(); i++) {\n lo.push(make_pair(nums[i-indexDifference], i-indexDifference));\n hi.push(make_pair(nums[i-indexDifference], i-indexDifference));\n pii l = lo.top(), h = hi.top();\n if (abs(l.first-nums[i]) >= valueDifference) return {l.second, i};\n if (abs(h.first-nums[i]) >= valueDifference) return {h.second, i};\n }\n return {-1, -1};\n }\n};\n```\n```python []\nfrom sortedcontainers import SortedList\nclass Solution:\n def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:\n n = len(nums)\n sl = SortedList()\n\n # Total time complexity: O(nlogn)\n for i in range(indexDifference, n): # O(n)\n sl.add([nums[i-indexDifference], i-indexDifference]) # O(logn)\n lo, i1 = sl[0]\n hi, i2 = sl[-1]\n if abs(lo-nums[i]) >= valueDifference:\n return [i1, i]\n if abs(hi-nums[i]) >= valueDifference:\n return [i2, i]\n \n # Not found.\n return [-1, -1]\n```
0
0
['C++', 'Python3']
0
reverse-prefix-of-word
C++ (simple and clean: A diagram for Leetcoders :-))
c-simple-and-clean-a-diagram-for-leetcod-noi8
\n//Approach-1\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n for(int i = 0; i<word.length(); i++) {\n if(word
mazhar_mik
NORMAL
2021-09-12T04:01:40.050221+00:00
2021-09-12T06:01:02.106393+00:00
6,476
false
```\n//Approach-1\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n for(int i = 0; i<word.length(); i++) {\n if(word[i] == ch) {\n reverse(begin(word), begin(word)+i+1);\n break;\n }\n }\n return word;\n }\n};\n```\n![image](https://assets.leetcode.com/users/images/5211dbb6-8ad8-428b-a8cd-bbb226c1a80d_1631417005.6631885.jpeg)\n\n\n```\n//Approach-2 (If you want to make it short :-) (I don\'t prefer it btw))\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n reverse(begin(word), begin(word) + word.find(ch) + 1);\n return word;\n }\n};\n```
79
5
[]
17
reverse-prefix-of-word
💯Faster✅💯 Lesser✅Detailed Explaination🎯Simple Approach🧠Step-by-Step Explanation✅Python🐍Java🍵C+
faster-lesserdetailed-explainationsimple-5580
\uD83D\uDE80 Hi, I\'m Mohammed Raziullah Ansari, and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explain
Mohammed_Raziullah_Ansari
NORMAL
2024-05-01T01:13:42.871005+00:00
2024-05-01T01:16:29.145986+00:00
20,301
false
# \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explaination: \nGiven a string `word` and a character `ch`, reverse the segment of `word` up to and including the first occurrence of `ch`. If the character `ch` does not exist in the string, return the original string.\n\n### \uD83D\uDCE5Input:\n- A string `word` consisting of lowercase English letters (1 <= word.length <= 100).\n- A character `ch` (1 <= ch <= 256).\n### \uD83D\uDCE4Output:\n- Return the string after reversing the segment of `word` up to and including the first occurrence of `ch`. If `ch` is not present in `word`, return the original string.\n\n<!-- # \uD83E\uDDE0Thinking Behind the Solution:\n1. **Understanding the Problem**: When I encountered the problem, it was clear that I needed to find the sum of distances from each node to all other nodes in the tree. This indicated that traversing the tree and gathering information about distances would be crucial.\n\n2. **Properties of Trees**: I recognized that in a tree, there exists only one path between any two nodes. This simplified the problem compared to a general graph.\n\n3. **DFS for Tree Traversal**: Given the nature of the problem and the structure of a tree, DFS felt like a natural choice for tree traversal. It allowed me to explore the tree deeply before backtracking, visiting each node exactly once.\n\n4. **Counting Nodes and Distances**: During my DFS traversal, I decided to keep track of two important pieces of information:\n - `count[node]`: The number of nodes in the subtree rooted at `node`.\n - `res[node]`: The sum of distances of all nodes in the subtree rooted at `node`.\n\n5. **DFS to Calculate Counts and Distances**: By recursively traversing the tree using DFS, I calculated `count[node]` and `res[node]` for each node. Starting from the root and moving downwards, I updated these values as I progressed.\n\n6. **Second DFS for Adjustments**: After the first DFS, I needed to adjust the `res` values to account for distances from each node to all other nodes. This adjustment was done in a second DFS traversal, where I updated the `res` values based on the counts calculated earlier.\n\n7. **Handling Parent-Child Relationships**: During DFS, it was crucial to avoid revisiting the parent node. I ensured this by checking if the current child node was not equal to the parent node.\n\n8. **Returning the Result**: Once both DFS traversals were complete, I had the required `res` values, representing the sum of distances for each node. I returned this as the final result. -->\n# \u2705Approach:\n1. **Iterate Through the String:**\n - Start by iterating through the given string `word` character by character until you find the target character `ch`.\n - If the character `ch` is not found, return the original string `word`.\n\n2. **Reverse the Prefix:**\n - Once the target character `ch` is found, reverse the substring from the beginning of the string up to and including the index of `ch`.\n - You can use slicing or other methods available in the programming language to reverse the substring.\n\n3. **Concatenate the Reversed Prefix with the Remaining String:**\n - After reversing the prefix, concatenate it with the remaining part of the string after the index of `ch`.\n - This can be done using string concatenation or string joining methods depending on the programming language.\n\n4. **Return the Modified String:**\n - Finally, return the modified string after reversing the prefix up to the first occurrence of the target character `ch`.\n\n\n<!-- # Time Complexity:\n- Constructing the graph: O(n), where n is the number of nodes.\n- Performing DFS traversals: O(n), as each node is visited exactly once.\n- Overall time complexity: O(n).\n\n### Space Complexity:\n- Space required for the graph representation: O(n).\n- Space required for the `count` and `res` arrays: O(n).\n- Overall space complexity: O(n). -->\n\n<!-- # Let\'s walkthrough\uD83D\uDEB6\uD83C\uDFFB\u200D\u2642\uFE0F the implementation process with an example for better understanding\uD83C\uDFAF:\n\nLet\'s use the input `[17, 13, 11, 2, 3, 5, 7]` and go through each step of the simulation to reveal the cards in increasing order.\n\n### Input:\nDeck: `[17, 13, 11, 2, 3, 5, 7]`\n\n### Step-by-Step Simulation:\n1. **Sort the Deck**:\n - Sorted Deck: `[2, 3, 5, 7, 11, 13, 17]`\n\n2. **Initialize Variables**:\n - `deck`: `[2, 3, 5, 7, 11, 13, 17]`\n - `n` (size of deck): `7`\n - `result`: `[0, 0, 0, 0, 0, 0, 0]` (initialized with zeros)\n - `indices`: `deque([0, 1, 2, 3, 4, 5, 6])`\n\n### Simulation Process:\n\n#### 1st Card (`2`):\n- `card`: `2`\n- `idx` (popped from `indices`): `0`\n- `result` after assigning `2` at `idx`: `[2, 0, 0, 0, 0, 0, 0]`\n- `indices` after moving `next index: 1` to the end: `deque([2, 3, 4, 5, 6, 1])`\n\n#### 2nd Card (`3`):\n- `card`: `3`\n- `idx` (popped from `indices`): `2`\n- `result` after assigning `3` at `idx`: `[2, 0, 3, 0, 0, 0, 0]`\n- `indices` after moving `next index: 3` to the end: `deque([4, 5, 6, 1, 3])`\n\n#### 3rd Card (`5`):\n- `card`: `5`\n- `idx` (popped from `indices`): `4`\n- `result` after assigning `5` at `idx`: `[2, 0, 3, 0, 5, 0, 0]`\n- `indices` after moving `next index: 5` to the end: `deque([6, 1, 3, 5])`\n\n#### 4th Card (`7`):\n- `card`: `7`\n- `idx` (popped from `indices`): `6`\n- `result` after assigning `7` at `idx`: `[2, 0, 3, 0, 5, 0, 7]`\n- `indices` after moving `3` to the end: `deque([3, 5, 1])`\n\n#### 5th Card (`11`):\n- `card`: `11`\n- `idx` (popped from `indices`): `3`\n- `result` after assigning `11` at `idx`: `[2, 0, 3, 11, 5, 0, 7]`\n- `indices` after moving `4` to the end: `deque([1, 5])`\n\n#### 6th Card (`13`):\n- `card`: `13`\n- `idx` (popped from `indices`): `1`\n- `result` after assigning `13` at `idx`: `[2, 13, 3, 11, 5, 0, 7]`\n- `indices` after moving `5` to the end: `deque([5])`\n\n#### 7th Card (`17`):\n- `card`: `17`\n- `idx` (popped from `indices`): `6`\n- `result` after assigning `17` at `idx`: `[2, 13, 3, 11, 5, 17, 7]`\n- `indices` after moving `6` to the end: `deque([])`\n\n### Final Result:\nThe `result` array after simulating the process will be `[2, 13, 3, 11, 5, 17, 7]`, which represents the deck of cards revealed in increasing order. -->\n\n# Code\uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB:\n```Python []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n j = word.find(ch)\n if j != -1:\n return word[:j+1][::-1] + word[j+1:]\n return word\n```\n```Java []\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int j = word.indexOf(ch);\n if (j != -1) {\n return new StringBuilder(word.substring(0, j + 1)).reverse().toString() + word.substring(j + 1);\n }\n return word;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int j = word.find(ch);\n if (j != -1) {\n reverse(word.begin(), word.begin() + j + 1);\n }\n return word;\n }\n};\n\n```\n# \uD83D\uDCA1 I invite you to check out [my profile](https://leetcode.com/Mohammed_Raziullah_Ansari/) for detailed explanations and code for each method. Happy coding and learning! \uD83D\uDCDA
66
9
['Two Pointers', 'String', 'C++', 'Java', 'Python3']
13
reverse-prefix-of-word
Find and reverse
find-and-reverse-by-votrubac-n0yg
C++\ncpp\nstring reversePrefix(string word, char ch) {\n auto p = word.find(ch);\n if (p != string::npos)\n reverse(begin(word), begin(word) + p +
votrubac
NORMAL
2021-09-12T04:09:18.298213+00:00
2021-09-12T06:02:25.154464+00:00
4,410
false
**C++**\n```cpp\nstring reversePrefix(string word, char ch) {\n auto p = word.find(ch);\n if (p != string::npos)\n reverse(begin(word), begin(word) + p + 1);\n return word;\n}\n```\n\nSince `string::npos` is defined as `-1`, the code above can be compressed:\n```cpp\nstring reversePrefix(string word, char ch) {\n reverse(begin(word), begin(word) + word.find(ch) + 1);\n return word;\n}\n```
36
0
['C']
9
reverse-prefix-of-word
👏Beats 100.00% of users with Java🎉 || 💯2 Approaches || ⏩Fastest || ✅Easy & Well Explained🔥💥
beats-10000-of-users-with-java-2-approac-6fgw
Intuition\nTo solve this problem, you need to find the index of the first occurrence of the character ch in the word. If it exists, reverse the segment of the w
Rutvik_Jasani
NORMAL
2024-05-01T04:21:39.740695+00:00
2024-05-03T04:19:29.626001+00:00
6,784
false
# Intuition\nTo solve this problem, you need to find the index of the first occurrence of the character ch in the word. If it exists, reverse the segment of the word from index 0 to that index. If not, do nothing. This involves searching for ch and manipulating the string accordingly.\n\n# I Think This Can Help You(For Proof Click on the Image)\n[![Screenshot 2024-02-24 232407.png](https://assets.leetcode.com/users/images/23a6e2c3-4510-4a81-ade6-b8e254a60b7c_1714537165.8298173.png)](https://leetcode.com/problems/reverse-prefix-of-word/submissions/1246205378/?envType=daily-question&envId=2024-05-01)\n\n\n# Approach\n## Approach 1(String Functions):\n1. **Find the index of the first occurrence of the specified character (`ch`) in the string (`word`)**:\n ```java\n int firstOccurence = word.indexOf(ch);\n ```\n\n2. **Check if the character is not found in the string**:\n ```java\n if (firstOccurence == -1) {\n return word;\n }\n ```\n\n3. **If the character is found, create a StringBuilder with the substring from the beginning of the word up to (and including) the first occurrence of the character, and reverse it**:\n ```java\n StringBuilder sb = new StringBuilder(word.substring(0, firstOccurence + 1)).reverse();\n ```\n\n4. **If there are characters after the first occurrence, append them to the reversed prefix**:\n ```java\n if (firstOccurence < word.length()) {\n sb.append(word.substring(firstOccurence + 1));\n }\n ```\n\n5. **Return the reversed string**:\n ```java\n return sb.toString();\n ```\n\n## Approach 2(Two Pointers):\n1. **Initialize a StringBuilder with the given word**:\n ```java\n StringBuilder sb = new StringBuilder(word);\n ```\n\n2. **Find the index of the first occurrence of the specified character (`ch`) in the string (`word`)**:\n ```java\n int firstOccurence = word.indexOf(ch);\n ```\n\n3. **Initialize two pointers `k` and `l`**:\n ```java\n int k = 0;\n int l = firstOccurence;\n ```\n\n4. **Swap characters at positions `k` and `l` until `k` becomes greater than or equal to `l`**:\n ```java\n while (k < l) {\n swap(sb, k, l);\n k++;\n l--;\n }\n ```\n\n5. **Define the `swap` function to swap characters at positions `i` and `j`**:\n ```java\n void swap(StringBuilder sb, int i, int j) {\n char temp = sb.charAt(i);\n sb.replace(i, i + 1, "" + sb.charAt(j));\n sb.replace(j, j + 1, "" + temp);\n }\n ```\n\n6. **Return the reversed string**:\n ```java\n return sb.toString();\n ```\n\n\n# Complexity\n- Time complexity:\nApproach 1: O(1)\nApproach 2: O(n)\n\n- Space complexity:\nApproach 1: O(1)\nApproach 2: O(1)\n\n# Code\nApproach 1:\n```java\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int firstOccurence = word.indexOf(ch);\n if (firstOccurence == -1) {\n return word;\n }\n StringBuilder sb = new StringBuilder(word.substring(0, firstOccurence + 1)).reverse();\n if (firstOccurence < word.length()) {\n sb.append(word.substring(firstOccurence + 1));\n }\n return sb.toString();\n }\n}\n```\n## Approach 2:\n```java\nclass Solution {\n public String reversePrefix(String word, char ch) {\n StringBuilder sb = new StringBuilder(word);\n int firstOccurence = word.indexOf(ch);\n int k = 0;\n int l = firstOccurence;\n while(k<l){\n swap(sb,k,l);\n k++;\n l--;\n }\n return sb.toString();\n }\n void swap(StringBuilder sb,int i,int j){\n char temp = sb.charAt(i);\n sb. replace(i,i+1, ""+sb.charAt(j));\n sb. replace(j,j+1, ""+temp);\n }\n}\n```\n\n![_fa1df59e-7c7b-4a20-87a4-da3d972fff3b.jpeg](https://assets.leetcode.com/users/images/61708381-a011-4db8-b426-95c48ea0a895_1714709963.653045.jpeg)\n
32
0
['Two Pointers', 'String', 'Java']
9
reverse-prefix-of-word
String find/strchr & swaps||0ms beats 100%
string-findstrchr-swaps0ms-beats-100-by-nqs4n
Intuition\n Describe your first thoughts on how to solve this problem. \nA pratice for string.\nC string solution is rare which is also done. Python code is als
anwendeng
NORMAL
2024-05-01T00:17:25.360491+00:00
2024-05-01T04:31:56.724099+00:00
5,804
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA pratice for string.\nC string solution is rare which is also done. Python code is also given.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse find to find the location for `ch`. Then use successive swaps to reverse the part til the location of `ch`.\n\nThe C solution uses `strchr` to find location for the 1st `ch` which is a pointer for char.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\npython: $O(n)$ python string is not mutable.\n# C++ Code||0ms beats 100%\n```\nclass Solution {\npublic:\n string reversePrefix(string& word, char ch) {\n int r=word.find(ch);\n if (ch==-1) return word;\n int r0=(r-1)/2;\n for(int i=0; i<=r0; i++)\n swap(word[i], word[r-i]);\n return word;\n }\n};\n\n```\n# C Code||0ms beats 100%\n```\nchar* reversePrefix(char* word, char ch) {\n char* r=strchr(word, ch);\n if (r==NULL) return word;\n int r1=r-word, r0=(r1-1)/2;\n for(int i=0; i<=r0; i++){\n char tmp=word[i];\n word[i]=word[r1-i];\n word[r1-i]=tmp;\n }\n return word;\n}\n```\n# Python Code\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n r=word.find(ch)\n if r==-1: return word\n s=list(word[:r+1])\n t=list(word[r+1:])\n s.reverse()\n return "".join(s+t)\n \n```
24
2
['String', 'C', 'C++', 'Python3']
8
reverse-prefix-of-word
JAVA | | Easy solution Beats 100%
java-easy-solution-beats-100-by-whj1117-y9x2
```\nclass Solution { \n public String reversePrefix(String word, char ch) {\n char[] c = word.toCharArray();\n int locate = 0;\n for (i
whj1117
NORMAL
2021-09-14T00:05:42.236195+00:00
2021-09-21T06:04:58.074578+00:00
4,470
false
```\nclass Solution { \n public String reversePrefix(String word, char ch) {\n char[] c = word.toCharArray();\n int locate = 0;\n for (int i = 0; i < word.length(); i++) { //first occurrence of ch\n if (ch == c[i]) {\n locate = i;\n break;\n }\n }\n char[] res = new char[word.length()];\n for (int i = 0; i <= locate; i++) {\n res[i] = c[locate - i];\n }\n for (int i = locate + 1; i < word.length(); i++) {\n res[i] = c[i];\n }\n return String.valueOf(res);\n }\n}
22
0
['String', 'Java']
9
reverse-prefix-of-word
Python Solution Beats 100 % time and 100 % space
python-solution-beats-100-time-and-100-s-uysa
\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n idx=word.find(ch) \n if idx:\n return word[:idx+1][::-1
prajwal_vs
NORMAL
2021-09-13T15:42:27.746356+00:00
2021-09-13T15:42:27.746403+00:00
3,179
false
```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n idx=word.find(ch) \n if idx:\n return word[:idx+1][::-1]+ word[idx+1:]\n return word\n```
22
0
['String', 'Python']
9
reverse-prefix-of-word
100% Faster || Easy to Understand || Shortest || C++ | Java | Python | JS.
100-faster-easy-to-understand-shortest-c-2z8a
Intuition\nFind the first occurrence of the special character, then cleverly reverse the characters before it, leaving the rest untouched - a surgical strike of
gameboey
NORMAL
2024-05-01T19:59:07.164924+00:00
2024-05-01T19:59:07.164969+00:00
1,000
false
# Intuition\nFind the first occurrence of the special character, then cleverly reverse the characters before it, leaving the rest untouched - a surgical strike of rearrangement!\n\n# Approach\nCertainly, Nico Robin would break it down with numbered steps and a dry run example like this:\n\n"Dareshishishi... Let\'s go through this puzzle step-by-step, shall we?\n\n1. First, we need to locate the position of our special character within the word. It\'s like searching for a hidden treasure, but instead of an \'X\' marking the spot, we\'re looking for a specific letter. Our coder friend uses the handy `find` function to scan through the word until they encounter the character we seek.\n\n2. If the character is nowhere to be found, our coder friend simply returns the original word, untouched. No need to stir up trouble where there is none, just like how I know when to keep my powers dormant.\n\n3. However, if the character is present, the real fun begins. Our coder friend focuses their attention on the part of the word before the special character, like a skilled explorer zeroing in on the treasure they\'ve been seeking.\n\n4. Using the `reverse` function, they ingeniously rearrange the characters in this prefix, flipping them around like a magician performing a sleight of hand trick. It\'s akin to how I can sprout arms and hands from any surface, manipulating the world around me with effortless grace.\n\n5. The rest of the word remains unchanged, like a carefully guarded secret, much like how I selectively reveal my abilities to those I trust.\n\n6. And just like that, our coder friend has crafted a new word, with the prefix reversed and the rest of the word intact. It\'s like uncovering a hidden message within a larger puzzle, revealing the true nature of the word itself.\n\nDareshishishi... Let\'s see this in action with an example. Let\'s say the input `word` is "abcdefd" and the special character `ch` is "d".\n\n1. Our coder friend uses `find` to locate the first occurrence of "d" in "abcdefd". It\'s found at index 3.\n\n2. Since "d" is present, we proceed to step 3.\n\n3. Our focus is now on the prefix "abcd" before the "d".\n\n4. Using `reverse`, our coder friend flips this prefix to become "dcba".\n\n5. The rest of the word, "efd", remains unchanged.\n\n6. The resulting word, with the prefix reversed, is "dcbaefd".\n\nDareshishishi... Isn\'t it fascinating how a simple task can be approached with such cleverness and precision? Our coder friend truly understands the art of manipulation, much like how I wield my powers with careful calculation."\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n\n```C++ []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int idx = word.find(ch);\n if(idx == -1) {\n return word;\n }\n\n reverse(begin(word), begin(word) + idx + 1);\n return word;\n }\n};\n```\n```java []\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int idx = word.indexOf(ch);\n if(idx == -1) {\n return word;\n }\n\n StringBuilder res = new StringBuilder(word.substring(0, idx + 1)).reverse();\n if(idx < word.length()) {\n res.append(word.substring(idx + 1));\n }\n\n return res.toString();\n }\n}\n```\n```python []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n idx = word.find(ch)\n if idx == -1 :\n return word\n\n return word[:idx + 1][::-1] + word[idx + 1:]\n```\n```C []\nchar* reversePrefix(char* word, char ch) {\n char* first_occurrence = strchr(word, ch);\n if (first_occurrence == NULL) {\n return word;\n }\n\n int first_index = first_occurrence - word;\n for (int i = 0; i <= first_index / 2; ++i) {\n char temp = word[i];\n word[i] = word[first_index - i];\n word[first_index - i] = temp;\n }\n\n return word;\n}\n```\n```C# []\npublic class Solution {\n public string ReversePrefix(string word, char ch) {\n int idx = word.IndexOf(ch);\n if (idx == -1) {\n return word;\n }\n\n string prefix = word.Substring(0, idx + 1);\n char[] prefixChars = prefix.ToCharArray();\n Array.Reverse(prefixChars);\n string reversedPrefix = new string(prefixChars);\n return reversedPrefix + word.Substring(idx + 1);\n }\n}\n```\n```javascript []\n/**\n * @param {string} word\n * @param {character} ch\n * @return {string}\n */\nvar reversePrefix = function(word, ch) {\n const idx = word.indexOf(ch);\n if (idx === -1) {\n return word;\n }\n\n const prefix = word.substring(0, idx + 1);\n const reversedPrefix = prefix.split(\'\').reverse().join(\'\');\n return reversedPrefix + word.substring(idx + 1);\n};\n\n```\n```Dart []\nclass Solution {\n String reversePrefix(String word, String ch) {\n int idx = word.indexOf(ch);\n if (idx == -1) {\n return word;\n }\n\n String prefix = word.substring(0, idx + 1);\n String reversedPrefix = prefix.split(\'\').reversed.join(\'\');\n return reversedPrefix + word.substring(idx + 1);\n }\n}\n```\n```Go []\nfunc reversePrefix(word string, ch byte) string {\n\tidx := strings.IndexByte(word, ch)\n\tif idx == -1 {\n\t\treturn word\n\t}\n\n\tprefix := word[:idx + 1]\n\treversed := reverseString(prefix)\n\treturn reversed + word[idx + 1:]\n}\n\nfunc reverseString(s string) string {\n\trunes := []rune(s)\n\tfor i, j := 0, len(runes)-1; i < j; i, j = i + 1, j - 1 {\n\t\trunes[i], runes[j] = runes[j], runes[i]\n\t}\n\treturn string(runes)\n}\n```\n```Scala []\nobject Solution {\n def reversePrefix(word: String, ch: Char): String = {\n val idx = word.indexOf(ch)\n if (idx == -1) {\n word\n } else {\n val prefix = word.substring(0, idx + 1)\n val reversedPrefix = prefix.reverse\n reversedPrefix + word.substring(idx + 1)\n }\n }\n}\n```\n![NicoRobin.jpg](https://assets.leetcode.com/users/images/156f601a-03df-4049-82f7-6147d70a78ca_1714593480.3881311.jpeg)\n\n\n
19
0
['String', 'C', 'C++', 'Java', 'Go', 'Python3', 'Scala', 'JavaScript', 'C#', 'Dart']
3
reverse-prefix-of-word
[Python 3] One-liner | Faster than 100% (Explained!)
python-3-one-liner-faster-than-100-expla-9cr1
The idea is to slice the string upto and including ch, reverse that specific string segment, and concatenate the remaining string.\n\nExample:\n\n\nword = "abcd
TP0604
NORMAL
2021-09-12T09:26:46.584798+00:00
2021-09-24T19:40:55.170587+00:00
1,319
false
The idea is to slice the string upto and including `ch`, reverse that specific string segment, and concatenate the remaining string.\n\nExample:\n\n```\nword = "abcdefd", ch = "d"\n\n#slice the string upto and including "d"\nword[:3 + 1] = "abcd"\n\n#reverse the string\nword[:3 + 1][::-1] = "dcba"\n\n#finally, add it to the remaining string\nword[:3 + 1][::-1] + word[3 + 1:] = "dcbaefd"\n```\n\n------------------------------------------------------------------------------------------------------\nSolution:\n\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n return word[:word.index(ch) + 1][::-1] + word[word.index(ch) + 1:] if ch in word else word\n```\n\nOr even shorter using [`str.find()`](https://www.programiz.com/python-programming/methods/string/find):\n```\nreturn word[:word.find(ch) + 1][::-1] + word[word.find(ch) + 1:] \n```\n\n![image](https://assets.leetcode.com/users/images/e852ec12-bbd6-49e8-a6cf-117ac8006bc0_1631438824.3637667.png)\n\nHope this helps!
13
0
['Python', 'Python3']
4
reverse-prefix-of-word
🚀 💯 100% Beats 🔥 | | ✅both ✅green beats🧠 | | DSA solution in java
100-beats-both-green-beats-dsa-solution-dgcu4
# Intuition \n\n\n# Approach\n1. Find the index of the first occurrence of character ch in the string word.\n1. If the character ch is not found, return the o
Pintu008
NORMAL
2023-12-06T13:00:48.246551+00:00
2023-12-06T13:00:48.246570+00:00
329
false
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Find the index of the first occurrence of character ch in the string word.\n1. If the character ch is not found, return the original string.\n1. Create a StringBuilder to store the reversed segment.\n1. Iterate from index 0 to the index of the first occurrence of ch (inclusive), appending characters to the StringBuilder.\n1. Reverse the StringBuilder.\n1. Concatenate the reversed segment with the remaining part of the string after the index of the first occurrence of ch\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: **(ON))**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int ind = word.indexOf(ch);\n StringBuilder str = new StringBuilder();\n for(int i=0; i<=ind; i++){\n str.append(word.charAt(i));\n }\n str.reverse();\n String sb = word.substring(ind+1);\n return str.toString()+sb;\n \n }\n}\n```\n![WhatsApp Image 2023-12-03 at 12.33.52.jpeg](https://assets.leetcode.com/users/images/ba54f7bf-ed8e-4ea1-bd6b-b995f6507f16_1701867634.7906091.jpeg)\n
12
0
['String', 'Java']
3
reverse-prefix-of-word
💯Fastest - 0 ms || ✅Easiest Explanation || Two Pointer 🔥 || 3️⃣ Lines of code || DryRun 🏋️‍♀️
fastest-0-ms-easiest-explanation-two-poi-snby
Thanks for checking out my solution \u2764, You can view my profile here: TheCodeAlpha and check out other solutions too \uD83D\uDC4D\n\n# Approach 1 : Two Poin
TheCodeAlpha
NORMAL
2024-05-01T07:02:53.584474+00:00
2024-05-01T18:19:31.763383+00:00
668
false
#### Thanks for checking out my solution \u2764, You can view my profile here: [TheCodeAlpha](https://leetcode.com/u/TheCodeAlpha/) and check out other solutions too \uD83D\uDC4D\n\n# Approach 1 : Two Pointer\n\n# Intuition\n\n- Pehla khayaal jo mujhe aaya (Vo uska nahi tha), vo ye tha ki apne ko chahiye diye huyi character ki index.\n - \n- Iss se apan ko pata chalega ki reverse karna bhi hai ya nahi\n - \n- Ab isme bhi do tarike se kaam ho sakta hai\n - \n #### 1) Pehla toh ye ki character string mai hai hi nahi, Isme humko bas jo string di hai, usko hi return kardena hai\n #### 2) Dusra ye ki string ke paas character hai, unlike ur `EX`\n - Ab hai toh humko iss character tak ke string ke tukde ko reverse karna hoga\n - \n - Chalo maan lete hain character milgya `found` variable mai, ekdum vese hi jese tumhare crush ke variable mai koi input aaya ho :)\n - \n - Ab humare paas destination hai, question mai start ko 0 index bola hi hai, bas ab seedhe ko ulta krte hai isme, (Jese Placement ke interviews mai karta hu mai)\n - \n - Start or end ki index ko swap karte raho jab tak ki start end se chota hai\n - \n #### a) Isko krne ke liye har badlu (Swapping) operation ke baad start ko badhate jao aur end ko ghatate jao.\n #### b) start++, end--\n #### c) Bas jab `start` `end` se badha ho jaye toh loop tod ke `word` string ko return kardo\n\n### Abhi bhi koi dikkat ho toh ye DropDown mai dryrun \uD83C\uDFCB\uFE0F\u200D\u2640\uFE0F\uD83C\uDFCB\uFE0F\u200D\u2640\uFE0F hai dekhlo\n\n<details>\n\t<summary>DRYRUN</summary>\n\t<br>\n\t<strong>Let\'s dry run the code for the given word "alok" and character \'w\':\n\n Start with the given word: "alok".\n Iterate through each character of the word.\n At index 0: \'a\' does not match \'w\'.\n At index 1: \'l\' does not match \'w\'.\n At index 2: \'o\' does not match \'w\'.\n At index 3: \'k\' does not match \'w\'.\n Since none of the characters match \'w\', \n the loop completes without making any changes to the word.\n Return the original word: "alok".\n<br/>\n\t</details>\n \n<details>\n\t<summary>DRYRUN2</summary>\n\t<br>\n\t<strong>Given word: "alokiscoding"\nCharacter: \'k\'\n\n Start with the given word: "alokiscoding".\n Iterate through each character of the word.\n At index 0: \'a\' does not match \'k\'.\n At index 1: \'l\' does not match \'k\'.\n At index 2: \'o\' does not match \'k\'.\n At index 3: \'k\' matches \'k\'.\n Initialize pointer j to 0.\n while(j < i)\n Swap characters at positions j (currently 0) and i (currently 3): "kloaiscoding".\n Increment j to 1 and decrement i to 2.\n Swap characters at positions j (currently ) and i (currently 2): "kolaiscoding".\n Increment j to and decrement i to 1, Loop Terminates\n Outer loop is terminated, coz of break Statement\n\n word = "kolaiscoding" is returned\n\n<br/>\n\t</details>\n\n\n### Aur bas Hogya ye sawal bhi.... Abhi niche ek majedaar tareeka bhi bataya hai mehej 3 lines ke code se. Naya kuch nahi hai, bs jo hai uska hi istemaal kiya hai, kya pata kaam aajaye...\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n![image.png](https://assets.leetcode.com/users/images/560c535b-62d8-4b50-95ca-5391be26f240_1714546961.504763.png)\n## Ab Code kar lete hai aur apni streak ko aage badhate hain\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n // Loop through each character of the word\n for (int i = 0; i < word.size(); i++) {\n // If the current character matches the target character\n if (word[i] == ch) {\n int j = 0; // Initialize a pointer `j` to the beginning of the string\n // Reverse the prefix of the string up to the index `i`\n while (j < i)\n swap(word[j++], word[i--]);\n break; // Exit the loop once the prefix is reversed\n }\n }\n // Return the modified string\n return word;\n }\n};\n```\n```java []\nclass Solution {\n public String reversePrefix(String word, char ch) {\n // Loop through each character of the word\n // Strings are immutable in java, so we go via character array\n // For the swaapping operations\n char[] answer = word.toCharArray();\n for (int i = 0; i < word.length(); i++) {\n // If the current character matches the target character\n if (word.charAt(i) == ch) {\n int j = 0; // Initialize a pointer `j` to the beginning of the string\n // Reverse the prefix of the string up to the index `i`\n while (j < i) {\n // Swap characters at positions `j` and `i`\n swapChars(answer, j++, i--);\n }\n return new String(answer);\n }\n }\n // Return the modified string\n return word;\n }\n \n // Helper method to swap characters at positions `i` and `j` in a string\n private void swapChars(char[] answer, int index1, int index2) {\n char temp = answer[index2];\n answer[index2] = answer[index1];\n answer[index1] = temp;\n }\n}\n```\n```python []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n # Loop through each character of the word\n # Convert the string to a list of characters first\n # this is because strings are immutable in python, just like java\n Word = list(word)\n for i in range(len(word)):\n # If the current character matches the target character\n if Word[i] == ch:\n j = 0 # Initialize a pointer `j` to the beginning of the string\n # Reverse the prefix of the string up to the index `i`\n while j < i:\n # Swap characters at positions `j` and `i`\n Word[j] , Word[i] = Word[i] , Word[j]\n j += 1\n i -= 1\n break # Exit the loop once the prefix is reversed\n # Return the modified string\n return (\'\').join(Word)\n```\n____\n# Approach 1.1 Use of inbuilt functions\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n### Dekho khel abhi bhi wahi hai, bas iss baar humne hatiyaar behter istemaal kiye hain.\n### - `find()` ya `indexOf()` : ye humko seedha index dedeta hai character ki, agar vo string mai hai, varna -1, dedeta hai\n### - `reverse()` : Ye humare string ki diye huye hisse ko ulta urf reverse kar deta hai\n\n# Algorithm\n\nSabse pehle to find function se index nikalo diye huye character ki, par isme thoda matter ho sakta hai\n -\n - Agar character string mai hua tab toh theek, hum uss index tak ka ek tukda ya `substring`, lekar usse reverse karke, bache huyi string ke sath jod denge aur return kardenge\n -\n - Par agar character string mai ni hua, toh `find()` -1 return kardega, aur iss index se `c++` or `java` mai error aajata hai\n - \n - Iss case ko handle karne ke liye hume bas `reverse()` or `substring()` ki property ka istemaal krna hai\n - \n - humko ye toh pta hi hai ki `reverse(start, end)`, `start` se `end - 1` tak ke hisse mai kaam krta hai, toh `end` ko access krne ke liye humko bas `end ko end + 1` likhna hai.\n - Aur yahi kaam humko `substring` mai bhi krna hai\n - Ye question mai diya hi hai ki reverse krna hai shuru se, toh `start` 0 hai humara, aur endpoint `found`\n - Ab agar `found` = `-1`, toh `endpoint + 1 = -1 + 1 = 0`, and 0 index se hum normally nipat sakte hain\n - Bas ab iss jugad se humko koi index error nahi aayega\n\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n![image.png](https://assets.leetcode.com/users/images/f32cd743-2bd6-4d64-abf2-f4130025c7e9_1714543893.2540286.png)\n\n# Code\n```cpp []\nclass Solution\n{\npublic:\n string reversePrefix(string word, char ch)\n {\n // Get the index of the given character\n // `find()` returns the index of the character if found, else -1\n int found = word.find(ch);\n\n // Now reverse the segment of the string starting from the beginning to the index of the character (if found)\n // If `found` variable has -1, then `found + 1 = 0`, \n // And `reverse()` from [0, 0) will therefore reverse an empty string\n reverse(word.begin(), word.begin() + found + 1);\n\n // Once all is said and done, return the modified `word` string\n return word;\n }\n};\n```\n```java []\nclass Solution {\n public String reversePrefix(String word, char ch) \n {\n // Get the index of the given character in the word\n // `indexOf()` returns the index of the character if found, else -1\n int found = word.indexOf(ch);\n // String are immutable in Java, and hence we will create a new string using the StringBuilder\n // Reverse the segment of the string starting from the beginning to the index of the character\n // If `found` variable is -1, then `found + 1 = 0`, and \n // `substring(0, 0)` will result in an empty substring, \n // Therefore `reverse()` will reverse an empty string\n \n // Else we will reverse the substring from the starting to the index of the given character, i.e. `found`\n word = new StringBuilder(word.substring(0, found + 1)).reverse() + word.substring(found + 1);\n\n // Return the modified `word` string\n return word;\n }\n}\n```\n```python []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n # Get the index of the given character in the word\n # `find()` returns the index of the character if found, else -1\n found = word.find(ch)\n # [:found + 1] slices the string from [0 to `found`]\n # [found + 1:] slices the string from [`found + 1` to end of the string]\n # The [::-1] notation is a Python idiom for reversing a string.\n # Reverse the segment of the string starting from the beginning to the index of the character\n # If `found` variable is -1, then `found + 1 = 0`, and `word[:0]` won\'t reverse anything, as it will be an empty string\n word = word[:found + 1][::-1] + word[found + 1:]\n\n # Return the modified `word` string\n return word\n\n```\n____\n![upvote.png](https://assets.leetcode.com/users/images/f68d1a41-b639-485d-9155-dc417c1a42d4_1714544537.1242034.png)\n
11
1
['Two Pointers', 'String', 'C++', 'Java', 'Python3']
1
reverse-prefix-of-word
C++ 2-line solution (O(N) time & O(1) space)
c-2-line-solution-on-time-o1-space-by-mi-u6ak
\nclass Solution {\npublic:\n string reversePrefix(string& word, const char& ch) {\n reverse(word.begin(), word.begin() + word.find(ch) + 1);\n
minato_yukina
NORMAL
2021-09-12T05:35:51.041093+00:00
2021-09-12T05:35:51.041134+00:00
939
false
```\nclass Solution {\npublic:\n string reversePrefix(string& word, const char& ch) {\n reverse(word.begin(), word.begin() + word.find(ch) + 1);\n return word;\n }\n};\n```
11
0
[]
3
reverse-prefix-of-word
✅Detailed Explaination||Step-by-Step Explanation✅Python🐍Java🍵C+
detailed-explainationstep-by-step-explan-damm
\n\n# Code\n# C++\n\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n string ans;\n\n // Find the index of the charac
sujalgupta09
NORMAL
2024-05-01T04:22:41.705943+00:00
2024-05-01T04:22:41.705979+00:00
2,202
false
\n\n# Code\n# C++\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n string ans;\n\n // Find the index of the character \'ch\' in the word\n int ind = 0;\n for(int i = 0; i < word.length(); i++){\n if(word[i] == ch){\n ind = i;\n break;\n }\n }\n\n // Push characters onto a stack until the index \'ind\'\n stack<char> st;\n for(int i = 0; i <= ind; i++) st.push(word[i]);\n\n // Pop characters from the stack to reverse the prefix\n while(!st.empty()){\n ans += st.top();\n st.pop();\n }\n\n // Append the remaining characters after \'ch\'\n for(int i = ind+1; i < word.length(); i++) ans += word[i];\n\n return ans;\n }\n}; \n\n```\n\n\n# Python\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n # Find the index of the character \'ch\' in the word\n ind = word.find(ch)\n if ind == -1:\n return word # If character not found, return the original word\n \n # Reverse the prefix up to the index \'ind\'\n prefix = word[:ind+1][::-1]\n \n # Append the remaining characters after \'ch\'\n ans = prefix + word[ind+1:]\n \n return ans\n\n```\n# JAVA\n```\nimport java.util.Stack;\n\nclass Solution {\n public String reversePrefix(String word, char ch) {\n StringBuilder ans = new StringBuilder();\n\n // Find the index of the character \'ch\' in the word\n int ind = 0;\n for (int i = 0; i < word.length(); i++) {\n if (word.charAt(i) == ch) {\n ind = i;\n break;\n }\n }\n\n // Push characters onto a stack until the index \'ind\'\n Stack<Character> st = new Stack<>();\n for (int i = 0; i <= ind; i++) {\n st.push(word.charAt(i));\n }\n\n // Pop characters from the stack to reverse the prefix\n while (!st.isEmpty()) {\n ans.append(st.pop());\n }\n\n // Append the remaining characters after \'ch\'\n for (int i = ind + 1; i < word.length(); i++) {\n ans.append(word.charAt(i));\n }\n\n return ans.toString();\n }\n}\n\n```
10
0
['C++']
2
reverse-prefix-of-word
🗓️ Daily LeetCoding Challenge Day 133|| 🔥 JAVA SOL
daily-leetcoding-challenge-day-133-java-emch3
Code\n\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int j = word.indexOf(ch);\n if (j != -1) {\n return
DoaaOsamaK
NORMAL
2024-05-01T03:37:45.989920+00:00
2024-05-01T03:37:45.989960+00:00
1,303
false
# Code\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int j = word.indexOf(ch);\n if (j != -1) {\n return new StringBuilder(word.substring(0, j + 1)).reverse().toString() + word.substring(j + 1);\n }\n return word;\n }\n}\n```
10
0
['Java']
3
reverse-prefix-of-word
Ruby Solution | like plx
ruby-solution-like-plx-by-bornfundeath-cle9
\n# Code\n\n# @param {String} word\n# @param {Character} ch\n# @return {String}\ndef reverse_prefix(word, ch)\n dest_index = word.index(ch).to_i + ch.length\
bornfundeath
NORMAL
2023-11-19T05:25:14.482188+00:00
2023-11-19T05:25:14.482211+00:00
197
false
\n# Code\n```\n# @param {String} word\n# @param {Character} ch\n# @return {String}\ndef reverse_prefix(word, ch)\n dest_index = word.index(ch).to_i + ch.length\n reverse_word = word[0...dest_index].reverse\n new_word = word[dest_index...word.length]\n return reverse_word + new_word\nend\n```
10
1
['Ruby']
1
reverse-prefix-of-word
Two Solutions. Two Pointers( 93%/97% )
two-solutions-two-pointers-9397-by-kubat-2xcu
\n/**\n * @param {string} word\n * @param {character} ch\n * @return {string}\n */\nvar reversePrefix = function(word, ch) {\n // #1\n let chIndex = word.
kubatabdrakhmanov
NORMAL
2022-10-30T11:43:47.559081+00:00
2022-10-30T11:43:47.559115+00:00
1,466
false
```\n/**\n * @param {string} word\n * @param {character} ch\n * @return {string}\n */\nvar reversePrefix = function(word, ch) {\n // #1\n let chIndex = word.indexOf(ch)\n if(chIndex < 0) return word\n \n let result = \'\'\n \n for(let i = chIndex; i >= 0; i--){\n result += word[i]\n }\n \n for(let j = chIndex+1; j < word.length; j++){\n result += word[j]\n }\n \n return result\n \n \n // #2\n let chIndex = word.indexOf(ch)\n if(chIndex < 0 || word === ch) return word\n \n let left = chIndex, right = chIndex+1, result = \'\'\n while(right <= word.length){\n if(left >= 0){\n result += word[left--]\n }else if(!word[right]){\n return result\n }else{\n result += word[right++]\n }\n }\n return result\n};\n```
10
0
['JavaScript']
3
reverse-prefix-of-word
🔥 6 lines of simple code beat 100% users 🚀 fully explained ✅ || Easy to understand 👍
6-lines-of-simple-code-beat-100-users-fu-ndnl
Intuition\nPython, Python3 and C++ :\n1. Iterate through the characters of the string \'word\' until you find the first occurrence of the specified character \'
siddharth-kiet
NORMAL
2024-05-01T07:04:52.560799+00:00
2024-05-01T07:05:06.279420+00:00
1,652
false
# Intuition\n**Python, Python3 and C++ :**\n1. Iterate through the characters of the string **\'word\'** until you find the first occurrence of the specified character **\'ch\'**.\n2. Once found, store the index of the occurrence in **\'c\'**.\n3. Extract the substring from the beginning of the **\'word\'** string up to the index of the found character (inclusive) add it to **\'st\'**.\n4. Reverse the substring **\'st\'**.\n5. Concatenate the reversed substring **\'st\'** with the rest of the **\'word\'** string after the found character.\n6. Return the **\'st\'** string.\n\n**I hope you understand the code \uD83D\uDE4F and if you have any query let me know in the comment.**\n\n# Approach : StraightForward \n\n# Complexity\n- Time complexity: O(n)\n![Screenshot (16).png](https://assets.leetcode.com/users/images/cafe1a0d-a833-4b6e-b620-598a3c51cfa3_1714547036.8860185.png)\n- Space complexity: O(n)\n\n# Code\n```Python3 []\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n c=0\n for i in range(len(word)):\n if word[i]==ch: \n c=i \n break\n st=word[0:c+1][::-1]+word[c+1:]\n return st\n \n```\n```Python []\nclass Solution(object):\n def reversePrefix(self, word, ch):\n """\n :type word: str\n :type ch: str\n :rtype: str\n """\n c=0\n for i in range(len(word)):\n if word[i]==ch: \n c=i \n break\n st=word[0:c+1][::-1]+word[c+1:]\n return st\n```\n```C++ []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int c=0;\n for(int i=0;i<word.length();i++){\n if(word[i]==ch){\n c=i;\n break;\n }\n }\n string st=word.substr(0,c+1);\n reverse(st.begin(),st.end());\n st=st+word.substr(c+1,word.length());\n return st;\n }\n};\n```\n
9
0
['String', 'Python', 'C++', 'Python3']
2
reverse-prefix-of-word
Python 3 || 3 lines, index and string slices || T/S: 91% / 99%
python-3-3-lines-index-and-string-slices-4ti0
\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n \n if ch not in word: return word\n\n idx = word.index(ch)\n
Spaulding_
NORMAL
2024-05-01T00:46:47.789834+00:00
2024-06-11T21:34:55.626215+00:00
501
false
```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n \n if ch not in word: return word\n\n idx = word.index(ch)\n return word[:idx+1][::-1]+ word[idx+1:]\n```\n[https://leetcode.com/problems/reverse-prefix-of-word/submissions/607834040/](https://leetcode.com/problems/reverse-prefix-of-word/submissions/607834040/)\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(word)`.
9
0
['Python3']
2
reverse-prefix-of-word
two methods || python || easy to understand
two-methods-python-easy-to-understand-by-b9lt
\n\n# Code\n\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n """\n #method 1:\n for i in range(len(word)):\n
Kairanishanth
NORMAL
2022-12-15T16:38:17.992719+00:00
2022-12-15T16:38:17.992757+00:00
946
false
\n\n# Code\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n """\n #method 1:\n for i in range(len(word)):\n if word[i]==ch:\n return word[:i+1][::-1]+word[i+1:]\n return word"""\n #method 2:\n l=0\n r=word.find(ch)\n word=list(word)\n while l<r:\n word[l],word[r]=word[r],word[l]\n l+=1\n r-=1\n return "".join(word)\n \n\n \n\n\n \n\n \n```
9
0
['Python3']
2
reverse-prefix-of-word
[JAVA] | indexOf() | O(N) Time | 100% Optimal & Faster Solution
java-indexof-on-time-100-optimal-faster-q6e5z
\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int index=word.indexOf(ch);\n if(index!=-1)\n return reverse(
kanojiyakaran
NORMAL
2021-09-15T16:06:49.770274+00:00
2021-09-15T16:06:49.770321+00:00
1,259
false
```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int index=word.indexOf(ch);\n if(index!=-1)\n return reverse(index,index+1,word); \n else \n return word;\n }\n \n public String reverse(int i,int j,String word){\n StringBuilder sb=new StringBuilder();\n while(i>=0){\n sb.append(word.charAt(i--));\n }\n while(j<word.length())\n sb.append(word.charAt(j++));\n \n return sb.toString();\n }\n}\n```
9
0
['Java']
3
reverse-prefix-of-word
C++ || 3 Liner Solution || Easy-to-understand
c-3-liner-solution-easy-to-understand-by-2xcb
class Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int pos=word.find(ch);\n reverse(word.begin(),word.begin()+pos+1);\n
venom-xd
NORMAL
2022-03-02T13:23:09.697192+00:00
2022-03-02T13:23:09.697236+00:00
524
false
class Solution {\npublic:\n string reversePrefix(string word, char ch) {\n int pos=word.find(ch);\n reverse(word.begin(),word.begin()+pos+1);\n return word;\n }\n};\n
8
1
['String', 'C']
1
reverse-prefix-of-word
Java 100% fast,Easy
java-100-fasteasy-by-aniketalok863-37w6
```\n public String reversePrefix(String word, char ch) {\n StringBuilder sb=new StringBuilder();\n int index=word.indexOf(ch);\n sb.append
aniketalok863
NORMAL
2021-10-02T05:31:35.265731+00:00
2021-10-02T05:31:35.265763+00:00
794
false
```\n public String reversePrefix(String word, char ch) {\n StringBuilder sb=new StringBuilder();\n int index=word.indexOf(ch);\n sb.append(word.substring(0,index+1));\n sb.reverse();\n sb.append(word.substring(index+1));\n return sb.toString();\n \n }
8
1
['Java']
2
reverse-prefix-of-word
🔥 100% Faster | Reverse Prefix Using Stack | Optimized C++ Solution 🚀
100-faster-reverse-prefix-using-stack-op-8pt2
IntuitionUse a stack to store characters up to the first occurrence of ch, then pop from the stack to reverse the prefix in place.Approach Find the first occurr
FarhanTalkal
NORMAL
2025-03-02T14:48:28.278519+00:00
2025-03-02T14:48:28.278519+00:00
301
false
# Intuition Use a stack to store characters up to the first occurrence of ch, then pop from the stack to reverse the prefix in place. # Approach 1. **Find the first occurrence of `ch`** in `word` while pushing characters onto a stack. 2. If `ch` is not found, return `word` as is. 3. **Pop characters from the stack** to overwrite the prefix in `word`, effectively reversing it. 4. The rest of `word` remains unchanged. 5. **Time Complexity:** `O(N)`, **Space Complexity:** `O(K)` (at most `O(N)`). 6. **Efficient in-place modification** using a stack ensures optimal performance. 🚀 # Complexity - Time complexity: The time complexity is O(N) because we traverse the string once to find ch (O(N)) and then modify only a prefix of length K (O(K) ≤ O(N)). Since both operations are linear, the overall complexity remains O(N). 🚀 - Space complexity: The space complexity is O(K) because the stack stores at most K characters (up to the first occurrence of ch). In the worst case (ch at the end or not present), it becomes O(N), but typically, it's much smaller. ✅ # Code ```cpp [] class Solution { public: string reversePrefix(string word, char ch) { stack<char> stk; int index = -1; for (int i = 0; i < word.length(); i++) { stk.push(word[i]); if (word[i] == ch) { index = i; break; } } if (index == -1) return word; for (int i = 0; i <= index; i++) { word[i] = stk.top(); stk.pop(); } return word; } }; ```
7
0
['String', 'Stack', 'C++']
0
reverse-prefix-of-word
Easy Python Solution (28ms) | Faster than 93%
easy-python-solution-28ms-faster-than-93-2xgz
Easy Python Solution (28ms) | Faster than 93%\nRuntime: 28 ms, faster than 93% of Python3 online submissions for Reverse Prefix of Word.\nMemory Usage: 14.3 MB\
the_sky_high
NORMAL
2021-09-19T10:17:39.961987+00:00
2021-09-19T10:18:40.538842+00:00
1,281
false
# Easy Python Solution (28ms) | Faster than 93%\n**Runtime: 28 ms, faster than 93% of Python3 online submissions for Reverse Prefix of Word.\nMemory Usage: 14.3 MB**\n\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n try:\n ix = word.index(ch)\n return word[:ix+1][::-1] + word[ix+1:]\n except ValueError:\n return word\n```
7
1
['String', 'Python', 'Python3']
3
reverse-prefix-of-word
Simple Golang Solution
simple-golang-solution-by-nathannaveen-nx4w
The idea of this solution is:\n\n We reverse the first i letters of word and store it as s.\n Then when word[i] (letter) equals ch we can return s + word[i + 1:
nathannaveen
NORMAL
2021-09-13T15:42:40.311510+00:00
2021-09-19T13:12:29.238912+00:00
216
false
The idea of this solution is:\n\n* We reverse the first `i` letters of `word` and store it as `s`.\n* Then when `word[i]` (`letter`) equals `ch` we can return `s + word[i + 1:]` (The reversed string up to`i`, and then the remaining of `word`)\n\n```\nfunc reversePrefix(word string, ch byte) string {\n s := ""\n \n for i, letter := range word {\n s = string(letter) + s\n \n if letter == rune(ch) {\n return s + word[i + 1 :]\n }\n }\n \n return word\n}\n```
7
0
['Go']
1
reverse-prefix-of-word
Easy to Understand Solution || C++ || Reverse
easy-to-understand-solution-c-reverse-by-j088
Idea is simple, find the position of ch in word. If not found return -1. \n\nOtherwise, reverse the word starting from beginning of word till position of ch+1.
i_quasar
NORMAL
2021-09-12T04:03:35.243919+00:00
2021-09-12T04:10:26.712030+00:00
551
false
**Idea** is simple, find the position of `ch` in word. If not found return -1. \n\nOtherwise, reverse the word starting from beginning of word till position of ch+1. \n\n\t\treverse(word.begin(), word.begin() + pos + 1);\n\n# Code : \n```\n string reversePrefix(string word, char ch) {\n \n\tint pos = -1;\n\tfor(int i=0; i<word.size(); i++)\n\t{\n\t\tif(word[i] == ch) \n\t\t{\n\t\t\tpos = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(pos == -1) return word;\n\n\treverse(word.begin(), word.begin() + pos + 1);\n\treturn word;\n}\n```\n\n**Time : O(n)** -> search character O(n), reverse string O(n) worst case\n**Space : O(1)**\n\n***If you find the solution helpful, do give it a like :)***\n
7
0
['String', 'C']
0
reverse-prefix-of-word
EASY JAVA SOLUTION for BEGINNERS [1ms]
easy-java-solution-for-beginners-1ms-by-8689d
Approach\n1. Initialize Variables:\n - Create int ind to store the index of ch.\n - Initialize StringBuilder str for the resulting string.\n\n2. Find the In
RajarshiMitra
NORMAL
2024-05-26T06:58:21.780641+00:00
2024-06-16T06:46:33.652885+00:00
74
false
# Approach\n1. **Initialize Variables**:\n - Create `int ind` to store the index of `ch`.\n - Initialize `StringBuilder str` for the resulting string.\n\n2. **Find the Index of `ch`**:\n - Iterate through `word` to find the first occurrence of `ch`.\n - Store the index in `ind` and break the loop.\n\n3. **Reverse the Prefix**:\n - Use a `while` loop to append characters from `ind` to `0` in reverse order to `str`.\n\n4. **Append the Remaining Part**:\n - Use another `while` loop to append characters from `ind + 1` to the end of `word` to `str`.\n\n5. **Return the Result**:\n - Convert `str` to a string and return it.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int ind=0;\n StringBuilder str=new StringBuilder();\n for(int i=0; i<word.length(); i++){\n if(word.charAt(i) == ch){\n ind=i;\n break;\n }\n }\n int st=0, lt=ind;\n while(lt>=0){\n str.append(word.charAt(lt));\n lt--;\n }\n ind++;\n while(ind < word.length()){\n str.append(word.charAt(ind));\n ind++;\n }\n return str.toString();\n }\n}\n```\n\n![193730892e8675ebafc11519f6174bee5c4a5ab0.jpeg](https://assets.leetcode.com/users/images/bdab8c02-9cad-4ae3-aed2-96cbe4945289_1718520387.8909087.jpeg)\n
6
0
['Java']
0
reverse-prefix-of-word
C++ and C# very easy solution.
c-and-c-very-easy-solution-by-aloneguy-co71
\n\n\nC# []\npublic class Solution {\n public string ReversePrefix(string word, char ch) {\n char[] a = word.ToCharArray();\n for(int i = 0; i <
aloneguy
NORMAL
2023-04-12T01:22:26.370610+00:00
2023-04-12T01:22:26.370650+00:00
1,203
false
![photo_2023-04-12_06-18-51.jpg](https://assets.leetcode.com/users/images/d3ff2165-eb77-4885-aa3c-e79ea547b81d_1681262479.6319585.jpeg)\n![photo_2023-04-12_06-18-58.jpg](https://assets.leetcode.com/users/images/9bc4f308-2ec0-4a2c-be01-93435ec2eb52_1681262485.2153604.jpeg)\n\n```C# []\npublic class Solution {\n public string ReversePrefix(string word, char ch) {\n char[] a = word.ToCharArray();\n for(int i = 0; i < a.Length; ++ i) {\n if(a[i] == ch) {\n for(int j = 0; j <= i / 2; ++ j) {\n char temp = a[j];\n a[j] = a[i - j];\n a[i - j] = temp;\n }\n return new string(a);\n }\n }\n\n return word;\n}\n}\n```\n```C# []\npublic class Solution {\n public string ReversePrefix(string word, char ch) {\n StringBuilder s=new();\n if(word.Contains(ch)){\n int index=word.IndexOf(ch);\n for(int i=index;i>=0;i--)\n s.Append(word[i]);\n s.Append(word.Substring(index+1));\n }\n else\n return word;\n return s.ToString();\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n string s1;\n int index=word.find(ch);\n if(index!=string::npos){\n for(int i=index;i>=0;i--)\n s1+=word[i];\n s1+=word.substr(index+1);\n return s1;\n }\n else\n return word;\n }\n};\n```\n\n# Code:If you like it,please upvote me.\n
6
0
['String', 'C++', 'C#']
3
reverse-prefix-of-word
Simple Javascript solution with 87% faster
simple-javascript-solution-with-87-faste-bwjh
Runtime: 64 ms, faster than 87.29% of JavaScript online submissions for Reverse Prefix of Word.\n\nconst reversePrefix = (word, ch) => {\n const indexCh = word
khoabt94
NORMAL
2022-07-14T08:31:42.493415+00:00
2022-07-14T08:31:42.493449+00:00
571
false
Runtime: 64 ms, faster than 87.29% of JavaScript online submissions for Reverse Prefix of Word.\n\nconst reversePrefix = (word, ch) => {\n const indexCh = word.indexOf(ch);\n if (indexCh === -1) return word;\n\n const sliceString = word\n .slice(0, indexCh + 1)\n .split("")\n .reverse()\n .join("");\n\n return sliceString + word.slice(indexCh + 1);\n};\n\n
6
0
['JavaScript']
1
reverse-prefix-of-word
💯JAVA Solution Explained in HINDI
java-solution-explained-in-hindi-by-the_-ptgu
https://youtu.be/TpdXeHsMmLk\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote
The_elite
NORMAL
2024-05-01T13:55:01.561638+00:00
2024-05-01T13:55:01.561673+00:00
345
false
https://youtu.be/TpdXeHsMmLk\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote the solution if you liked it.\n\n# Subscribe:- [ReelCoding](https://www.youtube.com/@reelcoding?sub_confirmation=1)\n\nSubscribe Goal:- 400\nCurrent Subscriber:- 348\n# Complexity\n- Time complexity: O(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```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n \n char ans[] = word.toCharArray();\n int left = 0;\n\n for(int right = 0; right < word.length(); right++) {\n\n if(ans[right] == ch) {\n while(left <= right) {\n swap(ans, left, right);\n left++;\n right--;\n }\n return new String(ans);\n }\n }\n return word;\n }\n\n private void swap(char chars[], int idx1, int idx2) {\n char temp = chars[idx2];\n chars[idx2] = chars[idx1];\n chars[idx1] = temp;\n }\n}\n```
5
0
['Java']
1
reverse-prefix-of-word
✅ One Line Solution
one-line-solution-by-mikposp-viqw
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: O(n). Space complexi
MikPosp
NORMAL
2024-05-01T08:08:42.198889+00:00
2024-05-01T08:08:42.198912+00:00
451
false
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def reversePrefix(self, w: str, c: str) -> str:\n return w[:(q:=w.find(c)+1)][::-1]+w[q:]\n```\n\n# Code #2\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def reversePrefix(self, w: str, c: str) -> str:\n return (w[(q:=w.find(c))::-1]+w[q+1:],w)[q<0]\n```\n\n# Code #3\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def reversePrefix(self, w: str, c: str) -> str:\n return (p:=w.partition(c))[1] and c+p[0][::-1]+p[2] or w\n```\n\n(Disclaimer 2: all code above is just a product of fantasy, it is not claimed to be pure impeccable oneliners - please, remind about drawbacks only if you know how to make it better. PEP 8 is violated intentionally)
5
1
['String', 'Python', 'Python3']
1
reverse-prefix-of-word
✅Easy✨||C++|| Beats 100% || With Explanation ||
easyc-beats-100-with-explanation-by-olak-ry59
Intuition\n Describe your first thoughts on how to solve this problem. \nAll we need to do is to find the position of the first occurence of the target char.\nT
olakade33
NORMAL
2024-05-01T05:52:04.542532+00:00
2024-05-01T05:52:04.542555+00:00
1,433
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAll we need to do is to find the position of the first occurence of the target char.\nThen we need to reverse this part of the string.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. In the given string, find the given character which can be obtained by the built-in find method.\n2. Then we can use the reverse built-in method, to reverse a subset of the given word, by identifing the first position, which is 0 in our case, and the last index which is the position of the character + 1, because it is excluded.\n3. Return the word after the modification\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)$$ -->\nno extra space is needed.\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n auto firstOcc = word.find(ch); \n reverse(word.begin(), word.begin() + firstOcc + 1); \n return word; \n }\n};\n```
5
0
['C++']
2
reverse-prefix-of-word
✅ 🔥Java | Short solution | Easy understanding ✅ 🔥
java-short-solution-easy-understanding-b-59up
Given constraints are simple, so better to keep the answer as well simple in 3 lines.\n\n\t\t Find the index of the given char\n\t\t Reverse till that index\n\t
Surendaar
NORMAL
2024-05-01T03:15:25.843081+00:00
2024-05-01T03:25:06.606038+00:00
1,095
false
Given constraints are simple, so better to keep the answer as well simple in 3 lines.\n\n\t\t* Find the index of the given char\n\t\t* Reverse till that index\n\t\t* Return the substring of reversed charecter and the remaining char in original string.\n\n```\n public String reversePrefix(String word, char ch) {\n int idx = word.indexOf(ch)+1;\n\t\tStringBuffer rev = new StringBuffer(word.substring(0, idx));\n\t\treturn rev.reverse()+word.substring(idx);\n }
5
0
['Java']
2
reverse-prefix-of-word
✅ Beats 100% | 3 lines only ⚡| built_in methods are usefull 😉
beats-100-3-lines-only-built_in-methods-xjejl
\n# Intuition\n Describe your first thoughts on how to solve this problem. \n All we need to do is to find the position of the first occurence of the target cha
abdelazizSalah
NORMAL
2024-05-01T00:16:21.151853+00:00
2024-05-01T00:19:54.099595+00:00
1,238
false
![image.png](https://assets.leetcode.com/users/images/b8ba9dcd-4f45-43b9-95c3-71adfb3ebb4b_1714522569.5664985.png)\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* All we need to do is to find the position of the first occurence of the target char. \n* Then we need to reverse this part of the string.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. in the given string, find the given character which can be obtained by the built-in find method.\n2. then we can use the reverse built-in method, to reverse a subset of the given word, by identifing the first position, which is 0 in our case, and the last index which is the position of the character + 1, because it is excluded.\n3. return the word after the modification\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1. O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. no extra space is needed.\n# Code\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n auto firstOcc = word.find(ch); \n reverse(word.begin(), word.begin() + firstOcc + 1); \n return word; \n }\n};\n```
5
1
['Two Pointers', 'String', 'C++']
2
reverse-prefix-of-word
Java | Faster than 100% Solution
java-faster-than-100-solution-by-nknidhi-kudf
Do vote up if you like it :)\n\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int len = word.length();\n for(int i =
nknidhi321
NORMAL
2021-10-02T20:42:57.684611+00:00
2021-10-02T20:42:57.684643+00:00
488
false
**Do vote up if you like it :)**\n```\nclass Solution {\n public String reversePrefix(String word, char ch) {\n int len = word.length();\n for(int i = 0; i < len; i++) {\n if(word.charAt(i) == ch) {\n String reversedString = reverse(word.substring(0, i+1));\n return reversedString + word.substring(i + 1);\n }\n }\n return word;\n }\n \n public static String reverse(String s){\n int left = 0, right = s.length() - 1;\n char[] letters = s.toCharArray();\n while(left < right) {\n char temp = letters[left];\n letters[left++] = letters[right];\n letters[right--] = temp;\n }\n return String.valueOf(letters);\n }\n}\n```
5
0
[]
2
reverse-prefix-of-word
C++ Easy Solution
c-easy-solution-by-parth_chovatiya-i6pw
Just find the first occurence and reverse string till that occurence.\n\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n st
parth_chovatiya
NORMAL
2021-09-12T04:11:45.553887+00:00
2021-09-13T05:28:38.933250+00:00
375
false
Just find the first occurence and reverse string till that occurence.\n```\nclass Solution {\npublic:\n string reversePrefix(string word, char ch) {\n string ans = "";\n int tr = true;\n for(auto w : word){\n ans.push_back(w);\n if(tr && w == ch){\n tr=false;\n reverse(ans.begin(), ans.end());\n }\n }\n return ans;\n }\n};\n```
5
0
['C']
2
reverse-prefix-of-word
Java One Liner
java-one-liner-by-vikrant_pc-uinx
\npublic String reversePrefix(String word, char ch) {\n\treturn new StringBuilder(word.substring(0, word.indexOf(ch) + 1)).reverse().toString() + word.substring
vikrant_pc
NORMAL
2021-09-12T04:03:21.609107+00:00
2021-09-12T04:03:21.609150+00:00
408
false
```\npublic String reversePrefix(String word, char ch) {\n\treturn new StringBuilder(word.substring(0, word.indexOf(ch) + 1)).reverse().toString() + word.substring(word.indexOf(ch) + 1);\n}\n```
5
3
[]
1
reverse-prefix-of-word
Beats 100.00% of users with Java🎉 || 0 MS || ⏩Fastest || Simple
beats-10000-of-users-with-java-0-ms-fast-nzg3
Code
yogaasri_t
NORMAL
2025-02-16T08:46:04.460538+00:00
2025-02-16T08:46:04.460538+00:00
413
false
# Code ```java [] class Solution { public String reversePrefix(String word, char ch) { int index = word.indexOf(ch); return index >= 0 ? new StringBuilder(word.substring(0,index+1)) .reverse() .append(word.substring(index+1,word.length())) .toString() : word; } }
4
0
['String', 'Java']
2