title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
707 values
level
stringclasses
3 values
question_hints
stringlengths
19
3.98k
view_count
int64
8
630k
vote_count
int64
5
10.4k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
31,485
83
My idea is pretty simple. Just build a map for the words and their relative count in L. Then we traverse through S to check whether there is a match.\n\n public static List<Integer> findSubstring(String S, String[] L) {\n List<Integer> res = new ArrayList<Integer>();\n if (S == null || L == null || L.length == 0) return res;\n int len = L[0].length(); // length of each word\n \n Map<String, Integer> map = new HashMap<String, Integer>(); // map for L\n for (String w : L) map.put(w, map.containsKey(w) ? map.get(w) + 1 : 1);\n \n for (int i = 0; i <= S.length() - len * L.length; i++) {\n Map<String, Integer> copy = new HashMap<String, Integer>(map);\n for (int j = 0; j < L.length; j++) { // checkc if match\n String str = S.substring(i + j*len, i + j*len + len); // next word\n if (copy.containsKey(str)) { // is in remaining words\n int count = copy.get(str);\n if (count == 1) copy.remove(str);\n else copy.put(str, count - 1);\n if (copy.isEmpty()) { // matches\n res.add(i);\n break;\n }\n } else break; // not in L\n }\n }\n return res;\n }\n\nAt first I was gonna to use a set for words. Owing to the fact that duplicate is allowed in L, we need to use map instead.
2,872
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
729
9
**Please UPVOTE if you LIKE!!**\n***Watch this video for the better explanation of the code.*\nAlso you can SUBSCRIBE \uD83E\uDC83 this channel for the daily leetcode challange solution.**\n\n\n \u2B05\u2B05 **Telegram link** to discuss leetcode daily questions and other dsa problems\n\n\n**C++**\n```\nclass Solution {\npublic:\n vector<int> findSubstring(string s, vector<string>& words) {\n int wordsquan= words.size();\n int wordsleng= words[0].size();\n int target= wordsquan * wordsleng;\n unordered_map<string, int> unmap;\n \n for(int j=0; j< wordsquan; j++)\n {\n unmap[words[j]]++; \n }\n vector<int > ans;\n if(s.size()<target)\n {\n return ans;\n }\n for(int i=0; i<=s.size()-target; i++)\n {\n unordered_map<string, int> unmap2;\n unmap2= unmap; \n int k;\n for( k=0; k< wordsquan; k++)\n {\n string s1= s.substr(i+k*wordsleng, wordsleng);\n if(unmap2.count(s1)==0)\n break;\n else if(unmap2[s1]!=0)\n unmap2[s1]--;\n else\n break; \n }\n \n if(k==wordsquan)\n {\n ans.push_back(i);\n }\n \n \n }\n return ans;\n }\n};\n```\n**JAVA**(Copied)\n```\nclass Solution \n{\n public List<Integer> findSubstring(String s, String[] words) \n {\n if(words[0].length()*words.length>s.length())\n return new ArrayList<>();\n \n Map<String,Integer> word_frq=new HashMap<>();\n List<Integer> ans=new ArrayList<>();\n \n // Map store the frequency of every word in words[]\n \n for(String str:words)\n word_frq.put(str,word_frq.getOrDefault(str,0)+1);\n \n int wordlen=words[0].length(); \n \n String[] str=new String[s.length()];\n \n for(int i=0;i<wordlen;i++)\n {\n Map<String,Integer> frq=new HashMap<>(); // count frequency of words inside the window\n \n int begin=i,size=0; // size is the no. of window and begin is the starting index of window\n \n // s.length()-wordlen -> based on observation\n \n for(int j=i;j<=s.length()-wordlen;j+=wordlen)\n {\n str[j]=s.substring(j,j+wordlen); // window\n if(word_frq.containsKey(str[j]))\n {\n begin= begin==-1? j:begin; // begin=-1 means new window need to be started\n frq.put(str[j],frq.getOrDefault(str[j],0)+1); \n size++; \n \n if(size==words.length) // substring may be possible\n {\n if(frq.equals(word_frq))\n ans.add(begin);\n \n // sliding the window \n \n frq.put(str[begin],frq.get(str[begin])-1); \n begin+=wordlen; // new starting index\n size--;\n }\n }\n else // reset window\n {\n begin=-1;\n size=0;\n frq.clear();\n }\n }\n }\n return ans;\n }\n}\n```\n**PYTHON**((Copied)\n```\n res = []\n WordLen = [len(s) for s in words]\n WordIni = [ s[0] for s in words]\n TotWordLen = sum(WordLen)\n LongestWordLen = max(WordLen)\n \n d = {}\n for i in range(len(words)):\n if words[i] not in d:\n d[words[i]] = [i]\n else:\n d[words[i]].append(i) \n \n \n def isCCT(string):\n \n copy_d = copy.deepcopy(d)\n temp = \'\'\n #print(\'isCCT:\',string,copy_d)\n \n for c in string:\n temp += c\n if temp in copy_d:\n \n if len(copy_d[temp]) > 1:\n copy_d[temp].pop()\n else:\n del copy_d[temp]\n temp = \'\'\n elif len(temp) >= LongestWordLen:\n #print(\'isCCT:\',string, temp, \'zero patience\')\n return False\n \n #print(\'isCCT:\',string, temp) \n if temp == \'\' and len(copy_d) == 0:\n return True\n else:\n return False\n \n \n for i in range(len(s)):\n if s[i] in WordIni:\n if (i + TotWordLen - 1) <= len(s): \n testSubStr = s[i:i + TotWordLen]\n #print(i,testSubStr)\n if isCCT(testSubStr) == True:\n res.append(i)\n \n return res\n```**Please Don\'t forget to UPVOTE if you LIKE!!**
2,873
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
434
6
```\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n word_len = len(words[0])\n counter = collections.Counter(words)\n window_size = len(words) * word_len\n ans = []\n for i in range(len(s) - window_size + 1):\n temp = s[i:i+window_size]\n temp = [temp[j:j+word_len] for j in range(0, window_size, word_len)]\n if collections.Counter(temp) == counter:\n ans.append(i)\n return ans\n```
2,875
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
2,280
25
Please give a upvote if you like this solutions. Comment if you didn\'t get it.\n```\nclass Solution {\npublic:\n vector<int> findSubstring(string s, vector<string>& words) {\n \n unordered_map<string, int> M, temp;\n vector<int> Ans;\n int N = words.size();\n int L = words[0].size();\n \n // Store all the frequencies of all strings\n // in the array words[]\n for(auto &it : words) {\n M[it]++;\n }\n int size = s.length();\n \n // Loop till possible number of starting\n // index of the valid indices\n for(int i = 0; i < size - N*L + 1; i++) {\n \n // Iterate the current window of\n // length N*L over the range\n // [i, i + N*L] and extract the\n // substring of length L and store\n // it\'s frequency\n for(int j = i; j < i + N*L; j+= L) {\n string ans = s.substr(j, L);\n temp[ans]++;\n }\n \n int flag = 1;\n \n // Now, check if the frequency of each string\n // in map M is the same as the frequency in\n // map temp. This ensure that the current\n // window is of the same concatenation of\n // the strings in the array words[]\n for(auto &it : M) {\n if(M[it.first] != temp[it.first]) {\n flag = 0;\n break;\n }\n }\n \n // If the current window is the possible\n\t\t\t// result then store the starting index of it\n if(flag) Ans.push_back(i);\n \n // Clear the temp for another window\n temp.clear();\n }\n \n // Return the resultant vector of indices\n return Ans;\n }\n};\n```
2,877
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
1,462
6
[]()\n[]()\n# DO UPVOTE IF YOU FIND IT SUITABLE AND HELPFUL AND FOR ANY DOUBTS COMMENT.\n# DO LIKE AS EACH VOTE COUNTS\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> Refer and take the refernce from the find all anagrams and permutations in a string question of leetcode 438.\n\n# Approach\n<!-- Describe your approach to solving the problem. --> Sliding window + hashtable for each word in words list and then inside nested loop use substrcount each time new and compare for equivalence\\.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->The first for-loop iterates over all words in the input list words and takes O(N) time where N is the number of words in the list.\nThe second for-loop iterates over all substrings of length len(words)*len(words[0]) in the input string s. The number of substrings will be O(M) where M is the length of the input string. For each substring, the code creates a new dictionary substrcount and iterates over all words of length len(words[0]) in the substring. This takes O(len(substr)/len(words[0])) time for each substring. Therefore, the overall time complexity of the second for-loop is O(M * len(substr)/len(words[0])) = O(M*N), where N and M are defined as before.\nThe dictionary operations (insertion, lookup) in the code take O(1) time.\nThus, the overall time complexity of the code is O(M*N), where N is the number of words in the input list and M is the length of the input string.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->The code uses two dictionaries, wordcount and substrcount, to store word frequencies. The maximum size of each dictionary is N (the number of words in the input list).\nThe code stores the input string s, which takes O(M) space.\nThe code stores the result list result, which can take up to O(M/N) space in the worst case (when all substrings are valid).\nThus, the overall space complexity of the code is O(M + N).\n\nIn summary, the time complexity of the given code is O(M*N) and the space complexity is O(M + N), where N is the number of words in the input list and M is the length of the input string.\n\n\n\n\n# Code\n```\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n wordcount={}\n for word in words:\n wordcount[word]=1+wordcount.get(word,0)\n result=[]\n substringlength=len(words)*len(words[0])\n for i in range(len(s)-substringlength+1):\n substr=s[i:i+substringlength]\n substrcount={}\n for j in range(0,len(substr),len(words[0])):\n word=substr[j:j+len(words[0])]\n substrcount[word]=1+substrcount.get(word,0)\n if substrcount==wordcount:\n result.append(i)\n return result\n\n# m=\'\'.join(words)\n# pcount=dict()\n# scount=dict()\n# if len(m)>len(s):\n# print([])\n# for i in range(len(m)):\n# pcount[m[i]]=1+pcount.get(m[i],0)\n# scount[s[i]]=1+scount.get(s[i],0)\n# # print(pcount)\n# # print(scount)\n# res=[0]if pcount==scount else []\n# l=0\n# for i in range(len(m),len(s),1):\n# scount[s[i]]=1+scount.get(s[i],0)\n# scount[s[l]]-=1 \n# if scount[s[l]]==0:\n# del scount[s[l]]\n# l+=1 \n# if scount==pcount:\n# res.append(l)\n# #@print(res)\n# return res\n \n```
2,879
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
921
10
Runtime: 40 ms, faster than 92.72% of C++ online submissions for Substring with Concatenation of All Words.\nMemory Usage: 16.5 MB, less than 91.23% of C++ online submissions for Substring with Concatenation of All Words.\n\nHere we are using the concept of longest-substring-without-repeating-characters\nLink: \n\nLets understand the approach with example:\n\n"wordgoodgoodgoodbestword", \nwords = ["word","good","best","word"]\n\nWe will store the word and its freq in a map, lets name the map as "contain".\ncontain[words[i]]++\n\nOur map will look like:\nword = 2\ngood = 1\nbest = 1\n\nlet len = length of words in words, ie len = words[0].length()\n\nThen we will use two loops to iterate \nOutermost loop will determine the starting which is from 0 to len - 1\nInnermost loop will do a jump of i += len\nand within this we will implement longest substring without repeating.\n\nLets try to visualise why we used two loop\n\ns = "wordgoodgoodgoodbestword", \nwords = ["word","good","best","word"]\n\nWe can break this as\n\nword good good good best word \nor\nw ordg oodg oodg oodb estw ord\nor\nwo rdgo odgo odgo odbe stwo rd\nor\nwor dgoo dgoo dgoo dbes twor d\n\nif we further break it then it will be identical to the first \n\nNow after breaking, we just need to find the longest substring without repeating-characters\nBut here our words may repeat as per the freq so instead of > 1 we will use > contain[word[i]] (contain is the map we made earlier) in our if condition.\n\nCode:\n```\n vector<int> findSubstring(string str, vector<string>& words) {\n int len = words[0].length();\n \n unordered_map<string, int> contain;\n for(string s: words) contain[s]++;\n \n vector<int> res;\n for(int j = 0; j < len; j++) {\n unordered_map<string, int> found;\n int st = j;\n for(int i = 0 + j; i < str.size() - len + 1; i += len) {\n string curr = str.substr(i, len);\n if(contain.find(curr) != contain.end()) {\n found[curr]++;\n while(found[curr] > contain[curr]) {\n found[str.substr(st, len)]--;\n st += len;\n }\n int size = (i - st + len) / len;\n if(size == words.size()) {\n cout << j << " " << st << " " << i << endl;\n res.push_back(st);\n }\n } else {\n found.clear();\n st = i + len;\n }\n }\n }\n \n return res;\n }\n```\n\nPS: I am not a good with writing explanations so please bear with that\nIf it helped please upvote.\n\n\n\n\n\n\n\n\n\n\n\n\n\n
2,883
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
1,302
6
```\nclass Solution \n{\npublic:\n vector<int> findSubstring(string s, vector<string>& words) \n {\n vector<int> res;\n int n=words.size();\n int m=words[0].size(); // each word has the same length;\n int t = m*n;\n \n if(s.size() < t) return res;\n \n unordered_map<string, int> freq;\n \n for(auto it:words)\n freq[it]++;\n \n for(int i=0; i<=s.size()-t; i++)\n {\n unordered_map<string, int> mp = freq;\n \n int j;\n for(j=0; j<s.size(); j++)\n {\n string temp = s.substr(i+j*m, m); //create string of size m and starting index i+j*m\n \n if(mp[temp]==0)\n break;\n else\n mp[temp]--;\n }\n if(j==n) //check whether all word in words are in the string or not \n res.push_back(i);\n \n }\n return res;\n \n }\n};\n```
2,885
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
706
8
```\nclass Solution {\npublic:\n bool check(unordered_map<string, int> hash, string current, int wordSize){\n for(int i = 0; i < current.size(); i += wordSize){\n string word = current.substr(i, wordSize);\n \n if(!hash[word]) return false;\n hash[word]--;\n }\n \n return true;\n }\n \n vector<int> findSubstring(string s, vector<string>& words) {\n int size = words[0].size() * words.size();\n vector<int> result;\n unordered_map<string, int> hash;\n \n if(s.size() < size) return {};\n \n for(string word : words) hash[word]++;\n \n for(int i = 0; i <= s.size() - size; i++){\n if(check(hash, s.substr(i, size), words[0].size()))\n result.push_back(i);\n }\n \n return result;\n }\n};\n```\n\n**Please upvote if this solution helped**
2,889
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters. You can return the answer in any order.
Hash Table,String,Sliding Window
Hard
null
791
9
```\nclass Solution {\npublic:\n vector<int> findSubstring(string s, vector<string>& words) {\n vector<int> v1;\n \n int n=words.size();\n int len=words[0].length();\n int k=n*len;\n if(s.length()<k)return v1;\n unordered_map <string,int> mp;\n for(int i=0;i<n;i++)\n {\n mp[words[i]]++;\n }\n for(int i=0;i<=s.length()-k;i++)\n {\n \n int count=n;\n int st=i;\n unordered_map<string,int> mp1;\n while(count)\n {\n \n string s1=s.substr(st,len);\n mp1[s1]++;\n if(mp.find(s1)!=mp.end() && mp[s1]>=mp1[s1])\n {\n count--;\n st+=len;\n }\n else break;\n \n }\n if(count==0)\n {\n v1.push_back(i);\n \n }\n \n }\n return v1;\n }\n};
2,896
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
36,254
423
\n\n# Approach\n The steps are the following:\n\n1. Find the break-point, i: Break-point means the first index i from the back of the given array where arr[i] becomes smaller than arr[i+1].\nFor example, if the given array is {2,1,5,4,3,0,0}, the break-point will be index 1(0-based indexing). Here from the back of the array, index 1 is the first index where arr[1] i.e. 1 is smaller than arr[i+1] i.e. 5.\n2. To find the break-point, using a loop we will traverse the array backward and store the index i where arr[i] is less than the value at index (i+1) i.e. arr[i+1].\nIf such a break-point does not exist i.e. if the array is sorted in decreasing order, the given permutation is the last one in the sorted order of all possible permutations. So, the next permutation must be the first i.e. the permutation in increasing order.\nSo, in this case, we will reverse the whole array and will return it as our answer.\n3. If a break-point exists:\nFind the smallest number i.e. > arr[i] and in the right half of index i(i.e. from index i+1 to n-1) and swap it with arr[i].\nReverse the entire right half(i.e. from index i+1 to n-1) of index i. And finally, return the array.\n\n![image.png]()\n\n<!-- Describe your approach to solving the problem. -->\n\n\n\n# Code\n```\nclass Solution {\n public void nextPermutation(int[] nums) {\n int ind1=-1;\n int ind2=-1;\n // step 1 find breaking point \n for(int i=nums.length-2;i>=0;i--){\n if(nums[i]<nums[i+1]){\n ind1=i;\n break;\n }\n }\n // if there is no breaking point \n if(ind1==-1){\n reverse(nums,0);\n }\n \n else{\n // step 2 find next greater element and swap with ind2\n for(int i=nums.length-1;i>=0;i--){\n if(nums[i]>nums[ind1]){\n ind2=i;\n break;\n }\n }\n\n swap(nums,ind1,ind2);\n // step 3 reverse the rest right half\n reverse(nums,ind1+1);\n }\n }\n void swap(int[] nums,int i,int j){\n int temp=nums[i];\n nums[i]=nums[j];\n nums[j]=temp;\n }\n void reverse(int[] nums,int start){\n int i=start;\n int j=nums.length-1;\n while(i<j){\n swap(nums,i,j);\n i++;\n j--;\n }\n }\n}\n```\n![images.jpeg]()\n
2,900
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
3,673
5
# Code\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int n = nums.size();\n int idx = -1;\n for(int i = 0; i < n-1; i++) {\n if(nums[i]<nums[i+1]) idx = i;\n }\n if(idx == -1) {\n reverse(nums.begin(), nums.end());\n return;\n }\n int l = idx + 1;\n for(int i = idx + 1; i < n; i++) {\n if(nums[i] > nums[idx]) l = i;\n }\n swap(nums[idx], nums[l]);\n reverse(nums.begin() + 1 + idx, nums.end());\n return;\n }\n};\n```
2,904
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
28,294
182
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this question using 3 ways.\n\n1. Find all the permutation of Array(nums) then we can easily find next permutation.\n2. Solved using Array + Two Pointers.\n3. Solved using next_permutation (inbuilt) function.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the All the approaches by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity : O(N), Since we traverse the entire Array(nums) once in the worst case. Where N = size of the Array(nums).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity : O(1), Constant Space.\n\n# Code\n```\n/*\n\n Time Complexity : O(N), Since we traverse the entire Array(nums) once in the worst case. Where N = size of\n the Array(nums).\n\n Space Complexity : O(1), Constant Space.\n\n Solved using Array + Two Pointers.\n\n*/\n\n\n/***************************************** Approach 1 First Code *****************************************/\n\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int n = nums.size(), index = -1;\n for(int i=n-2; i>=0; i--){\n if(nums[i] < nums[i+1]){\n index = i;\n break;\n }\n }\n for(int i=n-1; i>=index && index != -1; i--){\n if(nums[i] > nums[index]){\n swap(nums[i], nums[index]);\n break;\n }\n }\n reverse(nums.begin() + index + 1, nums.end());\n }\n};\n\n\n\n\n\n\n/***************************************** Approach 1 Second Code *****************************************/\n\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n next_permutation(nums.begin(), nums.end());\n }\n};\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]()
2,905
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
117,239
1,159
According to [Wikipedia](), a man named Narayana Pandita presented the following simple algorithm to solve this problem in the 14th century.\n\n1. Find the largest index `k` such that `nums[k] < nums[k + 1]`. If no such index exists, just reverse `nums` and done.\n2. Find the largest index `l > k` such that `nums[k] < nums[l]`.\n3. Swap `nums[k]` and `nums[l]`.\n4. Reverse the sub-array `nums[k + 1:]`.\n\n```cpp\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n \tint n = nums.size(), k, l;\n \tfor (k = n - 2; k >= 0; k--) {\n if (nums[k] < nums[k + 1]) {\n break;\n }\n }\n \tif (k < 0) {\n \t reverse(nums.begin(), nums.end());\n \t} else {\n \t for (l = n - 1; l > k; l--) {\n if (nums[l] > nums[k]) {\n break;\n }\n } \n \t swap(nums[k], nums[l]);\n \t reverse(nums.begin() + k + 1, nums.end());\n }\n }\n}; \n```\n\nThe above algorithm can also handle duplicates and thus can be further used to solve [Permutations]() and [Permutations II]().
2,912
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,357
8
**NOTE - PLEASE READ INTUITION AND APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem :\n```\narr : [2,5,8,4,7,6,3] -> nextPermutation : [2,5,8,6,3,4,7]\n\n1. In below image arr[i] and arr[i+1] = 4 and 7. so, i = 3.\n2. In below image arr[i] and arr[j] = 4 and 6. So, j = 5.\n3. swap arr[i] and arr[j]. So, our new array will be [2,5,8,6,7,4,3]\n4. reverse i+1 to n-1. So, our final array will be [2,5,8,6,3,4,7] which is the next permutaion of given array \n\n**NOTE : THE ABOVE 4 STEPS IS SAME AS BELOW EXPLAINED APPROACH.**\n 8\n / \\\n / \\ 7\n / \\ / \\\n / \\ / 6\n 5 \\ / \\\n / 4 \\\n / \\\n / 3\n /\n 2\n```\n1. *Find the first element from the right that is smaller than its adjacent element. This is the first element that can be swapped with a larger element to its right to create a greater permutation.*\n - int i = n - 2;\n while (i >= 0 && nums[i] >= nums[i+1]) {\n i--;\n }\n2. *If such an element is found, find the smallest element to the right of it that is larger than it.*\n - int j = n - 1;\n while (j >= 0 && nums[i] >= nums[j]) {\n j--;\n }\n3. *Swap these two elements.*\n - swap(nums[i], nums[j]); \n4. *Reverse the subarray to the right of the swapped element. This is because the elements to the right of the swapped element are in descending order, and reversing them creates the smallest possible permutation that is greater than the original one.*\n - reverse(nums.begin() + i + 1, nums.end()); \n<!-- Describe your approach to solving the problem. -->\n\n# Code :\n```C++ []\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int n = nums.size();\n \n // Find the first element from the right that is smaller(nums[i]) than its adjacent(nums[i+1]) element\n int i = n - 2;\n while (i >= 0 && nums[i] >= nums[i+1]) {\n i--;\n }\n \n // If such an element(nums[i]) is found, find the smallest element(nums[j]) to the right of it(nums[i]) that is just larger than it(nums[i]).\n if (i >= 0) {\n int j = n - 1;\n while (j >= 0 && nums[i] >= nums[j]) {\n j--;\n }\n // Swap the two elements\n swap(nums[i], nums[j]);\n }\n \n // Reverse the subarray to the right of the swapped element\n reverse(nums.begin() + i + 1, nums.end());\n }\n};\n```\n\n# Time Complexity and Space Complexity:\n- **Time Complexity :** **O(n)**, where n is the length of the input vector nums. This is because we traverse the vector from right to left at most once to find the first element that is smaller than its adjacent element and from right to left again to find the smallest element to the right of the element we found in the previous step. Then we reverse the subarray to the right of the swapped element in O(n/2) time. Therefore, the total time complexity is **O(n) + O(n) + O(n/2) = O(n)**.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space Complexity :** **O(1)**. We use constant extra space throughout the algorithm.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
2,916
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
47,295
852
Implementation based on description from [Project Nayuki](). I cannot describe it better than them:\n\n![next permutation steps][1]\n\n\tpublic class Solution {\n\t/*0*/ public void nextPermutation(int[] nums) {\n\t // pivot is the element just before the non-increasing (weakly decreasing) suffix\n\t/*2*/ int pivot = indexOfLastPeak(nums) - 1;\n\t // paritions nums into [prefix pivot suffix]\n\t if (pivot != -1) {\n\t int nextPrefix = lastIndexOfGreater(nums, nums[pivot]); // in the worst case it\'s suffix[0]\n\t // next prefix must exist because pivot < suffix[0], otherwise pivot would be part of suffix\n\t/*4*/ swap(nums, pivot, nextPrefix); // this minimizes the change in prefix\n\t }\n\t/*5*/ reverseSuffix(nums, pivot + 1); // reverses the whole list if there was no pivot\n\t/*6*/ }\n\t \n\t /**\n\t * Find the last element which is a peak.\n\t * In case there are multiple equal peaks, return the first of those.\n\t * @return first index of last peak\n\t */\n\t/*1*/ int indexOfLastPeak(int[] nums) {\n\t for (int i = nums.length - 1; 0 < i; --i) {\n\t if (nums[i - 1] < nums[i]) return i;\n\t }\n\t return 0;\n\t }\n\n\t /** @return last index where the {@code num > threshold} or -1 if not found */\n\t/*3*/ int lastIndexOfGreater(int[] nums, int threshold) {\n\t for (int i = nums.length - 1; 0 <= i; --i) {\n\t if (threshold < nums[i]) return i;\n\t }\n\t return -1;\n\t }\n\n\t /** Reverse numbers starting from an index till the end. */\n\t void reverseSuffix(int[] nums, int start) {\n\t int end = nums.length - 1;\n\t while (start < end) {\n\t swap(nums, start++, end--);\n\t }\n\t }\n\t \n\t void swap(int[] nums, int i, int j) {\n\t int temp = nums[i];\n\t nums[i] = nums[j];\n\t nums[j] = temp;\n\t }\n\t}\n\n\n [1]:
2,917
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
490
7
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTreating the array as real number for example [1,2,3] read as 123, the next permutation or the next greater number that can be formed using these digits is 132 [1,3,2] is thus the next permutation.One thing to observe is that when we move from right to left as soon as we encounter a smaller number we think of swapping it with its just greater number because we need a number just greater than the given number so using this observation we can loop in reverse order and find a number that is less than the current digit .On the contrary if we get a number greater than the current number then using the digits we cannot form a greater number so we are in search of a smaller number.As soon as it is found we break out from the loop. We then find a just greater number in the right half(already traversed part of the array just now) and swap the dip element with it. As we know if we swap a number greater than the dip element we need the other numbers to be in sorted order in th right half so that the number formed is just greater as the array was already sorted in descending order we just reverse it to get the increasing order.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int i,j,n=nums.size();\n for(i=n-2;i>=0;i--)\n {\n if(nums[i]<nums[i+1])\n break;\n } \n if(i<0)\n {\n reverse(nums.begin(),nums.end());\n }\n else\n {\n for(j=n-1;j>=i;j--)\n {\n if(nums[j]>nums[i])\n break;\n }\n swap(nums[i],nums[j]);\n reverse(nums.begin()+i+1,nums.end());\n }\n }\n};\n```
2,918
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
11,734
145
![image]()\n\n```\nvoid nextPermutation(vector<int>& nums) \n {\n int n=nums.size();\n int l,r;\n for(l=n-2;l>=0;l--) // find decreasing sequence\n {\n if(nums[l]<nums[l+1]) break;\n }\n if(l<0) reverse(nums.begin(),nums.end());\n else\n {\n for(r=n-1;r>l;r--) // find rightmost successor to pivot\n {\n if(nums[r]>nums[l]) break;\n }\n swap(nums[l],nums[r]); // swap l,r\n \n reverse(nums.begin()+l+1,nums.end()); // reverse from l+1 to end\n }\n }\n```
2,919
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
922
5
# Approach\n- First we have to find where i < i+1 while we are traversing the array from second last element , second last beacause we are comapring it with i+1.If we start from last then it will give index out of bound.When we find that point where i < i+1 we store that i index in variable name ind which is firstly intialised as -1.\nlet understand why we are doing this,\n```\n->In question asked of next permutation of given arr elements . \nLet suppose the given arr = [1 2 3]\nwe can rearrange it in 6 different ways or we say there is 3! permutations , which are\n 1 2 3\n 1 3 2<- This is our answer \n 2 1 3\n 2 3 1\n 3 1 2\n 3 2 1\nAs we can see 1 3 2 > 1 2 3,\n->so we have to check and take that prefix,if we make change on that then our modified array is greater then previous array . \nunderstand this with different example \n;- i i+1\n ^ ^\ngiven arr = [1 , 2 , 0 , 5 , 1]\n this is where our condition stops \nNow we store this i in ind variable and break the loop.\n```\n- We can\'t directly swap i with i+1 or any other number which can make array greater then previous beacuse output is according to the sorted permutation so we have to update it in sorted order before that think of edge case \n```\nEDGE CASE \ngiven arr = [3 2 1]\nAll permutation : -\n 1 2 3\n 1 3 2\n 2 1 3\n 2 3 1\n 3 1 2\n 3 2 1\nAs we there is no next permutaion of 3 2 1 then we return the first permutation means\n1 2 3 is our output in this case and we can get it by just reversing the array .\n```\n- Now lets decide with which element we can swap our ind index in order to make **Greater then previous** and **Next Permutation**\n```\ngiven arr = [1 2 0 5 1]\n 0 1 2 3 4<-Index\nind = 2 \nnow we have 5 and 1 to swap with ind index in order to make it greater then previous array , \ni can\'t write all possible permutaion of 1 2 0 5 1 but i just write the next permutation of it which is \n 1 2 1 0 5 is our next permutaion\n->Now if we swap i with 5 then our array is greater but not our next permutation \n-> If we swap ind index value with 1 then our array is \n1 2 1 5 0\n->So by this we understanded we have to pick smallest from all larger elements\n->0(ind index value)<1<5,just greater then ind index value and smaller then all choices we have.\n->We can find this by traversing the array from last to ind or 0.\nif(a[i]>a[ind]){\nswap(a[i],a[ind]);\nbreak;\n}\nNow after this we have 1 2 1 5 0\n```\n- After this we have to sort the remainig array in order to make next permutation we can do it simply by reversing the array from ind+1 to a.legnth-1.\n```\n1 2 1 5 0<-a.length-1\n ^ \n ind+1\nif we just reverse this portion then\n 1 2 1 0 5 is array and this is also next permutation of our given array.\n```\n\n---\n\n*If there is some doubt or any mistake i have done in explaining please let me know in comments \uD83D\uDE4F*\n# Complexity\nin place and use only constant extra memory.\n\n# Code\n```\nclass Solution {\n public void nextPermutation(int[] a) {\n int ind = -1;\n for(int i = a.length-2;i>=0;i--){\n if(a[i]<a[i+1]){\n ind = i;\n break;\n }\n }\n if(ind==-1){\n arev(a,0,a.length-1);\n return;\n }\n for(int i = a.length-1;i>=0;i--){\n if(a[i]>a[ind]){\n int temp = a[i];\n a[i]=a[ind];\n a[ind]=temp;\n break;\n }\n }\n arev(a,ind+1,a.length-1);\n\n }\n static void arev(int[] a,int low,int high){\n while(low<high){\n int temp = a[low];\n a[low]=a[high];\n a[high]=temp;\n low++;\n high--;\n }\n }\n}\n```
2,925
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,015
8
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n next_permutation(nums.begin(), nums.end());\n }\n};\n```\n![upvote new.jpg]()\n
2,926
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,280
6
**Approach to the Problem**\n\nLet\'s understand the problem with an example.\n```\n1 2 3 4 \n```\nFirstly, we traverse from the end element i.e, 4. \nFind the pnt where the element is less than the next element. here it is-> 2 as 2<3\nCode for above two lines:\n```\nfor(pnt=n-2;pnt>=0;pnt--){\nif(nums[pnt]<nums[pnt+1]\n break;\n}\n```\nNow if pnt<0 it means the number is in decreasing order and hence, the next permutation will be the reverse of it.\ncode for it:\n```\nif(pnt<0)\n reverse(nums.begin(),nums.end());\n```\nElse check by traversing from the last element the number greater than the number at (pnt) if found then swap them.\nCode for it:\n```\nelse{\n for(l=n-1;l>k;l--){\n\t if(nums[l]>nums[k])\n\t break;\n\t}\n\tswap(nums[l],nums[k]);\n```\nNow at the end, reverse the sequence starting after pnt and ending at nums end.\n```\nreverse(nums.begin()+pnt+1,nums.end());\n```\nfor eg. \n```\n**1 2 3 4** \nnext permutation=> **1 2 4 3** => swapped(3,4)\nnext permutation=> 1 2 4 3 => 1 3 4 2(swapped 2 with 3)=>**1 3 2 4**(reversed the number after 4)\nnext permutation=>1 3 2 4=> 1 3 4 2(swapped 2 wih 4)\nnext permutation=>1 3 4 2=>1 4 3 2(swapped 3 with 4)=>**1 4 2 3**(reversed the number after 4)\n```\nHere\'s the whole code \uD83D\uDC47\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int n=nums.size(),pnt,l;\n for(pnt=n-2;pnt>=0;pnt--){\n if(nums[pnt]<nums[pnt+1]){\n break;\n }\n }\n if(pnt<0){\n reverse(nums.begin(),nums.end());\n }else{\n for(l=n-1;l>pnt;l--){\n if(nums[l]>nums[pnt]){\n break;\n }\n }\n swap(nums[l],nums[pnt]);\n reverse(nums.begin()+pnt+1,nums.end());\n }\n }\n};\n```\n**IF You Liked the explanation please Upvote it:)**
2,927
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
972
7
# STL Code\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n next_permutation(nums.begin(), nums.end());\n }\n};\n```\n\n# Code\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int idx = -1;\n int n = nums.size();\n\n for(int i = n-2;i >= 0;i--){\n if(nums[i] < nums[i+1]){\n idx = i;\n break;\n }\n }\n\n if(idx == -1){\n reverse(nums.begin(), nums.end());\n return;\n }\n\n for(int i = n-1;i >= 0;i--){\n if(nums[i] > nums[idx]){\n swap(nums[i], nums[idx]);\n break;\n }\n }\n reverse(nums.begin() + idx + 1, nums.end());\n }\n};\n```
2,928
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,413
8
# Intuition\nEvery lexicographic sequence has increasing order. We aim to get a peak from where the increasing sequence starts.\n\n# Approach\n1. From the right, find an element (i) which is greater than its previous element (i-1).\n2. If no such number is found, it means that array is in highest possible order. So return the reverse of the array (To rearrange it in lowest possible order).\n3. Now from the right, find an element (j) which is greater than (i-1).\n4. Swap (i-1) and (j).\n5. Reverse the array after (i-1), i.e. From (i) till end. (Here we are resetting the number after finding the peak).\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int i=nums.size()-1,j=nums.size()-1;\n while(i && nums[i-1]>=nums[i]) i--;\n if(!i) return reverse(nums.begin(),nums.end());\n while(nums[i-1]>=nums[j]) j--;\n swap(nums[i-1],nums[j]);\n return reverse(nums.begin()+i,nums.end());\n }\n};\n```\n---\n---\n![3bjfi3.jpg]()\n\n
2,931
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,794
22
Hey Guys,\nHope you all are doing well!\nIn this post, I\'ve provided two simple and easy-to-understand solutions.\nApproach 1:\nStep 1: Linearly traverse the array from backwards\xA0so that the array\'s ith index value is less than the array\'s (i+1)th index value. Store \xA0that index into a variable.\nStep 2: If the index value obtained in step 1 is less than zero. This indicates that the given input array has already been sorted in descending order. Simply reverse the given array to obtain the next permutation. Otherwise, simply traverse the array backwards to find the index that has\xA0a value greater than the previously found index. Store index in another variable.\nStep 3: Swap values present in indices found in the above two steps.\nStep 4: Reverse array from index+1 where the index is found at step 1 till the end of the array.\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& arr) {\n int n=arr.size(),i,j;\n for(i=n-2;i>=0;i--){\n if(arr[i]<arr[i+1]) break;\n }\n if(i<0) reverse(arr.begin(),arr.end());\n else{\n for(j=n-1; j>=0; j--){\n if(arr[j]>arr[i]) break;\n }\n swap(arr[i],arr[j]);\n reverse(arr.begin()+i+1,arr.end());\n }\n }\n};\n```\nApproach 2: We can simply use the C++ STL library function ```next_permutation()``` to get the next lexicographically greater permutation.\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& arr) {\n next_permutation(arr.begin(),arr.end());\n }\n};\n```\nWhile traversing from backwards we are searching for an element whose value is smaller than the value of its previous element and in each step, we are decrementing the counter i by 1. \nIf the given array is already sorted in descending order then we will not get a single element. Eventually, counter i become -1.\nAs we know to find the next permutation of any integer array which is already sorted in descending order simply take the reverse of it. \n\n![sample]()\n\n\nLet me know in comments if you have any doubts. I will be happy to answer.\nPlease upvote if you found the solution useful.\nHappy Coding!!
2,942
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
7,208
97
```\n def nextPermutation(self, nums):\n for i in range(len(nums)-1, 0, -1):\n # find the index of the last peak\n if nums[i - 1] < nums[i]:\n nums[i:] = sorted(nums[i:])\n \n # get the index before the last peak\n j = i - 1\n \n # swap the pre-last peak index with the value just large than it\n for k in range(i, len(nums)):\n if nums[j] < nums[k]:\n nums[k], nums[j] = nums[j], nums[k]\n return nums\n return nums.reverse()\n```\n\n**Please upvote me if you think this is useful! Much appreciated!**\n\nImagine this as a wave or signal, what we want to do is to move the last peak one-bit forward with equal or smaller peak\n\nConsider the following example [1, 2, 3, 5, 2, 3, 7, 5, 4, 3, 0]\n![image]()\n\nThe last peak is the red dot (index = 6), the index before the last peak (aka the pre-last peak index) is the green dot (index = 5)\n![image]()\n\nThen sort the region after the pre-peak index (green dot), the sorted region is shown in yellow dots\n![image]()\n\nThen find the point where its value is just above the pre-peak index (green dot)\nIn this example, it is the pink dot with index = 8\n![image]()\n\nSwap the green dot and the pink dot\n![image]()\n\n**Done!** Output the final list\nIn this case, it is [1,2,3,5,2,4,0,3,3,5,7]
2,949
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
496
10
# Approach 1: Brute Force \uD83E\uDDD0\n\n### Intuition \uD83E\uDD14\nWe want to find the next lexicographically greater permutation of an array of integers, `nums`.\n\n### Approach \uD83D\uDEE0\uFE0F\nThe brute force solution has three steps:\n1. Find all possible permutations of given array `nums`.\n2. Linearly search for the given permutation.\n3. Return the very next permutation of the given found permutation.\n\n### Time Complexity \u23F3\n- **Generating All Permutations:** Generating all permutations of an array with N elements has a time complexity of O(N!). This is because there are N! (N factorial) possible permutations of an array of size N.\n\n- **Finding a Particular Arrangement Linearly:** After generating all permutations, you would need to linearly search for a particular arrangement. This search would also take O(N!) time in the worst case because you might need to go through all permutations to find the desired one.\n\n- **Returning the Next Permutation of the Found Permutation:** Once you\'ve found the desired permutation, finding the next permutation of it would also take O(N) time because you need to follow the steps for finding the next permutation on that specific permutation.\n\nThus, the time complexity of this approach would be O(N!) due to the generation of all permutations. It\'s an inefficient approach, especially for large values of N, and is likely to give a **TLE**.\n\n### Space Complexity \uD83D\uDE80\nThe space complexity for generating all permutations of an array with N elements is O(N!) because you\'re storing N! different permutations.\n\n# Approach 2: Better Solution (only for cpp users) - Using `next_permutation()` fun\uD83E\uDDD0\n\n### Approach \uD83D\uDEE0\uFE0F\nWe can use the `next_permutation()` function. The next_permutation function is a part of the C++ Standard Library\'s `<algorithm>` header. It\'s used to generate the next lexicographically greater permutation of a vector.\n\n### Time Complexity \u23F3\nThe time complexity of the `next_permutation()` function is O(N), where N is the size of the input vector (nums in this case).\nThe function traverses the vector from right to left to find the first pair of two consecutive elements such that the left element is less than the right element. This operation takes O(N) time in the worst case.\nThe subsequent operations, such as finding the smallest greater element and reversing the subarray, also take O(N) time in total.\nSo, the overall time complexity is O(N).\n\n### Space Complexity \uD83D\uDE80\nThe next_permutation function operates in-place and does not use any additional memory that scales with the input size. Therefore, the space complexity of the nextPermutation function is O(1), which means it uses constant extra memory.\n\n### Code \uD83D\uDCBB\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n next_permutation(nums.begin(),nums.end());\n }\n};\n```\n\n# Approach 3: Optimized Solution \uD83E\uDDD0\n\n### Approach \uD83D\uDEE0\uFE0F\n- Like in a dictionary the very next word to a given word is almost the same except for a very few alphabets, e.g. in a dictionary Fire would come after fira. Notice how the first three alphabets are the same?\n- Observing this lexicographical order in an English dictionary, we apply a similar approach in the array as well.\n- Given array `nums` we find a **break point**. What is a breakpoint exactly and why are we finding it?\n- Notice that the next permutation of [1,2,5,4,3,0] -> [1,3,5,4,2,0] -> [1,3,0,2,4,5]. Observe how two numbers have been swapped( 2 and 3) first, and then the rest of the array is reversed.\n- This is because 2 is a breakpoint. A breakpoint here refers to a point that is lesser than the next element in the array.\n- We traverse `nums` starting from i=n-2th index. We compare each `nums[i]` with `nums[i+1]`. If at any index `i`, `nums[i]`<`nums[i+1]`, we set `i` as out `breakindex` variable.\n- Now after we\'ve found the `breakindex`, we traverse the right half of the `nums` array after `breakindex`, so from `i=n-1` till `i=breakpint+1`, and look for the least greater after the `breakpoint`.\n- In the array example taken above, index 1 was the `breakindex` and we traverse from element 5 to 0 and find that 3 is the least element greater than 1 in that portion of the array.\n- Now, we swap the `breakindex` element with this `leastgreat` index element.\n- Now we reverse the array from `breakindex+1` to `n-1`.\n-**Edge case:** It may happen that the array in the input is the last possible maximum permutation possible for the elements like: [5,4,3,3,2,0], so the next permutation will be the reverse of it which is the first smallest possible permutation of the elements. So in case we do not find a `breakpoint` like in this case, we simply reverse the given `nums` array.\n\n### Time Complexity \u23F3\nThe time complexity of this approach is linear. We traverse the array twice: first to find the `breakpoint` and then to find the least greater element. Each traversal takes O(N) time.tore indices and values.\n\n### Space Complexity \uD83D\uDE80\nThe space complexity is constant O(1) because the algorithm operates in-place without using any additional data structures that scale with the input size. \n\n### Code \uD83D\uDCBB\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n //find the breakpoint\n int breakpoint=-1;\n int n=nums.size();\n for(int i=n-2;i>=0;i--){\n if(nums[i]<nums[i+1]){\n breakpoint=i;\n break;\n } \n } \n if(breakpoint==-1){reverse(nums.begin(),nums.end());return;}\n \n //find least greater of element at the breakpoint\n int leastgreater=-1; \n int leastGvalue=101;\n for(int i=n-1;i>breakpoint;i--){\n if(nums[i]>nums[breakpoint]){\n if(nums[i]<leastGvalue){\n leastgreater=i;\n leastGvalue=nums[i];\n }\n }\n }\n\n //now swap breakpoint with leastgreater\n swap(nums[breakpoint],nums[leastgreater]);\n \n //reverse everything after the breakpoint\n reverse(nums.begin()+breakpoint+1,nums.end());\nreturn;\n}\n};\n```\n\n![CAN YOU PLEASE UPVOTE.jpg]()\n\n\n
2,950
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,874
7
# Complexity\n- Time complexity:\n$$O(n*log(n))$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n**First Approach**\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int n = nums.size(), element;\n if(n==1){\n return;\n }\n int index=-1;\n priority_queue<int> pq;\n for(int i=n-1; i>=0; i--){\n pq.push(nums[i]);\n if(pq.top()!= nums[i]){\n index = i;\n break;\n }\n }\n\n if(index == -1){\n sort(nums.begin(), nums.end());\n return;\n }\n\n int check, k = n-1;\n bool flag = true;\n element = nums[index];\n while (!pq.empty()) {\n if(pq.top() == element && flag){\n check = k+1;\n flag = false;\n }\n nums[k] = pq.top();\n pq.pop();\n k--;\n }\n \n reverse(nums.begin() + index, nums.begin() + check);\n reverse(nums.begin() + index, nums.begin() + check+1);\n\n }\n};\n```\n**Second Approach**\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int n = nums.size();\n if(n==1){\n return;\n }\n\n int index=-1,element,check;\n for(int i=n-1; i>0; i--){\n if(nums[i]>nums[i-1]){\n index = i-1;\n element = nums[i-1];\n break;\n }\n }\n\n if(index == -1){\n sort(nums.begin(), nums.end());\n return;\n }\n sort(nums.begin() + index, nums.end());\n \n for(int i=n-1; i>=index; i--){\n if(nums[i] == element){\n check = i+1;\n break;\n }\n }\n \n reverse(nums.begin() + index, nums.begin() + check);\n reverse(nums.begin() + index, nums.begin() + check+1);\n }\n};\n```\n\n\n
2,956
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,432
5
# Approach\nstep 1: find the element with a[i]>a[i-1];\nstep 2: if non found then return a sort array.\nstep 3: find the just greater element than step 1 element.\nstep 4: swap step 3 and step 1 elements and reverse/sort the element before the step 1 index.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& a) {\n // 1 3 5 4 2\n //find a[i]>a[i+1]\n int toswap=INT_MIN,withswap=INT_MIN;\n for(int i=a.size()-1;i>0;i--){\n if(a[i]>a[i-1]){\n toswap=i-1;\n break;\n }\n }\n //edge case\n if(toswap==INT_MIN) return reverse(a.begin(),a.end());\n //just greater element than toswap.\n else{\n for(int i=a.size()-1;i>toswap;i--){\n if(a[i]>a[toswap]){\n withswap=i;\n break;\n }\n }\n swap(a[toswap],a[withswap]);\n return reverse(a.begin()+toswap+1,a.end()); \n }\n }\n};\n```
2,957
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
4,062
32
# Please do upvote if you like the code ..ty\n# Code\n```\nclass Solution {\npublic:\n void nextPermutation(vector<int>& nums) {\n int n = nums.size(),k,l;\n \n // finding first element from the last which is smaller than\n // element next to it\n for(k=n-2 ; k>=0 ; k--)\n if(nums[k] < nums[k+1]) break;\n\n // if we dont find any such element that means the vector \n // is already sorted in descending order\n\n // i.e. It is already the biggest number that can be formed\n // using all the integers\n\n // In this case the next Premutation will be the smallest\n // permutation that can be formed using the numbers of\n // array i.e. all the array elements in ascending order\n // which is nothing but the reverse of the current order\n \n if(k<0)\n reverse(nums.begin() ,nums.end());\n\n // After finding the index "k" of the number which is \n // smaller than the number next to it ,\n // we will again traverse from the right to \n // left and will find the first element which is greater\n // the element at index k ....which is indeed the smallest \n // of all the numbers right to the index k\n\n // we will then swap both the characters \n // after swapping we will just reverse the digits after the\n // index k as that is in descending order and reversing it\n // will make it in increasing order and will make the whole\n // number smallest possible number greater than \n // the original number \n else{\n for(l = n-1; l >k ;l--)\n if(nums[l] > nums[k]) break;\n swap(nums[k], nums[l]); \n reverse(nums.begin()+k+1 , nums.end());\n }\n\n \n }\n};\n```
2,958
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
9,939
117
# Find next permutation:\n\n### Algorithm:\n\n**step 1:** Linearly traverse given array from the end and find a number that is greater than its adjacent `nums[i] > nums[i-1]`. Store the index of smaller number in `breakPoint` variable. If there is no such element, reverse entire array and return.\n\n**step 2:** Linearly traverse from the end and this time find a number larger than `nums[breakPoint]`. Let\'s call it `nums[i]`.\n\n**step 3:** Swap `nums[i] and nums[breakPoint]`.\n\n**step 4:** Reverse the array from index `breakPoint + 1` to `nums.size()`.\n\n### Example:\n* Consider `nums[] = [1, 3, 5, 4, 2]`.\n* Traverse from back and find a breakpoint. Here, index `breakPoint = 1` and `nums[breakPoint] = 3`\n* Traverse from back and find a number larger than this. Here this number is: `nums[i] = 4`\n* Swap `nums[breakPoint] and nums[i]`. Value after swapping: nums[] = [1, **4**, 5, **3**, 2].\n* Reverse array from `breakPoint + 1` to `nums.size()` i.e. these elements: [1, 4, **5**, **3**, **2**]\n* **`Final answer = [1, 4, 2, 3, 5]`.**\n\n**code:**\n```\n// find next permutation\nvoid nextPermutation(vector<int> &nums)\n{\n // initialize variable:\n int breakPoint = -1;\n\n // find a breakpoint:\n for (int i = nums.size() - 1; i > 0; i--)\n {\n if (nums[i] > nums[i - 1])\n {\n breakPoint = i - 1;\n break;\n }\n }\n\n // if no breakpoint\n if (breakPoint < 0)\n {\n reverse(nums.begin(), nums.end());\n return;\n }\n\n // if found a breakpoint\n for (int i = nums.size() - 1; i >= 0; i--)\n {\n if (nums[i] > nums[breakPoint])\n {\n swap(nums[breakPoint], nums[i]);\n reverse(nums.begin() + breakPoint + 1, nums.end());\n break;\n }\n }\n}\n```
2,965
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
492
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAlgorithm / Intuition\nThe steps are the following:\n\nFind the break-point, i: Break-point means the first index i from the back of the given array where arr[i] becomes smaller than arr[i+1].\nFor example, if the given array is {2,1,5,4,3,0,0}, the break-point will be index 1(0-based indexing). Here from the back of the array, index 1 is the first index where arr[1] i.e. 1 is smaller than arr[i+1] i.e. 5.\nTo find the break-point, using a loop we will traverse the array backward and store the index i where arr[i] is less than the value at index (i+1) i.e. arr[i+1].\nIf such a break-point does not exist i.e. if the array is sorted in decreasing order, the given permutation is the last one in the sorted order of all possible permutations. So, the next permutation must be the first i.e. the permutation in increasing order.\nSo, in this case, we will reverse the whole array and will return it as our answer.\nIf a break-point exists:\nFind the smallest number i.e. > arr[i] and in the right half of index i(i.e. from index i+1 to n-1) and swap it with arr[i].\nReverse the entire right half(i.e. from index i+1 to n-1) of index i. And finally, return the array.\nNote: For a better understanding of intuition, please watch the video at the bottom of the page.\n\n# Dry run\n<!-- Describe your approach to solving the problem. -->\n![image.png]()\n![image.png]()\n![image.png]()\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity: O(3N), where N = size of the given array\nFinding the break-point, finding the next greater element, and reversal at the end takes O(N) for each, where N is the number of elements in the input array. This sums up to 3*O(N) which is approximately O(3N).\n\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity: Since no extra storage is required. Thus, its space complexity is O(1).\n\n# Code\n```\nclass Solution {\n public void nextPermutation(int[] arr) {\n int n = arr.length;\n int ind = -1;\n // for finding the break point\n for (int i = n - 2; i >= 0; i--) {\n if (arr[i] < arr[i + 1]) {\n ind = i;\n break;\n }\n }\n // if the break point does not exist\n if (ind == -1) {\n reverse(arr, 0, n - 1);\n return;\n }\n // if the break point exists\n int j = n - 1;\n for (int i = n - 1; i >= ind + 1; i--) {\n if (arr[i] > arr[ind]) {\n swap(arr, i, ind);\n break;\n }\n }\n // Reverse the entire right half array\n reverse(arr, ind + 1, n - 1);\n }\n\n // Function for reverse the array\n public void reverse(int[] arr, int l, int r) {\n int start = l;\n int end = r;\n while (start < end) {\n int temp = arr[start];\n arr[start] = arr[end];\n arr[end] = temp;\n start++;\n end--;\n }\n }\n\n // Function for swap the elements\n public void swap(int[] arr, int i, int j) {\n int tem = arr[i];\n arr[i] = arr[j];\n arr[j] = tem;\n }\n}\n\n```
2,966
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,646
10
# Intuition\nIn dictionary consider the names `sam`, `sai` and `sui`. `sai` would be exactly next to sam because it has **`longest prefix match -sa`**. Similarly `sui` will be after `sam` but exactly not after `sam` because it has **`smaller prefix match - s`**. So the permutation with longest prefix match has higher chances of being the next one.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Find the breaking index :** \n - Breaking index occurs when a dip point is observered in the\n pattern of the nums.\n \n ![next permutation1.jpg]()\n - `Base codition` occurs when there is no breaking point, this indicates the given nums array is the last permutation. Hence, `reverse` the nums array which gives us our next permutation.\n \n ![next permutation2.jpg]()\n\n1. **Finding num just greater than breaking idx :**\n - Traverse the nums array `n-1 to idx`, if `nums[i] > nums[idx]->swap`and exit the loop.\n \n ![next permutation3.jpg]()\n\n1. **Reverse the remaining nums array :**\n - Reversing is needed because we need the just next Permutation.\n \n ![next permutation4.jpg]()\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n $$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n $$O(1)$$\n\n# Code\n```\nclass Solution {\n public void nextPermutation(int[] nums) {\n int n = nums.length;\n // store the breaking point\n int idx = -1;\n\n for(int i = n-2 ; i>=0 ; i--) {\n if(nums[i] < nums[i+1]) {\n idx = i;\n break;\n }\n }\n \n // base case - no breakpoint found\n if(idx == -1) {\n Arrays.sort(nums, 0, n);\n return;\n }\n\n\n // finding the greater but closest num\n for(int i=n-1 ; i>idx ; i--) {\n if(nums[i] > nums[idx]) {\n int temp = nums[i];\n nums[i] = nums[idx];\n nums[idx] = temp;\n break;\n }\n }\n // Reversing the remaining array.\n Arrays.sort(nums, idx+1, n);\n }\n}\n```
2,968
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
51,911
365
\n def nextPermutation(self, nums):\n i = j = len(nums)-1\n while i > 0 and nums[i-1] >= nums[i]:\n i -= 1\n if i == 0: # nums are in descending order\n nums.reverse()\n return \n k = i - 1 # find the last "ascending" position\n while nums[j] <= nums[k]:\n j -= 1\n nums[k], nums[j] = nums[j], nums[k] \n l, r = k+1, len(nums)-1 # reverse the second part\n while l < r:\n nums[l], nums[r] = nums[r], nums[l]\n l +=1 ; r -= 1
2,973
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
1,281
5
# Code\n```\nclass Solution(object):\n # To Reverse the Part of a List/Array\n def reverseLst(self,lst,left,right):\n while left < right:\n lst[left],lst[right] = lst[right],lst[left]\n left += 1\n right -= 1\n return lst\n\n def nextPermutation(self, nums):\n numsLen = len(nums)\n\n # Reaching the element which is Greater than the next and near to the right, and the element\'s idx is eleIdx\n eleIdx = numsLen - 1\n while 0 < eleIdx and nums[eleIdx-1] >= nums[eleIdx]:\n eleIdx -= 1\n\n # if the eleIdx is 0 that mean the Whole lst is reversely sorted in this case just return the sorted array but don\'t sort Just reverse it to get the sorted lst\n if eleIdx == 0:\n return self.reverseLst(nums,0,numsLen -1)\n\n # Reversing the right sub array from the eleIdx to end -> indirectly Sorting\n nums = self.reverseLst(nums,eleIdx,numsLen -1)\n\n # mainEle is the element that is neaded to swap with the next minum element after the mainEle\'s idx\n mainEleIdx = eleIdx -1\n\n # finding the right position for the mainElement and swapping it to the right position\n while eleIdx < numsLen and nums[mainEleIdx] >= nums[eleIdx]:\n eleIdx += 1\n\n nums[mainEleIdx],nums[eleIdx] = nums[eleIdx],nums[mainEleIdx]\n return nums\n```\nYou Can also Look At My SDE Prep Repo [*`\uD83E\uDDE2 GitHub`*]()
2,974
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
126,869
352
My idea is for an array:\n\n 1. Start from its last element, traverse backward to find the first one with index i that satisfy num[i-1] < num[i]. So, elements from num[i] to num[n-1] is reversely sorted. \n 2. To find the next permutation, we have to swap some numbers at different positions, to minimize the increased amount, we have to make the highest changed position as high as possible. Notice that index larger than or equal to i is not possible as num[i,n-1] is reversely sorted. So, we want to increase the number at index i-1, clearly, swap it with the smallest number between num[i,n-1] that is larger than num[i-1]. For example, original number is 121543321, we want to swap the '1' at position 2 with '2' at position 7. \n 3. The last step is to make the remaining higher position part as small as possible, we just have to reversely sort the num[i,n-1]\n\nThe following is my code:\n\n \n public void nextPermutation(int[] num) {\n int n=num.length;\n if(n<2)\n return;\n int index=n-1; \n while(index>0){\n if(num[index-1]<num[index])\n break;\n index--;\n }\n if(index==0){\n reverseSort(num,0,n-1);\n return;\n }\n else{\n int val=num[index-1];\n int j=n-1;\n while(j>=index){\n if(num[j]>val)\n break;\n j--;\n }\n swap(num,j,index-1);\n reverseSort(num,index,n-1);\n return;\n }\n }\n \n public void swap(int[] num, int i, int j){\n int temp=0;\n temp=num[i];\n num[i]=num[j];\n num[j]=temp;\n }\n \n public void reverseSort(int[] num, int start, int end){ \n if(start>end)\n return;\n for(int i=start;i<=(end+start)/2;i++)\n swap(num,i,start+end-i);\n }
2,976
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
56,382
300
Using a simple example, we can derive the following steps:\n\n public void nextPermutation(int[] A) {\n if(A == null || A.length <= 1) return;\n int i = A.length - 2;\n while(i >= 0 && A[i] >= A[i + 1]) i--; // Find 1st id i that breaks descending order\n if(i >= 0) { // If not entirely descending\n int j = A.length - 1; // Start from the end\n while(A[j] <= A[i]) j--; // Find rightmost first larger id j\n swap(A, i, j); // Switch i and j\n }\n reverse(A, i + 1, A.length - 1); // Reverse the descending sequence\n }\n\n public void swap(int[] A, int i, int j) {\n int tmp = A[i];\n A[i] = A[j];\n A[j] = tmp;\n }\n\n public void reverse(int[] A, int i, int j) {\n while(i < j) swap(A, i++, j--);\n }
2,981
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
4,773
20
# Intuition\nBasic Idealogy about the lexicographical order of permutations to the given input\n\n# Approach\nStep 1:In first for loop, traverse the array from the end to find the first decreasing element from the right.(If any of the element had not been found means, just reverse the loop and exit the program.)\n\nStep 2:In second for loop, traverse the array from the end to find the first element which is greater than the element we had found before.\n\nStep 3:Swap the two elements we had found and stored previously.\n\nStep 4:Just reverse the array from the index next to the first swapped element to the end.\n\n\n Do upvote for me!\n\n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public void nextPermutation(int[] nums) {\n int ind1=-1;\n int ind2=-1;\n for(int i=nums.length-2;i>=0;i--){\n if(nums[i]<nums[i+1]){\n ind1=i;\n break;\n }\n }\n if(ind1==-1){\n reverse(nums,0);\n }\n else{\n for(int i=nums.length-1;i>=0;i--){\n if(nums[i]>nums[ind1]){\n ind2=i;\n break;\n }\n }\n swap(nums,ind1,ind2);\n reverse(nums,ind1+1);\n }\n }\n void swap(int[] nums,int i,int j){\n int temp=nums[i];\n nums[i]=nums[j];\n nums[j]=temp;\n }\n void reverse(int[] nums,int start){\n int i=start;\n int j=nums.length-1;\n while(i<j){\n swap(nums,i,j);\n i++;\n j--;\n }\n }\n}\n```
2,982
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
10,755
88
```\nclass Solution:\n def nextPermutation(self, nums: List[int]) -> None:\n """\n Do not return anything, modify nums in-place instead.\n """\n # To find next permutations, we\'ll start from the end\n i = j = len(nums)-1\n # First we\'ll find the first non-increasing element starting from the end\n while i > 0 and nums[i-1] >= nums[i]:\n i -= 1\n # After completion of the first loop, there will be two cases\n # 1. Our i becomes zero (This will happen if the given array is sorted decreasingly). In this case, we\'ll simply reverse the sequence and will return \n if i == 0:\n nums.reverse()\n return \n # 2. If it\'s not zero then we\'ll find the first number grater then nums[i-1] starting from end\n while nums[j] <= nums[i-1]:\n j -= 1\n # Now out pointer is pointing at two different positions\n # i. first non-assending number from end\n # j. first number greater than nums[i-1]\n \n # We\'ll swap these two numbers\n nums[i-1], nums[j] = nums[j], nums[i-1]\n \n # We\'ll reverse a sequence strating from i to end\n nums[i:]= nums[len(nums)-1:i-1:-1]\n # We don\'t need to return anything as we\'ve modified nums in-place\n \'\'\'\n Dhruval\n \'\'\'\n```\n\nTake an example from this site and try to re-run above code manually. This will better help to understand the code\n\n\nRelated Link: \n\n
2,986
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
2,991
6
# 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 void nextPermutation(vector<int>& nums) {\n next_permutation(nums.begin() ,nums.end());\n }\n};\n```\nPlease upvote to motivate me to write more solutions\n\n
2,998
Next Permutation
next-permutation
A permutation of an array of integers is an arrangement of its members into a sequence or linear order. The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). Given an array of integers nums, find the next permutation of nums. The replacement must be in place and use only constant extra memory.
Array,Two Pointers
Medium
null
32,030
235
**Solution 1**\n\nJust for info: There's a library function that does the job, even going from totally reverse sorted to sorted:\n\n void nextPermutation(vector<int>& nums) {\n next_permutation(begin(nums), end(nums));\n }\n\n---\n\n**Solution 2**\n\nUsing library functions for all building blocks of the algorithm. Very nice how they all play together, notice the total lack of `+1`/`-1`, it all fits exactly.\n\n void nextPermutation(vector<int>& nums) {\n auto i = is_sorted_until(nums.rbegin(), nums.rend());\n if (i != nums.rend())\n swap(*i, *upper_bound(nums.rbegin(), i, *i));\n reverse(nums.rbegin(), i);\n }\n\n---\n\n**Solution 3**\n\nDoing it all on my own (except `swap`, let's not be silly):\n\n void nextPermutation(vector<int>& nums) {\n int i = nums.size() - 1, k = i;\n while (i > 0 && nums[i-1] >= nums[i])\n i--;\n for (int j=i; j<k; j++, k--)\n swap(nums[j], nums[k]);\n if (i > 0) {\n k = i--;\n while (nums[k] <= nums[i])\n k++;\n swap(nums[i], nums[k]);\n }\n }\n\n---\n\n**Solution 4**\n\nOk, let's be silly after all and not even use `swap` :-)\n\n void nextPermutation(vector<int>& nums) {\n int i = nums.size() - 1, k = i, tmp;\n while (i > 0 && nums[i-1] >= nums[i])\n i--;\n for (int j=i; j<k; j++, k--)\n tmp = nums[j], nums[j] = nums[k], nums[k] = tmp;\n if (i > 0) {\n k = i--;\n while (nums[k] <= nums[i])\n k++;\n tmp = nums[i], nums[i] = nums[k], nums[k] = tmp;\n }\n }
2,999
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
141,509
1,003
class Solution {\n public:\n int longestValidParentheses(string s) {\n int n = s.length(), longest = 0;\n stack<int> st;\n for (int i = 0; i < n; i++) {\n if (s[i] == '(') st.push(i);\n else {\n if (!st.empty()) {\n if (s[st.top()] == '(') st.pop();\n else st.push(i);\n }\n else st.push(i);\n }\n }\n if (st.empty()) longest = n;\n else {\n int a = n, b = 0;\n while (!st.empty()) {\n b = st.top(); st.pop();\n longest = max(longest, a-b-1);\n a = b;\n }\n longest = max(longest, a);\n }\n return longest;\n }\n };\n\nThe workflow of the solution is as below.\n\n 1. Scan the string from beginning to end. \n 2. If current character is '(',\n push its index to the stack. If current character is ')' and the\n character at the index of the top of stack is '(', we just find a\n matching pair so pop from the stack. Otherwise, we push the index of\n ')' to the stack.\n 3. After the scan is done, the stack will only\n contain the indices of characters which cannot be matched. Then\n let's use the opposite side - substring between adjacent indices\n should be valid parentheses. \n 4. If the stack is empty, the whole input\n string is valid. Otherwise, we can scan the stack to get longest\n valid substring as described in step 3.
3,000
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
7,030
67
# Approach\n- Here the approach is nothing but we are using a stack and when we encounter an opening brace then we push the index of it into the stack and whenever we touch a closing brace then we see the top of the stack if it\'s size is one then it means the closing braces have dominated the opening brace. We then edit the top value of the stack to the index of the closing brace.\n>- This method is clearly depicted in the picture as shown below.\n\n![pic1.png]()\n\n>- here answer is given as the line `ans = max(ans , index - stk.top())` only when the size of stack is not 1 and there is a closing brace encountered.\n\n---\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n stack<int>stk;\n stk.push(-1);\n int ans = 0;\n for(int i = 0 ; i < s.size(); i++)\n {\n if(s[i] == \'(\')\n stk.push(i);\n else\n {\n if(stk.size() == 1)\n stk.top() = i;\n else\n {\n stk.pop();\n ans = max(ans , i - stk.top());\n }\n }\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public int longestValidParentheses(String s) {\n int leftCount = 0;\n int rightCount = 0;\n int maxLength = 0;\n \n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == \'(\') {\n leftCount++;\n } else {\n rightCount++;\n }\n \n if (leftCount == rightCount) {\n maxLength = Math.max(maxLength, 2 * rightCount);\n } else if (rightCount > leftCount) {\n leftCount = rightCount = 0;\n }\n }\n \n leftCount = rightCount = 0;\n \n for (int i = s.length() - 1; i >= 0; i--) {\n if (s.charAt(i) == \'(\') {\n leftCount++;\n } else {\n rightCount++;\n }\n \n if (leftCount == rightCount) {\n maxLength = Math.max(maxLength, 2 * leftCount);\n } else if (leftCount > rightCount) {\n leftCount = rightCount = 0;\n }\n }\n \n return maxLength;\n }\n}\n```\n```python []\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n stack=[]\n l=[\'0\']*len(s)\n for ind,i in enumerate(s):\n if i==\'(\':\n stack.append(ind)\n else:\n if stack:\n l[stack.pop()]=\'1\'\n l[ind]=\'1\'\n return max(len(i) for i in \'\'.join(l).split(\'0\'))\n```\n\n---\n\n\n\n# Complexity\n>- Time complexity:Here the complexity would be $$O(n)$$ as we are using only a single loop with a stack only so this runs in a linear complexity.\n\n>- Space complexity:Here the space complexity would be $O(n)$ as we are using just a stack that too store the elements in the worst case it goes to that complexity.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n\n\n**IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.**\n\n![UPVOTE.jpg]()\n
3,001
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
540
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int n = s.size();\n stack <int>st;\n st.push(-1);\n int len_max = 0;\n for(int i=0;i<s.size();i++){\n if(s[i]==\'(\'){\n st.push(i);\n }\n \n else{\n st.pop();\n if(st.empty()){\n st.push(i);\n }\n else {\n int len = i-st.top();\n len_max = max(len,len_max);\n \n }\n }\n \n }\n return len_max;\n }\n};\n```
3,006
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
10,131
210
***Solution (Simulating with stack) :***\n\nWe can use a stack to find the longest valid parentheses. \n\nWe will start by pushing `-1` into the stack at first. This will denote index preceding to **potential start of valid parentheses**. It will be more clear later. Now will start iterating over `s` and we will have two cases -\n1. **`s[i] == \'(\'`** - In this case, we will push the index into the stack (just as we do in valid parentheses check).\n2. **`s[i] == \')\'`** - In this case, we will pop the index from the stack (again just as in parentheses check). Now, after popping, we need to do some simple checks which are main steps of this problem. Again, there will be following scenarios that may occur -\n * **stack is not empty** - If stack is not empty, then this **may be our longest valid parentheses**. We update the `MAX_len` as `max(MAX_len, current index - stack.top())`. Do notice, that our bottom of stack will always hold index preceding to a potential valid parentheses.\n\t* **stack becomes empty** - This will only happen when we have an extra \')\' bracket. There may have been valid parentheses previously which have been updated and stored in `MAX_len`. But, since we now have an extra closing bracket any further extensions of previous valid parentheses is not possible. So, push the current index into stack, again which will denote that bottom of stack will hold the index preceding to a **potential** valid parentheses.\n\n```\nExample - \'()())()\'\nInitial stack(from bottom to top) : [ -1 ] , MAX = 0\n\n1. i = 0 | s[i] = \'(\' => case-1: push current index into stack\nstack : [-1, 0] | MAX = 0\n\n2. i = 1 | s[i] = \')\' => case-2.1: pop. After pop, stack is not empty so update MAX.\nstack : [-1] | MAX = max(0, 1 - (-1)) = 2.\n\n\'NOTE : Since the index starts from 0, having index preceding to the start of valid parentheses will give us actual length of the valid parentheses,\ninstead of us having to add 1 to it everytime.\'\n\n3. i = 2 | s[i] = \'(\' => case-1: push current index into stack\nstack : [-1, 1] | MAX = 2.\n\n4. i = 3 | s[i] = \')\' => case-2.1: pop. After pop, stack is not empty so update MAX.\nstack : [-1] | MAX = max(2, 3 - (-1)) = 4.\n\n5. i = 4 | s[i] = \')\' => case-2.2: pop. After pop, stack is empty, so push current index into stack.\nThis denotes any valid parentheses from now will start from next index and previous valid parentheses cant be extended further.\nstack : [4] | MAX = 4.\n\n6. i = 5 | s[i] = \'(\' => case-1: push current index into stack\nstack : [4, 5] | MAX = 4.\n\n7. i = 6 | s[i] = \')\' => case-2.2: pop. After pop, stack is empty, so push current index into stack.\nstack : [4] | MAX = max(4, 6 - 4) = 4.\n```\n\nThe small simulation above might have given you the idea of how this process works. Watch the LC solution showing a gif which will give you better idea. Below is them implementation of the same -\n\n\n```\nint longestValidParentheses(string s) {\n\tint MAX = 0; // denotes length of maximum valid parentheses\n\tstack<int> stk;\n\tstk.push(-1); // bottom of stack will always hold index preceding to potential start of valid parentheses\n\tfor(int i = 0; i < size(s); i++)\n\t\tif(s[i] == \'(\') stk.push(i); \n\t\telse{ \n\t\t\tstk.pop();\n\t\t\tif(stk.empty()) stk.push(i);\n\t\t\telse MAX = max(MAX, i - stk.top());\n\t\t} \n\treturn MAX;\n}\n```\n\n***Time Complexity :*** **`O(N)`**, for iterating over the string s.\n***Space Complexity :*** **`O(N)`**, for maintaining the stack.\n
3,007
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
747
7
# Intuition\nStack to Keep Track of Opening Parentheses: The code uses a stack to keep track of the indices of opening parentheses \'(\' encountered while iterating through the input string.\n\nMatching Parentheses: When a closing parenthesis \')\' is encountered, it checks if there is a matching opening parenthesis \'(\' in the stack. If found, it marks both the opening and closing parentheses as valid by replacing them with underscores (\'_\'). This step essentially eliminates valid pairs of parentheses from further consideration.\n\nConsecutive Underscores Counting: After processing the entire string, it goes through the modified string with underscores (\'_\'). It counts consecutive underscores to determine the length of valid parentheses substrings. The idea is that consecutive underscores represent a sequence of valid parentheses.\n\nTracking the Longest Valid Substring: While counting consecutive underscores, it keeps track of the maximum count encountered, which corresponds to the length of the longest valid parentheses substring.\n\n# Approach\nInitialize variables:\n\nn is set to the length of the input string s.\nCreate an empty stack of integers named st. This stack will be used to store the indices of opening parentheses \'(\'.\nLoop through each character in the input string s using a for loop.\n\nInside the loop, check if the current character is a closing parenthesis \')\' (i.e., s[i] == \')\').\n\na. If it\'s a closing parenthesis and the stack st is not empty, it means there is a matching opening parenthesis \'(\' for the current closing parenthesis.\n\nb. Pop the top index j from the stack st, indicating that the opening parenthesis \'(\' at index j matches the closing parenthesis \')\' at index i.\n\nc. Replace both the opening and closing parentheses with underscores (\'_\') in the string s to mark them as valid and ignore them in subsequent calculations.\n\nIf the current character is an opening parenthesis \'(\' (i.e., s[i] == \'(\'), push its index i onto the stack st to keep track of unmatched opening parentheses.\n\nAfter processing the entire string s, all valid parentheses pairs should be marked with underscores (\'_\') in the string.\n\nInitialize a variable ans to 0. This variable will store the length of the longest valid parentheses substring.\n\nIterate through the modified string s using a for loop.\n\nWhen you encounter an underscore (\'_\'), it indicates a valid parentheses pair. Start counting consecutive underscores to determine the length of this valid parentheses substring.\n\na. Increment a counter variable ct by 1 for the current underscore.\n\nb. Use a while loop to count consecutive underscores by incrementing ct until a non-underscore character is encountered.\n\nc. After counting the consecutive underscores, update the loop variable i to the position after the last underscore.\n\nd. Update the ans variable by taking the maximum of its current value and the value of ct. This keeps track of the longest valid parentheses substring encountered so far.\n\nAfter processing the entire modified string s, the ans variable will contain the length of the longest valid parentheses substring.\n\nReturn the ans as the result.\n\n# Complexity\n- Time complexity:\nO(2*n) -> O(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int n = s.length();\n stack<int> st;\n for(int i=0;i<n;i++)\n {\n if(s[i] == \')\')\n {\n if(st.empty()==0)\n {\n int j = st.top();\n st.pop();\n s[i] = \'_\';\n s[j] = \'_\';\n }\n }\n if(s[i] == \'(\')\n {\n st.push(i);\n }\n }\n int ans = 0;\n for(int i=0;i<n;i++)\n {\n if(s[i] == \'_\')\n {\n int ct=1;\n i++;\n while(s[i] == \'_\')\n {\n ct++;\n i++;\n }\n i--;\n ans = max(ans,ct);\n }\n }\n return ans;\n }\n};\n```
3,010
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
392
7
# Intuition\nThe problem asks for the length of the longest valid parentheses substring in a given string. To solve this problem, we can use dynamic programming. The idea is to maintain a dynamic programming array `dp`, where `dp[i]` represents the length of the longest valid parentheses substring ending at index `i` of the input string. We can initialize `dp` with zeros and then iterate through the string to update `dp` as we find valid parentheses substrings.\n\n# Approach\n1. Initialize a dynamic programming array `dp` of size `s.size() + 1` and initialize all elements to 0.\n2. Initialize a variable `ans` to 0, which will store the maximum length of valid parentheses substring found so far.\n3. Iterate through the characters of the input string `s` from left to right, starting from the second character (index 1).\n - If the current character is \')\':\n - Check if there is a valid opening parenthesis \'(\' that can be matched with the current closing parenthesis \')\'.\n - To do this, check if the character before the current closing parenthesis (at index `i`) is an opening parenthesis \'(\', and if the character just before the opening parenthesis (at index `i - dp[i] - 1`) is also an opening parenthesis \'(\'.\n - If the conditions are met, update `dp[i + 1]` as follows:\n - `dp[i + 1] = dp[i] + 2 + dp[i - dp[i] - 1]`\n - Here, `dp[i]` represents the length of valid parentheses substring ending at the previous character, and `dp[i - dp[i] - 1]` represents the length of valid parentheses substring just before the opening parenthesis that matches with the current closing parenthesis.\n - Update `ans` with the maximum value between the current `ans` and `dp[i + 1]`.\n4. After iterating through the entire string, `ans` will contain the length of the longest valid parentheses substring in the input string.\n5. Return `ans` as the result.\n\n# Complexity\n- Time complexity: O(n), where n is the length of the input string `s`. We iterate through the string once, and for each character, we perform constant time operations.\n- Space complexity: O(n), as we use a dynamic programming array `dp` of the same length as the input string.\n\n# Code\n```cpp\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n vector<int> dp(s.size() + 1, 0);\n int ans = 0;\n for (int i = 1; i < s.size(); i++) {\n if (s[i] == \')\' && (i - dp[i] - 1) >= 0 && s[i - dp[i] - 1] == \'(\')\n dp[i + 1] = dp[i] + 2 + dp[i - dp[i] - 1];\n ans = max(ans, dp[i + 1]);\n }\n return ans;\n }\n};
3,014
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
83,053
611
My solution uses DP. The main idea is as follows: I construct a array <b>longest[]</b>, for any longest[i], it stores the longest length of valid parentheses which is end at i.\n<br>And the DP idea is :\n<br> If s[i] is '(', set longest[i] to 0,because any string end with '(' cannot be a valid one.\n<br>Else if s[i] is ')'\n<br>\xa0\xa0\xa0\xa0 If s[i-1] is '(', longest[i] = longest[i-2] + 2\n<br>\xa0\xa0\xa0\xa0 Else if s[i-1] is ')' **and s[i-longest[i-1]-1] == '('**, longest[i] = longest[i-1] + 2 + longest[i-longest[i-1]-2]\n<br> For example, input "()(())", at i = 5, longest array is [0,2,0,0,2,0], longest[5] = longest[4] + 2 + longest[1] = 6.\n<br>\n \n\n int longestValidParentheses(string s) {\n if(s.length() <= 1) return 0;\n int curMax = 0;\n vector<int> longest(s.size(),0);\n for(int i=1; i < s.length(); i++){\n if(s[i] == ')'){\n if(s[i-1] == '('){\n longest[i] = (i-2) >= 0 ? (longest[i-2] + 2) : 2;\n curMax = max(longest[i],curMax);\n }\n else{ // if s[i-1] == ')', combine the previous length.\n if(i-longest[i-1]-1 >= 0 && s[i-longest[i-1]-1] == '('){\n longest[i] = longest[i-1] + 2 + ((i-longest[i-1]-2 >= 0)?longest[i-longest[i-1]-2]:0);\n curMax = max(longest[i],curMax);\n }\n }\n }\n //else if s[i] == '(', skip it, because longest[i] must be 0\n }\n return curMax;\n }\n\nUpdated: thanks to **Philip0116**, I have a more concise solution(though this is not as readable as the above one, but concise):\n\n int longestValidParentheses(string s) {\n if(s.length() <= 1) return 0;\n int curMax = 0;\n vector<int> longest(s.size(),0);\n for(int i=1; i < s.length(); i++){\n if(s[i] == ')' && i-longest[i-1]-1 >= 0 && s[i-longest[i-1]-1] == '('){\n longest[i] = longest[i-1] + 2 + ((i-longest[i-1]-2 >= 0)?longest[i-longest[i-1]-2]:0);\n curMax = max(longest[i],curMax);\n }\n }\n return curMax;\n }
3,015
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
566
5
# Please Upvote!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- The stack will store indices of the characters in the string. For every \')\' encountered, we check if the stack is not empty and the character at the top of the stack is \'(\', if so, it means that a pair of well-formed parentheses is formed.\n\n- The length of the longest valid parentheses can be updated by the current index minus the index at the new top of the stack (if the stack is not empty). If the stack is empty, we just push the current index into the stack.\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 {\npublic:\n int longestValidParentheses(string s) {\n stack<int> st;\n st.push(-1); // push -1 as initial index to start from\n int maxLength = 0;\n \n for(int i=0; i<s.size(); i++) {\n // if current character is \'(\', push its index\n if(s[i] == \'(\') {\n st.push(i);\n }\n else { \n // if current character is \')\', pop the top\n if(!st.empty())\n st.pop();\n // if stack is not empty, update the maxLength \n // by the difference of current index and index at the top of the stack\n if(!st.empty()) {\n maxLength = max(maxLength, i - st.top());\n }\n else {\n // if stack is empty, push the current index\n st.push(i);\n }\n }\n }\n \n return maxLength;\n }\n};\n\n```
3,016
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,869
13
# Approach\nIn My solution, trash indicates breakpoint or we can say that when we encounter \')\' but we don\'t have any \'(\' in stack to fulfil it , we can say next longer parentheses will start after this index and we need to keep track it since we are not inserting this into stack, \nand for rest if stack is not empty we can easily say (index-st.top());\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N) due to stack.\n\n# Code\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int n = s.length();\n \n stack<int>st;\n int trash = 0;\n int ans = 0;\n for(int i=1; i<=n; i++){\n if(s[i-1]==\'(\'){\n st.push(i);\n }\n else{\n if(st.empty()){\n trash= i;\n continue;\n }\n else{\n st.pop();\n }\n if(st.empty()){\n ans= max(ans, (int)(i-trash));\n }\n else{\n ans= max(ans, (int)(i-st.top()));\n } \n }\n \n }\n return ans;\n }\n};\n```
3,020
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,529
6
```\nclass Solution {\npublic:\n int longestValidParentheses(string str) {\n stack<int> s;\n s.push(-1);\n int ans = 0, n = str.size();\n for(int i=0; i<n; i++) {\n if(s.top() != -1 && str[s.top()] == \'(\' && str[i] == \')\') s.pop(), ans = max(ans, i - s.top());\n else s.push(i);\n }\n return ans;\n }\n};\n```
3,021
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
3,097
10
\n```\nclass Solution {\n // TC : O(n)\n // SC : O(n)\n public int longestValidParentheses(String s) {\n if(s==null || s.length()<2){\n return 0;\n }\n\n Stack<Integer> st =new Stack<>();\n\n for(int i=0;i<s.length();i++){\n if(s.charAt(i) == \'(\'){\n st.push(i);\n } else{\n\n // current closing bracket\n\n if(!st.empty() && s.charAt(st.peek()) == \'(\'){\n // balanced case\n st.pop();\n } else {\n // unbalanced case\n st.push(i);\n }\n }\n }\n \n int maxLen = 0;\n int endTerminal = s.length();\n\n while(!st.empty()){\n int startTerminal = st.pop();\n maxLen = Math.max(maxLen, endTerminal - startTerminal -1);\n endTerminal = startTerminal;\n }\n\n return Math.max(endTerminal, maxLen);\n \n }\n}\n```
3,023
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
8,594
61
The time complexity for both the approaches is `O(len(s)`.\n\n 1. ##### **Space - O(len(s))**\n\nThis approach solves the problem in similar way as using `Stack`. The stack is used to track indices of `(`. So whenever we hit a `)`, we pop the pair from stack and update the length of valid substring.\n\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n max_length = 0\n stck=[-1] # initialize with a start index\n for i in range(len(s)):\n if s[i] == \'(\':\n stck.append(i)\n else:\n stck.pop()\n if not stck: # if popped -1, add a new start index\n stck.append(i)\n else:\n max_length=max(max_length, i-stck[-1]) # update the length of the valid substring\n return max_length\n```\n\n2. ##### **Space - O(1)**\nThe valid parantheses problem can also be solved using a counter variable. Below implementation modifies this approach a bit and uses two counters:`left` and `right` for `(` and `)` respectively. \n\nThe pseudo code for this approach:\n1. Increment `left` on hitting `(`.\n2. Increment `right` on hitting `)`.\n3. If `left=right`, then calculate the current substring length and update the `max_length`\n4. If `right>left`, then it means it\'s an invalid substring. So reset both `left` and `right` to `0`.\n\nPerform the above algorithm once on original `s` and then on the reversed `s`.\n\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n max_length = 0\n \n l,r=0,0 \n # traverse the string from left to right\n for i in range(len(s)):\n if s[i] == \'(\':\n l+=1\n else:\n r+=1 \n if l == r:# valid balanced parantheses substring \n max_length=max(max_length, l*2)\n elif r>l: # invalid case as \')\' is more\n l=r=0\n \n l,r=0,0 \n # traverse the string from right to left\n for i in range(len(s)-1,-1,-1):\n if s[i] == \'(\':\n l+=1\n else:\n r+=1 \n if l == r:# valid balanced parantheses substring \n max_length=max(max_length, l*2)\n elif l>r: # invalid case as \'(\' is more\n l=r=0\n return max_length\n```\n\n---\n\n***Please upvote if you find it useful***
3,027
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,020
6
```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int n=s.length();\n vector<int>dp(n+1,0);\n stack<int>st;\n int ans=0;\n int temp=0;\n for(int i=0;i<n;i++)\n {\n if(s[i]==\'(\')\n st.push(i);\n else\n {\n if(!st.empty())\n {\n int k=st.top();\n st.pop();\n dp[k]=(i-k+1);\n }\n }\n }\n int i=0;\n while(i<n)\n {\n if(dp[i]==0)\n {\n temp=0;\n i++;\n }\n else\n {\n temp+=dp[i];\n i+=dp[i];\n }\n ans=max(ans,temp);\n }\n ans=max(ans,temp);\n return ans;\n }\n};\n```
3,030
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,657
6
# 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(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n# If you find this helpful,Please Upvote \n```\npublic class Solution {\n public int LongestValidParentheses(string s) {\n Stack<int> index =new Stack<int>();\n for(int i=0;i < s.Length;i++){\n if (s[i] == \'(\'){\n index.Push(i);\n }\n else{\n if(index.Any() && s[index.Peek()] == \'(\'){\n index.Pop();\n }\n else{\n index.Push(i);\n }\n }\n }\n if(!index.Any()){\n return s.Length;\n }\n int length = s.Length, unwanted = 0;\n int result = 0;\n while(index.Any()){\n unwanted = index.Peek();\n index.Pop();\n result = Math.Max(result,length - unwanted - 1);\n length = unwanted;\n }\n result = Math.Max(result,length);\n return result;\n }\n}\n```\n# Python Solution \n\n def ValidParantheses(s):\n length=len(s)\n dp=[0]*length\n count=0\n maxLen=0\n pos=0\n for par in s:\n if par == \'(\':\n count += 1\n elif par == \')\':\n if count>0:\n count-=1\n #immediate parentheses like ()()\n dp[pos]=dp[pos-1]+2\n #outer parentheses (out of nested parentheses or non immmediate valid parentheses)\n if dp[pos] <= pos:\n dp[pos] = dp[pos]+dp[pos-dp[pos]]\n \n maxLen=max(maxLen,dp[pos])\n pos += 1\n return maxLen\n\n# Upvote \uD83E\uDD1E
3,032
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,585
11
***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome*.**\n___________________\n_________________\n***Q32. Longest Valid Parentheses***\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n l,stack=0,[-1]\n for i in range(len(s)):\n if s[i]==\'(\':\n stack.append(i)\n else:\n stack.pop()\n if not stack:\n stack.append(i)\n else:\n l=max(l,i-stack[-1])\n return l;\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\n\u2705 **Java Code** :\n```\nclass Solution {\n public int longestValidParentheses(String s) {\n Stack<Integer> stack = new Stack();\n stack.push(-1);\n int maxLen = 0;\n for(int i = 0; i < s.length(); i++)\n {\n if(s.charAt(i) == \'(\')\n stack.push(i);\n else if(s.charAt(i) == \')\')\n { \n stack.pop();\n if(stack.empty())\n stack.push(i);\n else\n maxLen = Math.max(maxLen, i - stack.peek()); \n }\n }\n return maxLen;\n }\n}\n```\n\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **C++ Code** :\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int n = s.length(),len =0,maxlen =0;\n stack<int> st;\n st.push(-1);\n for(int i =0;i<n;i++)\n {\n if(s[i] == \'(\')\n st.push(i);\n if(s[i] == \')\')\n {\n st.pop();\n if(st.empty())\n st.push(i);\n len = i - st.top();\n maxlen = max(maxlen,len);\n }\n }\n return maxlen;\n }\n};\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n
3,034
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
2,109
29
**Please Upvote If It Helps**\n\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s) \n {\n // created a stack for storing the open parenthesis \n stack<int> st;\n st.push(-1); // initially push -1 to the stack because if there is ) then we can not pop our stack if it is empty\n \n int ans = 0;\n \n // iterate over the given string\n for(int i=0;i<s.length();i++)\n {\n // if it is open parenthesis then push that index to the stack\n if(s[i] == \'(\')\n st.push(i);\n \n // if it is close then pop the stack \n // and check it is empty or not if it is empty then push current value to it because if there is another ) then we can not pop our stack if it is empty\n // if it is not empty then find the length between the (current index i and stack top index) and store the max value in ans\n else\n {\n st.pop();\n \n if(st.empty())\n st.push(i);\n else\n ans = max(ans,i-st.top());\n }\n }\n \n // returning the answer\n return ans;\n }\n};\n```
3,035
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,681
12
```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int left=0,right=0,maxlen=0;\n for(int i=0;i<s.size();i++){\n if(s[i]==\'(\')\n left++;\n if(s[i]==\')\')\n right++;\n if(left==right)\n maxlen=max(maxlen,2*left);\n\t\t//when we traverse from left to right ,if right becomes more than left then we enter into invalid state\n else if(right>=left){\n left=0;\n right=0;\n }\n }\n left=0,right=0;\n for(int i=s.size()-1;i>=0;i--){\n if(s[i]==\'(\')\n left++;\n if(s[i]==\')\')\n right++;\n if(left==right)\n maxlen=max(maxlen,2*right);\n\t\t//when we traverse from right to left ,if left becomes more than right we enter into inavild state\n else if(left>=right){\n left=0;\n right=0;\n }\n }\n return maxlen;\n \n \n }\n};\n```
3,037
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
23,887
247
class Solution {\n public:\n int longestValidParentheses(string s) {\n stack<int> stk;\n stk.push(-1);\n int maxL=0;\n for(int i=0;i<s.size();i++)\n {\n int t=stk.top();\n if(t!=-1&&s[i]==')'&&s[t]=='(')\n {\n stk.pop();\n maxL=max(maxL,i-stk.top());\n }\n else\n stk.push(i);\n }\n return maxL;\n }\n };
3,041
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
3,033
64
This is quite difficult problem, which can be solved with dymamic programming. As usual let us define `dp[i]` the length of the longest valid substring ending at `i`-th index. We can have several cases now:\n1. If `i == -1`, it means we reached empty string, return `0`, answer for empty string. Also if `s[i] = (`, answer is also `0`, because no valid parantheses can end with `(`\n2. Now, we have case, when `s[i] = )`. Let us look at the previous element. If it is equal to `(`, then we have `()` as two last elements and we can return `dp(i-2) + 2`.\n3. Now consider the case, when `s[i-1] = )`, it means, that we have the following situation: `...))`. If we want to find the longest valid parentheses for `i`, first we need to deal with `i-1`. Define `P = i - dp(i-1) - 1`. Then we have the following situation:\n\n`...((.....))`\n\n`...P.......i`\n\nHere on the top is the structure of string and in the bottom are indexes. String from `P + 1` to `i - 1` indexes including is the longest valid parentheses endind with `i-1` place. What we can say about place `P`. If we have `)` element on this place, then we need to return `0`: in this case we have patten `...)(...))...` and we **know** that answer for `dp(P)` is equal to `0`: if it is not, what we considered was not the longest answer for `i-1`. And if answer for `dp(P)` is zero, than answer for `dp(i)` is zero as well.\nIn the case, when we have `...((.....))`, answer is `dp(i-1) + dp(P-1) + 2`. \n\n#### Complexity\nTime complexity is `O(n)`, space complexity as well.\n\n#### Code\n```python\nclass Solution:\n def longestValidParentheses(self, s):\n @lru_cache(None)\n def dp(i):\n if i == -1 or s[i] == "(": return 0\n if i >= 1 and s[i-1:i+1] == "()": return dp(i-2) + 2\n P = i - dp(i-1) - 1\n if P >= 0 and s[P] == "(":\n return dp(i-1) + dp(P-1) + 2\n return 0\n \n return max(dp(i) for i in range(len(s))) if s else 0\n```\n\nIf you have any question, feel free to ask. If you like the explanations, please **Upvote!**\n
3,045
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
40,981
229
```\npublic class Solution {\n public int longestValidParentheses(String s) {\n Stack<Integer> stack = new Stack<Integer>();\n int max=0;\n int left = -1;\n for(int j=0;j<s.length();j++){\n if(s.charAt(j)=='(') stack.push(j); \n else {\n if (stack.isEmpty()) left=j;\n else{\n stack.pop();\n if(stack.isEmpty()) max=Math.max(max,j-left);\n else max=Math.max(max,j-stack.peek());\n }\n }\n }\n return max;\n }\n}\n```
3,046
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,089
5
```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n stack<int> st;\n int n=s.size();\n for(int i=0;i<n;i++){\n if(st.empty()) st.push(i);\n else{\n if(s[i]==\'(\') st.push(i);\n else{\n if(s[st.top()]==\'(\') st.pop();\n else st.push(i);\n }\n }\n }\n int ans;\n if(!st.empty())\n ans=n-1 - st.top();\n else ans=n;\n while(!st.empty()){\n int a=st.top();\n st.pop();\n if(!st.empty())\n ans=max(ans,a-st.top() -1);\n else ans=max(ans,a-0);\n }\n return ans;\n }\n};
3,051
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
14,278
169
// **Stack solution 10ms** \nThe idea is simple, we only update the result (max) when we find a "pair". \nIf we find a pair. We throw this pair away and see how big the gap is between current and previous invalid. \nEX: "( )( )" \nstack: -1, 0, \nwhen we get to index 1 ")", the peek is "(" so we pop it out and see what's before "(". \nIn this example it's -1. So the gap is "current_index" - (-1) = 2. \n\nThe idea **only update the result (max) when we find a "pair"** and **push -1 to stack first** covered all edge cases. \n\n public class Solution {\n public int longestValidParentheses(String s) {\n LinkedList<Integer> stack = new LinkedList<>();\n int result = 0;\n stack.push(-1);\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == ')' && stack.size() > 1 && s.charAt(stack.peek()) == '(') {\n stack.pop();\n result = Math.max(result, i - stack.peek());\n } else {\n stack.push(i);\n }\n }\n return result;\n }\n }\n\n\n\n**//DP solution 4ms** \nThe idea is go through the string and use DP to store the longest valid parentheses at that point. \ntake example "()(())" \ni : [0,1,2,3,4,5] \ns : [( ,) ,( ,( ,) ,) ] \nDP:[0,2,0,0,2,6] \n\n1, We count all the \u2018(\u2018. \n2, If we find a \u2018)\u2019 and \u2018(\u2018 counter is not 0, we have at least a valid result size of 2. \u201c()" \n3, Check the the one before (i - 1). If DP[i - 1] is not 0 means we have something like this \u201c(())\u201d . This will have DP \u201c0024" \n4, We might have something before "(())\u201d. Take "()(())\u201d example, Check the i = 1 because this might be a consecutive valid string. \n\n public class Solution {\n public int longestValidParentheses(String s) {\n int[] dp = new int[s.length()];\n int result = 0;\n int leftCount = 0;\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == '(') {\n leftCount++;\n } else if (leftCount > 0){\n dp[i] = dp[i - 1] + 2;\n dp[i] += (i - dp[i]) >= 0 ? dp[i - dp[i]] : 0;\n result = Math.max(result, dp[i]);\n leftCount--;\n }\n }\n return result;\n }\n }
3,055
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
5,469
91
Rather than working with complex valid parenthesis strings, we just mark all of the occurences where an open parenthesis matches a close parenthesis. The idea is to then concatenate all of these individual valid parentheses to identify the longest valid streak of parentheses.\n\nFirst, we iterate through the string, keeping track of the indices of open parentheses in a stack. Every time we hit a close parenthesis, we know that the last open and the current close are both valid, so we mark both of these as being valid by overwriting them in the original string with `*`.\n\nOnce we have all of the valid individual parentheses marked, we iterate through the string once more and identify the longest sequence of `*`, which is our answer.\n```cpp\nint longestValidParentheses(string s) {\n\tstack<int> opens;\n\tfor(int i = 0; i < s.size(); i++) {\n\t\tif(s[i] == \'(\') opens.push(i);\n\t\telse if(opens.size()) {\n\t\t\ts[opens.top()] = s[i] = \'*\';\n\t\t\topens.pop();\n\t\t}\n\t}\n\n\tint curr = 0, res = 0;\n\tfor(int i = 0; i <= s.size(); i++) {\n\t\tif(s[i] == \'*\') curr++;\n\t\telse {\n\t\t\tres = max(res, curr);\n\t\t\tcurr = 0;\n\t\t}\n\t}\n\n\treturn max(curr, res);\n}\n```\n\n---\n\n**Alternate Solution:**\n\nTo reduce memory usage, we can take another approach. Scan the string from left to right, replacing any invalid parentheses with `*`. Then repeat the process, scanning from right to left. The string we\'re left with should have "pockets" of valid parentheses strings separated by `*`. We simply have to iterate through the string and count the longest stretch of parentheses.\n```\nint longestValidParentheses(string s, int res = 0) {\n\tfor (int i = 0, n = 0; i < s.size(); ++i)\n\t\tif (s[i] == \'(\') ++n;\n\t\telse if (!n--) s[i] = \'*\', n = 0;\n\tfor (int i = s.size() - 1, n = 0; i >= 0; --i) \n\t\tif (s[i] == \')\') ++n;\n\t\telse if (s[i] == \'*\') n = 0;\n\t\telse if (!n--) s[i] = \'*\', n = 0;\n\tfor (int i = 0, cur = 0; i < s.size(); ++i)\n\t\tif (s[i] != \'*\') res = max(res, ++cur);\n\t\telse cur = 0;\n\treturn res;\n}\n```
3,058
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
687
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n stack<int> stk; // Create a stack to keep track of indices\n stk.push(-1); // Initialize the stack with -1 as a base index\n int ans = 0; // Initialize the answer variable to store the maximum length\n\n for(int i = 0; i < s.size(); i++) {\n if(s[i] == \'(\')\n stk.push(i); // Push the index of an opening parenthesis onto the stack\n else {\n if(stk.size() == 1)\n stk.top() = i; // If stack contains only the base index, update it to the current index\n else {\n stk.pop(); // Pop the top index from the stack\n ans = max(ans, i - stk.top()); // Calculate the current valid length and update the answer\n }\n }\n }\n return ans; // Return the maximum valid length\n }\n};\n\n```
3,059
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
336
11
```\nclass Solution {\n func longestValidParentheses(_ s: String) -> Int {\n\t\tvar string = Array(s)\n\n\n\t\tfunc reverse(_ string: [Character]) -> [Character] {\n\t\t\tvar res: [Character] = []\n\t\t\tfor c in string.reversed() { res.append(c == "(" ? ")" : "(") }\n\t\t\treturn res\n\t\t}\n\t\t\n\n\t\tfunc _max(_ string: [Character]) -> Int {\n\t\t\tvar max = 0\n\t\t\tvar tmp = 0\n\t\t\tvar lastContinuousIndex = 0\n\t\t\tvar stack: [Character] = []\n\n\t\t\tfor (i, c) in string.enumerated() {\n\t\t\t\tif c == "(" {\n\t\t\t\t\tif stack.count == 0 { lastContinuousIndex = i }\n\t\t\t\t\tstack.append(c)\n\t\t\t\t} else {\n\t\t\t\t\tlet index = stack.count - 1\n\t\t\t\t\tif index >= 0 && stack[index] == "(" {\n\t\t\t\t\t\tstack.remove(at: index)\n\t\t\t\t\t\ttmp += 2\n\t\t\t\t\t\tmax = tmp > max ? tmp : max \n\t\t\t\t\t} else {\n\t\t\t\t\t\tstack.removeAll()\n\t\t\t\t\t\ttmp = 0\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (stack.count == 0) {\n\t\t\t\treturn max\n\t\t\t} else {\n\t\t\t\tlet a = _max(Array(string[0..<lastContinuousIndex]))\n\t\t\t\tlet b = _max(reverse(Array(string[lastContinuousIndex..<string.count])))\n\t\t\t\treturn a > b ? a : b\n\t\t\t}\n\t\t}\n\t\treturn _max(string)\n }\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful.
3,061
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,974
33
```swift\nclass Solution {\n func longestValidParentheses(_ s: String) -> Int {\n guard !s.isEmpty else { return 0 }\n var val = 0, stack = [-1]\n for (i, ch) in s.enumerated() {\n guard ch != "(" else { stack.append(i); continue }\n guard stack.count > 1 else { stack[0] = i; continue }\n stack.removeLast()\n val = max(val, i - stack.last!)\n }\n return val\n }\n}\n```\n\n<hr>\n\n<p><details>\n<summary><img src="" height="24"> <b>TEST CASES</b></summary>\n\n<p><pre>\nResult: Executed 3 tests, with 0 failures (0 unexpected) in 0.010 (0.012) seconds\n</pre></p>\n\n```swift\nimport XCTest\n\nclass Tests: XCTestCase {\n \n private let solution = Solution()\n \n // The longest valid parentheses substring is "()".\n func test0() {\n let res = solution.longestValidParentheses("(()")\n XCTAssertEqual(res, 2)\n }\n \n // The longest valid parentheses substring is "()()".\n func test1() {\n let res = solution.longestValidParentheses(")()())")\n XCTAssertEqual(res, 4)\n }\n \n func test2() {\n let res = solution.longestValidParentheses("")\n XCTAssertEqual(res, 0)\n }\n}\n\nTests.defaultTestSuite.run()\n```\n\n</details></p>
3,062
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
640
5
```\n\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int open=0, close=0;\n int maxLen=0;\n\t\t\n\t\t//traversing from left\n for(int i=0;i<s.size();i++){\n if(s[i]==\'(\'){\n open++;\n }\n else{\n close++;\n }\n\t\t\t//valid pair of paranthesis if number of opening and closing brackets are equal\n if(open==close){ \n int len=open+close;\n maxLen=max(maxLen,len);\n }\n\t\t\telse if(close>open){ //from left if closing brackets is greater than openin brackets\n close=0;\n open=0;\n }\n }\n \n open=0,close=0;\n \n\t\t//traversing from right\n for(int i=s.size()-1;i>=0;i--){\n if(s[i]==\'(\'){\n open++;\n }\n else{\n close++;\n }\n\t\t\t//valid pair of paranthesis if number of opening and closing brackets are equal\n if(open==close){\n int len=open+close;\n maxLen=max(maxLen,len);\n }\n else if(close<open){ //from right if opening brackets is greater than closing brackets\n close=0;\n open=0;\n } \n }\n return maxLen;\n }\n};\n//please upvote if found helpful\n```
3,066
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
5,619
80
- This solution is inspired by maximum sum of subsequence.\n\t- Let\'s recall the O(n) solution for that problem: we give up when the current sum < 0, set the sum = 0 and restart counting from the next number; and we records the maximum all the time.\n\t- In this problem, I use sum to indicate whether the expression is balanced:\n\t\t- +1 to represent \'(\' and -1 for \')\'; if sum == 0, then the substring is balanced;\n\t\t- sum < 0 means the expression is unbalanced, where I give up the current length and start again.\n\t- However, when we scan from left side, we can only find the expression unbalanced when \')\' appears too often, and \'(\' should also be checked for balance, so we should scan again from right side.\n\t- Total time complexity is O(n) as we scanned 2 times, and space complexity is O(1) as we don\'t record things in an array or stack:)\n```java\n\tpublic int longestValidParenthesesOnline(String s) {\n if (s == null) return -1;\n if (s.length() == 0) return 0;\n char[] str = s.toCharArray();\n int sum = 0, res = 0, len = 0, n = s.length();\n\t\t// Scan the string from left side, plus 1 for \'(\' and minus 1 for \')\'.\n for (int i = 0; i < n; i++) {\n if (str[i] == \'(\') sum++;\n else sum--;\n if (sum < 0) {\n sum = 0;\n len = 0;\n } else {\n len++;\n if (sum == 0) res = Math.max(res, len);\n }\n }\n\t\t// Scan again from right side, plus 1 for \')\' and minus 1 for \'(\'.\n sum = 0;\n len = 0;\n for (int i = n - 1; i >= 0; i--) {\n if (str[i] == \')\') sum++;\n else sum--;\n if (sum < 0) {\n sum = 0;\n len = 0;\n } else {\n len++;\n if (sum == 0) res = Math.max(res, len);\n }\n }\n return res;\n }
3,067
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,487
5
# Intuition\nUsed an Stack to find the longest valid parenthesis\n\n# Approach\nStack based approach using single while loop.\n\n# Complexity\n- Time complexity:\nTime complexity is 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 longestValidParentheses(String s) {\n Stack<Integer> st=new Stack<>();\n int ans=0;\n st.push(-1);\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==\'(\')\n st.push(i);\n else{\n if(!st.isEmpty())\n st.pop();\n if(!st.isEmpty())\n ans=Math.max(i-st.peek(),ans);\n else\n st.push(i);\n }\n }\n return ans;\n}\n}\n```
3,073
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,002
27
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nOne of the key things to realize about valid parentheses strings is that they\'re entirely self-satisfied, meaning that while you can have one substring that is entirely inside another, you can\'t have two substrings that only partially overlap.\n\nThis means that we can use a **greedy O(N) time complexity** solution to this problem without the need for any kind of backtracking. In fact, we should be able to use a very standard stack-based valid parentheses string algorithm with just three very minor modifications.\n\nIn a stadard valid parentheses string algorithm, we iterate through the string (**S**) and push the index (**i**) of any **\'(\'** to our **stack**. Whenever we find a **\')\'**, we match it with the last entry on the **stack** and pop said entry off. We know the string is not valid if we find a **\')\'** while there are no **\'(\'** indexes in the **stack** with which to match it, and also if we have leftover **\'(\'** in the **stack** when we reach the end of **S**.\n\nFor this problem, we will need to add in a step that updates our answer (**ans**) when we close a parentheses pair. Since we stored the index of the **\'(\'** in our stack, we can easily find the difference between the **\')\'** at **i** and the last entry in the **stack**, which should be the length of the valid substring which was just closed.\n\nBut here we run into a problem, because consecutive valid substrings can be grouped into a larger valid substring (ie, **\'()()\' = 4**). So instead of counting from the *last* **stack** entry, we should actually count from the *second to last* entry, to include any other valid closed substrings since the most recent **\'(\'** that will still remain after we pop the just-matched last **stack** entry off.\n\nThis, of course, brings us to the second and third changes. Since we\'re checking the second to last **stack** entry, what happens in the case of **\'()()\'** when you close the second valid substring yet there\'s only the one **stack** entry left at the time?\n\nTo avoid this issue, we can just wrap the entire string in another imaginary set of parentheses by starting with **stack = [-1]**, indicating that there\'s an imaginary **\'(\'** just before the beginning of the string at **i = 0**.\n\nThe other issue is that we will want to continue even if the string up to **i** becomes invalid due to a **\')\'** appearing when the **stack** is "empty", or in this case has only our imaginary index left. In that case, we can just effectively restart our **stack** by updating our imaginary **\'(\'** index (**stack[0] = i**) and continue on.\n\nThen, once we reach the end of **S**, we can just **return ans**.\n\n---\n\n#### ***Implementation:***\n\nThere are only minor differences in the code for all four languages.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **76ms / 39.9MB** (beats 99% / 78%).\n```javascript\nvar longestValidParentheses = function(S) {\n let stack = [-1], ans = 0\n for (let i = 0; i < S.length; i++)\n if (S[i] === \'(\') stack.push(i)\n else if (stack.length === 1) stack[0] = i\n else stack.pop(), ans = Math.max(ans, i - stack[stack.length-1])\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **40ms / 14.6MB** (beats 88% / 71%).\n```python\nclass Solution:\n def longestValidParentheses(self, S: str) -> int:\n stack, ans = [-1], 0\n for i in range(len(S)):\n if S[i] == \'(\': stack.append(i)\n elif len(stack) == 1: stack[0] = i\n else:\n stack.pop()\n ans = max(ans, i - stack[-1])\n return ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **2ms / 38.7MB** (beats 69% / 94%).\n```java\nclass Solution {\n public int longestValidParentheses(String S) {\n Stack<Integer> stack = new Stack<>();\n stack.push(-1);\n int ans = 0;\n for (int i = 0; i < S.length(); i++)\n if (S.charAt(i) == \'(\') stack.push(i);\n else {\n stack.pop();\n if (stack.isEmpty()) stack.push(i);\n else ans = Math.max(ans, i - stack.peek());\n }\n return ans;\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 7.1MB** (beats 100% / 71%).\n```c++\nclass Solution {\npublic:\n int longestValidParentheses(string S) {\n vector<int> stack = {-1};\n int ans = 0;\n for (int i = 0; i < S.size(); i++)\n if (S[i] == \'(\') stack.push_back(i);\n else if (stack.size() == 1) stack[0] = i;\n else {\n stack.pop_back();\n ans = max(ans, i - stack.back());\n }\n return ans;\n }\n};\n```
3,075
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
795
11
*Left* : keeps track of (\n*Right* : keeps track of )\n\nFor First Pass if *Right>Left* happens then they are re-initialized to zero as \')\' can\'t come before \'(\'\nSimilary,For Second Pass *Left>Right* happens then they are re-initialized to zero as \'(\' should come before \')\'\n\n\n\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s)\n {\n \n int n=s.size();\n int ans=0;\n int left=0,right=0;\n for(int i=0;i<n;i++)\n {\n if(s[i]==\')\')\n {\n right++;\n }\n else if(s[i]==\'(\')\n {\n left++;\n }\n if(left==right)\n {\n ans=max(left+right,ans);\n }\n else if(right>left)\n {\n left=right=0;\n }\n }\n \n left=right=0;\n \n for(int i=n-1;i>=0;i--)\n {\n if(s[i]==\'(\')\n {\n left++;\n }\n else if(s[i]==\')\')\n {\n right++;\n }\n if(left==right)\n {\n ans=max(left+right,ans);\n }\n else if(left>right)\n {\n left=right=0;\n }\n }\n \n return ans;\n }\n};\n```\n
3,076
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
293
6
\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int left=0,right=0,ansLeft=0,ansRight=0;\n \n // for left traversal \n for(int i=0;i<s.size();i++){\n if(s[i]==\'(\')\n left++;\n if(s[i]==\')\')\n right++;\n if(right>left) // if count of closing brackets becomes greater than opening bracket\n {\n right=0;\n left=0;\n }\n else if(right==left)\n ansLeft=max(ansLeft,left+right);\n }\n left=0;\n right=0;\n // for right traversal\n for(int i=s.size()-1;i>=0;i--){\n if(s[i]==\'(\')\n left++;\n if(s[i]==\')\')\n right++;\n if(left>right) // if count of opening brackets becomes greater than closing bracket\n { \n left=0;\n right=0;\n }\n else if(left==right)\n ansRight=max(ansRight,left+right);\n }\n return max(ansLeft,ansRight);\n }\n};\n```
3,078
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
12,746
125
let dp[i] is the number of longest valid Parentheses ended with the i - 1 position of s, then we have the following relationship:\ndp[i + 1] = dp[p] + i - p + 1 where p is the position of '(' which can matches current ')' in the stack.\n\n def longestValidParentheses(self, s):\n dp, stack = [0]*(len(s) + 1), []\n for i in range(len(s)):\n if s[i] == '(':\n stack.append(i)\n else:\n if stack:\n p = stack.pop()\n dp[i + 1] = dp[p] + i - p + 1\n return max(dp)
3,079
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
2,168
7
# Using Stack:\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n stack=[]\n stack.append(-1)\n ans=0\n for i in range(len(s)):\n if s[i]==\'(\':\n stack.append(i)\n else:\n stack.pop()\n if len(stack)==0:\n stack.append(i)\n ans=max(ans,i-stack[-1])\n return ans\n```\n# without Space complexity:\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n open,close,ans=0,0,0\n for i in s:\n if i=="(":\n open+=1\n else:\n close+=1\n if close==open:\n ans=max(ans,close+open)\n elif close>open:\n open=close=0\n open=close=0\n for i in range(len(s)-1,-1,-1):\n if "("==s[i]:\n open+=1\n else:\n close+=1\n if close==open:\n ans=max(ans,close+open)\n elif open>close:\n open=close=0\n return ans\n```
3,082
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
7,161
64
```\nclass Solution:\n def longestValidParentheses(self, s):\n """\n :type s: str\n :rtype: int\n """\n stack = [0]\n longest = 0\n \n for c in s:\n if c == "(":\n stack.append(0)\n else:\n if len(stack) > 1:\n val = stack.pop()\n stack[-1] += val + 2\n longest = max(longest, stack[-1])\n else:\n stack = [0]\n\n return longest\n```
3,083
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
606
5
**Brute Force O(n) Space:**\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n st=[-1]\n m=0\n for i in range(len(s)):\n if s[i]==\'(\':\n st.append(i)\n else:\n st.pop()\n if not st: #if -1 is popped\n st.append(i)\n else:\n m=max(m,i-st[-1])\n return m\n```\n**Optimized Solution O(1) Space:**\n```\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n l=r=m=0\n for i in range(len(s)):\n if s[i]==\'(\':\n l+=1\n else:\n r+=1\n if l==r: #for balanced parantheses\n m=max(m,l+r)\n elif r>l: #invalid case\n l=r=0\n l=r=0\n# We are traversing right to left for the test case where opening brackets are more than closing brackets. eg: s = "(()"\n for i in range(len(s)-1,-1,-1):\n if s[i]==\'(\':\n l+=1\n else:\n r+=1\n if l==r: #for balanced parantheses\n m=max(m,l+r)\n elif l>r: #invalid case\n l=r=0 \n return m\n```\n**An upvote will be encouraging**
3,088
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
2,604
5
````\n//IN THIS PROBLEM I FIND LONGEST LONGEST VALID PRENTHESIS SUBSTRING\nclass Solution\n{\npublic:\n int longestValidParentheses(string s)\n {\n vector<int> v;\n for (int i = 0; i < s.length(); i++)\n {\n if (s[i] == \'(\')\n {\n v.push_back(i);\n }\n else\n {\n if (v.size() > 0 && s[v.back()] == \'(\')\n {\n v.pop_back();\n }\n else\n {\n v.push_back(i);\n }\n }\n }\n if (v.size() == 0)//ARRAY WE STORE INDICES WHERE OUR SUBSTRINGS WILL BE INCOREECT & EXTRA OPENING BRACKET\'S INDICES\n return s.length();\n int ans = 0, a = 0, b = s.length();\n while (v.size() > 0)\n {\n a = v.back();\n v.pop_back();\n ans = max(ans, b - a - 1);\n b = a;\n }\n ans = max(ans,b);\n return ans;\n }\n};\n````
3,089
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,310
5
```\npublic class Solution {\n public int longestValidParentheses(String s) {\n int left = 0, right = 0, maxlength = 0;\n \n for (int i = 0; i < s.length(); i++) \n {\n if (s.charAt(i) == \'(\') left++;\n else right++;\n \n if (left == right) {\n maxlength = Math.max(maxlength, 2 * right);\n } else if (right >= left) {\n left = right = 0;\n }\n }\n \n left = right = 0;\n for (int i = s.length() - 1; i >= 0; i--) {\n \n if (s.charAt(i) == \'(\') left++;\n else right++;\n \n if (left == right) {\n maxlength = Math.max(maxlength, 2 * left);\n } else if (left >= right) {\n left = right = 0;\n }\n }\n \n return maxlength;\n }\n}\n```\n\n**Using Stack**\n\n```\npublic class Solution {\n public int longestValidParentheses(String s) {\n Stack <Integer> stack = new Stack<>();\n int result = 0;\n stack.push(-1);\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == \')\' && stack.size() > 1 && s.charAt(stack.peek()) == \'(\') {\n stack.pop();\n result = Math.max(result, i - stack.peek());\n } else {\n stack.push(i);\n }\n }\n return result;\n }\n}\n```\n**Using DP**\n```\npublic class Solution {\n public int longestValidParentheses(String s) {\n int[] dp = new int[s.length()];\n int result = 0;\n int leftCount = 0;\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == \'(\') {\n leftCount++;\n } else if (leftCount > 0){\n dp[i] = dp[i - 1] + 2;\n dp[i] += (i - dp[i]) >= 0 ? dp[i - dp[i]] : 0;\n result = Math.max(result, dp[i]);\n leftCount--;\n }\n }\n return result;\n }\n}\n```
3,091
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
347
5
#### Table of Contents\n\n- [TL;DR](#tldr)\n - [Code](#code)\n - [Complexity](#complexity)\n- [In Depth Analysis](#in-depth-analysis)\n - [Intuition](#intuition)\n - [Approach](#approach)\n - [Example](#example)\n\n# TL;DR\n\nAll we want to do is scan the string from start to finish and use a stack to figure out if the index we are still looking at is a valid parenthesis\n\nIn other words, we want to push the indices of the opening brackets and if you encounter a closing bracket, then we calculate how long was this valid parenthesis (assuming that the stack is not empty) and update the ans if it is longer than the current best\n\n## Code\n\n```c++\n#define OPEN_BRACKET \'(\'\n\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n const int n = s.size();\n int ans = 0;\n stack<int> brackets;\n brackets.push(-1);\n for (int i = 0; i < n; i++) {\n if (s[i] == OPEN_BRACKET)\n brackets.push(i);\n else {\n brackets.pop();\n if (brackets.empty())\n brackets.push(i);\n else\n ans = max(ans, i - brackets.top());\n }\n }\n\n return ans;\n }\n};\n\n```\n\n## Complexity\n\n**Time Complexity:** $$O(N)$$\n**Space Complexity:** $$O(N)$$\n\n**PLEASE UPVOTE IF YOU FIND MY POST HELPFUL!! \uD83E\uDD7A\uD83D\uDE01**\n\n---\n\n# In Depth Analysis\n\n## Intuition\n\nThis is a modified version of the valid parenthesis problem\n\nWe initially push `-1` onto the stack because it is to indicate the last location of a valid parenthesis. At first, the last valid parenthesis finished at index `-1`. Then, every time we encounter an opening bracket, we want to push that onto the stack too. \n\nIf it isn\'t an opening bracket (aka closing bracket), we want to pop off the stack. If the stack is not empty, that means we have encountered a valid parenthesis and the stack\'s current top is the position before the start of the valid string. Therefore, taking the difference between the current index and the stack\'s top will yield the length of the valid string and we update the answer if it is longer than the current best.\n\nIf the stack is empty, that means that we have no idea where the next valid parenthesis set is (since we always compare it to the stack\'s top element). Therefore, we just push the current index onto the stack to indicate the location of the last valid parenthesis.\n\n## Approach \n\nWe initialize push `-1` onto a stack and we iterate through all the characters in `s`. If the current character is a open bracket, push the index onto the stack. Otherwise, we pop off of the top. If the stack then becomes empty, we push the current index onto the stack. Otherwise, we update the answer to be the difference between the current index and the current stack top\'s value\n\n## Example\n\nLets use the second example, where `s = ")()())"`\n\nFirst, we push `-1` onto the stack since that the last valid location so far\n\n* i = 0\nStack = [-1] <-- TOP\nAns = 0\n\n`s[0] = \')\'`, so we pop off of the stack. Since it is empty now, we push `i = 0` onto the stack\n\n* i = 1\nStack = [0] <-- TOP\nAns = 0\n\n`s[1] = \'(\'`, so we push `i = 1` onto the stack\n\n* i = 2\nStack = [0,1] <-- TOP\nAns = 0\n\n`s[2] = \')\'`, so we pop off of the stack (`1`). Then, we update ans to be the max between itself and `i - stack.top() = 2 - 0 = 2`\n\n* i = 3\nStack = [0] <-- TOP\nAns = 2\n\n`s[3] = \'(\'`, so push `i = 3` onto the stack\n\n* i = 4\nStack = [0,3] <-- TOP\nAns = 2\n\n`s[4] = \')\'`, so we pop off of the stack (`3`). Then, we update ans to be the max between itself and `i - stack.top() = 4 - 0 = 4`\n\n* i = 5\nStack = [0] <-- TOP\nAns = 4\n\n`s[5] = \')\'`, so we pop off of the stack (`0`). Since the stack is empty now, then we push `i = 5` onto the stack\n\n* Aftermath\n\nWe return 4, which is the correct answer\n\n**PLEASE UPVOTE IF YOU FIND MY POST HELPFUL!! \uD83E\uDD7A\uD83D\uDE01**
3,093
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
String,Dynamic Programming,Stack
Hard
null
1,389
31
### Intuition\n\nBefore explaining the solution, I will write how I came up with the solution.\n\nThe main point to notice in this problem is that the moment we get an invalid parenthesis, the subarray can\'t start from beyond this point.\nNot clear ? Let\'s understand with an example.\n\nConsider this simple string.\n```()()))()(())```, at index 4 the subarray starting from index 0 becomes invalid, it is clear the longest valid parenthesis won\'t start from [0, 3] and end after 4.\n\nThis striked me that I can use a sliding window to solve this problem.\n\n### How to solve ?\n\nConsider a window with left end shown by **i** and right end shown by **j**.\nInitially **i = 0 and j = 0**\nLet us consider another variable k which will help us to determine when subarray becomes invalid.\n\nNow, we start moving j keeping i as fixed. \n\nIncrement k when we encounter ```(``` and decrement when we encounter ```)```.\n\nWhenever k becomes zero we will update our answer with max(ans, j - i + 1)\nIt is clear when k becomes negative the subarray will become invalid, so we will move the left end i.e **i** to the new position.\n\n**Question**\nWhy are we updating the answer when k is 0 and not when k > 0.\n**Answer**\nWe know for sure, whenever we get k as 0 the subarray is valid and length will be j - i + 1.\nBut when k > 0 the subarray is still valid, but the length will be less than j - i + 1.\nBut ofcourse we are missing some values, since the length which is less j - i + 1 can be a better answer.\n\nConsider this string ```(()```. Here, we will never get k = 0 and hence we can\'t update our answer.\n\n**How to resolve this?**\nWe have to repeat the above process but this time starting i = n - 1 and j = n - 1. Now, keep moving j to the left side and do the same as above. Here k will increase when we encounter ```)``` and decrease when we encounter ```(```.\n\n### Cpp Code\n\n```\nclass Solution {\npublic:\n int longestValidParentheses(string s) {\n int n = s.length(), i = 0, ans = 0, k = 0;\n for(int j = 0; j < n; j++) {\n if(s[j] == \'(\') k++;\n else if(s[j] == \')\') {\n k--;\n if(k == 0)\n ans = max(ans, j - i + 1);\n }\n if(k < 0) {\n k = 0;\n i = j + 1;\n }\n }\n k = 0, i = n - 1;\n for(int j = n - 1; j >= 0; j--) {\n if(s[j] == \')\') {\n k++;\n }\n else if(s[j] == \'(\') {\n k--;\n if(k == 0)\n ans = max(ans, i - j + 1);\n }\n if(k < 0) {\n k = 0;\n i = j - 1;\n }\n }\n return ans;\n }\n};\n```\n\n**Please upvote if this post is helpful to you :)**
3,094
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
48,470
262
# Problem Understanding\n\nThe task is to search for a target integer in a sorted array that has been rotated at an unknown pivot. \n\nFor instance, the array $$[0,1,2,4,5,6,7]$$ could be rotated at the 4th position to give $$[4,5,6,7,0,1,2]$$. The challenge is to find the position of the target integer in this rotated array. \n\n![example.png]()\n\n- The top section shows the `nums` array with a red rectangle highlighting the current "mid" value being considered in each step.\n- The bottom section displays a table that presents the steps of the binary search. Each row corresponds to a step, detailing:\n - The step number.\n - The indices of the low (L), mid (M), and high (R) pointers.\n - The values at the low (L), mid (M), and high (R) positions.\n\n# Live Coding & Explenation\n\n\n# Approach\n\nGiven the properties of the array, it\'s tempting to perform a linear search. However, that would result in a time complexity of $$O(n)$$. Instead, we can use the properties of the array to our advantage and apply a binary search to find the target with time complexity of $$ O(\\log n) $$ only.\n\n## Treating the Rotated Array\n\nAlthough the array is rotated, it retains some properties of sorted arrays that we can leverage. Specifically, one half of the array (either the left or the right) will always be sorted. This means we can still apply binary search by determining which half of our array is sorted and whether the target lies within it.\n\n## Binary Search\n\nBinary search is an efficient algorithm for finding a target value within a sorted list. It works by repeatedly dividing the search interval in half. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.\n\n## Initialization\n\nWe start with two pointers:\n\n- $$ \\text{left} $$ - This represents the beginning of the array. We initialize it to 0, the index of the first element.\n- $$ \\text{right} $$ - This represents the end of the array. It\'s set to $$ n - 1 $$, the index of the last element, where $$ n $$ is the length of the array.\n\n## Iterative Binary Search\n\nWe perform the binary search within a while loop until $$ \\text{left} $$ exceeds $$ \\text{right} $$. In each iteration, we calculate the midpoint between $$ \\text{left} $$ and $$ \\text{right} $$.\n\n### Deciding the Sorted Half:\n\nAt any point during the search in the rotated array, one half (either the left or the right) will always be sorted. Determining which half is sorted is crucial for our modified binary search. \n\n- **If left half $$[low...mid]$$ is sorted**: We know this if the element at $$ \\text{low} $$ is less than or equal to the element at $$ \\text{mid} $$. In a normally sorted array, if the start is less than or equal to the midpoint, it means all elements till the midpoint are in the correct increasing order.\n\n - **If the target lies within this sorted left half**: We know this if the target is greater than or equal to the element at $$ \\text{low} $$ and less than the element at $$ \\text{mid} $$. If this is the case, we then move our search to this half, meaning, we update $$ \\text{high} $$ to $$ \\text{mid} - 1 $$.\n\n - **Otherwise**: The target must be in the right half. So, we update $$ \\text{low} $$ to $$ \\text{mid} + 1 $$.\n\n- **If right half $$[mid...high]$$ is sorted**: This is the else part. If the left half isn\'t sorted, the right half must be!\n\n - **If the target lies within this sorted right half**: We know this if the target is greater than the element at $$ \\text{mid} $$ and less than or equal to the element at $$ \\text{high} $$. If so, we move our search to this half by updating $$ \\text{low} $$ to $$ \\text{mid} + 1 $$.\n\n - **Otherwise**: The target must be in the left half. So, we update $$ \\text{high} $$ to $$ \\text{mid} - 1 $$.\n\n### Rationale:\n\nThe beauty of this approach lies in its ability to determine with certainty which half of the array to look in, even though the array is rotated. By checking which half of the array is sorted and then using the sorted property to determine if the target lies in that half, we can effectively eliminate half of the array from consideration at each step, maintaining the $$ O(\\log n) $$ time complexity of the binary search.\n\n## Complexity\n\n**Time Complexity**: The time complexity is $$ O(\\log n) $$ since we\'re performing a binary search over the elements of the array.\n\n**Space Complexity**: The space complexity is $$ O(1) $$ because we only use a constant amount of space to store our variables ($$ \\text{left} $$, $$\\text{right} $$, $$ \\text{mid} $$), regardless of the size of the input array.\n\n# Performance\n\n![33-per.png]()\n\n\n# Code\n\n``` Python []\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n left, right = 0, len(nums) - 1\n\n while left <= right:\n mid = (left + right) // 2\n\n if nums[mid] == target:\n return mid\n\n # Check if left half is sorted\n if nums[left] <= nums[mid]:\n if nums[left] <= target < nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n # Otherwise, right half is sorted\n else:\n if nums[mid] < target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n\n return -1\n```\n``` C++ []\nclass Solution {\npublic:\n int search(std::vector<int>& nums, int target) {\n int low = 0, high = nums.size() - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n\n if (nums[mid] == target) {\n return mid;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n return -1;\n }\n};\n```\n``` Go []\nfunc search(nums []int, target int) int {\n low, high := 0, len(nums) - 1\n\n for low <= high {\n mid := (low + high) / 2\n\n if nums[mid] == target {\n return mid\n }\n\n if nums[low] <= nums[mid] {\n if nums[low] <= target && target < nums[mid] {\n high = mid - 1\n } else {\n low = mid + 1\n }\n } else {\n if nums[mid] < target && target <= nums[high] {\n low = mid + 1\n } else {\n high = mid - 1\n }\n }\n }\n\n return -1\n}\n```\n``` Rust []\nimpl Solution {\n pub fn search(nums: Vec<i32>, target: i32) -> i32 {\n let mut low = 0;\n let mut high = nums.len() as i32 - 1;\n\n while low <= high {\n let mid = (low + high) / 2;\n\n if nums[mid as usize] == target {\n return mid;\n }\n\n if nums[low as usize] <= nums[mid as usize] {\n if nums[low as usize] <= target && target < nums[mid as usize] {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if nums[mid as usize] < target && target <= nums[high as usize] {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n -1\n }\n}\n```\n``` Java []\nclass Solution {\n public int search(int[] nums, int target) {\n int low = 0, high = nums.length - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n\n if (nums[mid] == target) {\n return mid;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n return -1;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nvar search = function(nums, target) {\n let low = 0, high = nums.length - 1;\n\n while (low <= high) {\n let mid = Math.floor((low + high) / 2);\n\n if (nums[mid] === target) {\n return mid;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n return -1;\n};\n```\n``` C# []\npublic class Solution {\n public int Search(int[] nums, int target) {\n int low = 0, high = nums.Length - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n\n if (nums[mid] == target) {\n return mid;\n }\n\n if (nums[low] <= nums[mid]) {\n if (nums[low] <= target && target < nums[mid]) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if (nums[mid] < target && target <= nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n return -1;\n }\n}\n```\n\nI hope this explanation provides clarity on the "Search in Rotated Sorted Array" problem. If you have any more questions, feel free to ask! If you found this helpful, consider giving it a thumbs up. Happy coding! \uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDE80\uD83D\uDC68\u200D\uD83D\uDCBB
3,100
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,466
6
<iframe width="560" height="315" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n public int search(int[] A, int B) {\n int l = 0;\n int r = A.length-1;\n int m;\n while(l<=r){\n m = (l+r)/2;\n if(A[m] == B) return m;\n if(A[m]>=A[0]){\n if(B>=A[0] && B<=A[m]) r = m-1;\n else l = m+1;\n }else{\n if(B>=A[m] && B<=A[A.length-1]) l = m+1;\n else r = m-1;\n }\n\n }\n return -1;\n }\n}\n```\n\n```\nclass Solution {\npublic:\n int search(vector<int>& A, int B) {\n int l = 0;\n int r = A.size() - 1;\n int m;\n while (l <= r) {\n m = (l + r) / 2;\n if (A[m] == B) return m;\n if (A[m] >= A[0]) {\n if (B >= A[0] && B <= A[m]) r = m - 1;\n else l = m + 1;\n } else {\n if (B >= A[m] && B <= A[A.size() - 1]) l = m + 1;\n else r = m - 1;\n }\n }\n return -1;\n }\n};\n```\n\n```\nclass Solution:\n def search(self, A: List[int], B: int) -> int:\n l = 0\n r = len(A) - 1\n while l <= r:\n m = (l + r) // 2\n if A[m] == B:\n return m\n if A[m] >= A[0]:\n if B >= A[0] and B <= A[m]:\n r = m - 1\n else:\n l = m + 1\n else:\n if B >= A[m] and B <= A[-1]:\n l = m + 1\n else:\n r = m - 1\n return -1\n\n```
3,116
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
2,405
24
# Intuition & Approach\n- Explained in the code.\n\n# Code\n```\nclass Solution\n{\n public:\n \tLOGIC\n\n \tAPPROACH-1\n \t1.Simplest way is to traverse the array and find that number.\n \tO(N)\n\n \tAPPROACH-2(BINARY SEARCH)\n \t1.Why? Binary Search is used when\n \t-Array is Sorted\n \t- for finding target we have to eliminate the half\n \t- reduces the search space by half\n \t2. Here whole array is not sorted but we can figure out 2 sorted halves.\n \t3 We just have to identify the sorted half and eliminate the other half\n\n \tlow--------mid----T----high\n \t4.Like in the above case the target is in the 2nd half then we will eliminate the first half completely.\n \t5.So Binary Search is applied in halves.\n\n \tTC\n \tO(logn)\n//-------------------------------------------------------------------------------------------------------------------------\n int search(vector<int> &nums, int target)\n {\n int n = nums.size();\n int low = 0;\n int high = n - 1;\n while (low <= high)\n {\n int mid = (low + high) / 2;\n if (nums[mid] == target)\n return mid;\n \t//Index found\n else if (nums[low] <= nums[mid])\n \t//Left half\n {\n if (nums[low] <= target && target <= nums[mid])\n {\n //right half eliminated\n high = mid - 1;\n }\n else\n \t//left half eliminated\n {\n low = mid + 1;\n }\n }\n else\n {\n \t//right half\n if (nums[mid] <= target && target <= nums[high])\n \t//left half eliminated\n {\n low = mid + 1;\n }\n \t//right half eliminated\n else\n {\n high = mid - 1;\n }\n }\n }\n //Index not found\n return -1;\n }\n};\n```\n# Complexity\n- Time complexity:$O(logn)$ Binary Search\n\n- Space complexity:$O(1)$\n\nIf you *like* \uD83D\uDC4D this solution do *upvote* \u2B06\uFE0F and if there is any *improvement or suggestion* do mention it in the *comment* section \uD83D\uDE0A.\n\n<p align="center">\n<img src="" width=\'350\' alt="Upvote Image">\n</p>\n\n
3,119
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
903
8
**Connect with me on LinkedIn**: \n\n![image]()\n\n**Approach:**\n* identify in which segment our current *mid* is present \n* Present in left segment: a[m]>a[n-1]\n\t* Move right side: if target is in right segment or target is greater than mid\n\t* else move left\n* Present in right segment: a[m]<a[n-1]\n\t* Move left side: if target is in left segment or target is smaller than mid\n\t* else move right\n\n```\nclass Solution {\npublic:\n int search(vector<int>& a, int target) {\n int n=a.size();\n int l=0, r=n-1;\n \n while(l<=r){\n int m=(l+r)/2;\n if(a[m]==target) return m;\n if(a[m]>a[n-1]){ // left side of peak element\n if(target>a[m] || target<a[0]){\n l=m+1;\n }else{\n r=m-1;\n }\n }else{ // right side of peak element\n if(target<a[m] || target>a[n-1]){\n r=m-1;\n }else{\n l=m+1;\n }\n }\n }\n return -1;\n }\n};\n```\n\n**Do upvote if it helps :)**
3,120
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
22,336
137
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe function search takes in a vector nums representing the rotated sorted array and an integer target that we need to find.\nIt initializes the variables left and right to the start and end indices of the array, respectively.\nThe variable mid is calculated as the middle index of the array using the formula (left + right) / 2.\nThe while loop is executed as long as the left pointer is less than or equal to the right pointer. This ensures that the search space is not empty.\nInside the while loop, we check if the middle element nums[mid] is equal to the target. If it is, we return the index mid.\nIf the middle element is greater than or equal to the left element, it means the left part of the array is non-rotated.\nWe then check if the target is within the range of the left non-rotated part. If it is, we update the right pointer to mid - 1 to search in the left part.\nIf the target is not within the range, we update the left pointer to mid + 1 to search in the right part.\nIf the middle element is less than the left element, it means the right part of the array is rotated.\nWe then check if the target is within the range of the right rotated part. If it is, we update the left pointer to mid + 1 to search in the right part.\nIf the target is not within the range, we update the right pointer to mid - 1 to search in the left part.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(log n)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int search(vector<int>& nums, int target) {\n int n = nums.size();\n int left = 0;\n int right = n-1;\n int mid= left + (right - left) / 2;\n while(left <= right){\n if(nums[mid] == target)\n return mid;\n if(nums[mid] >= nums[left]) {\n if(target >= nums[left] && target <= nums[mid])\n {\n right = mid - 1;\n }\n else left = mid + 1;\n } \n else {\n if(target >= nums[mid] && target <= nums[right]) \n left = mid + 1;\n else right = mid - 1;\n }\n mid = left + (right - left) / 2;\n }\n return -1;\n }\n};\n```\n![upvote 1.jpeg]()\n\n\n\n
3,121
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,677
8
# Intuition\nIntuition\nhey every one i have made video playlist for binary search where i discuss a template solution and intuition behind it, this template solution will be very useful as this will help you solve many other questions in binary search this question is the part of that playlist:\nVideo link for question:\n\n\nPlaylist ink: \n\n\n\n# Code\n```\nclass Solution {\npublic:\n // 4 5 6 7 0 1 2 \n\n bool predicate(int mid,vector<int>& nums, int target){\n int val;\n if(target< nums[0] == nums[mid]<nums[0]){\n val=nums[mid];\n }\n else{\n if(target<nums[0]){\n val=INT_MIN;\n }\n else{\n val=INT_MAX;\n }\n }\n return val>=target;\n\n }\n int search(vector<int>& nums, int target) {\n int left=0;\n int right=nums.size()-1;\n while(left<right){\n int mid= left+ (right-left)/2;\n if(predicate(mid,nums,target)){\n right=mid;\n }\n else{\n left=mid+1;\n }\n }\n return nums[left]==target ? left:-1;\n }\n};\n```
3,122
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
409,347
1,679
class Solution {\n public:\n int search(int A[], int n, int target) {\n int lo=0,hi=n-1;\n // find the index of the smallest value using binary search.\n // Loop will terminate since mid < hi, and lo or hi will shrink by at least 1.\n // Proof by contradiction that mid < hi: if mid==hi, then lo==hi and loop would have been terminated.\n while(lo<hi){\n int mid=(lo+hi)/2;\n if(A[mid]>A[hi]) lo=mid+1;\n else hi=mid;\n }\n // lo==hi is the index of the smallest value and also the number of places rotated.\n int rot=lo;\n lo=0;hi=n-1;\n // The usual binary search and accounting for rotation.\n while(lo<=hi){\n int mid=(lo+hi)/2;\n int realmid=(mid+rot)%n;\n if(A[realmid]==target)return realmid;\n if(A[realmid]<target)lo=mid+1;\n else hi=mid-1;\n }\n return -1;\n }\n };
3,123
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
206,666
1,376
This very nice idea is from [rantos22\'s solution]() who sadly only commented *"You are not expected to understand that :)"*, which I guess is the reason it\'s now it\'s hidden among the most downvoted solutions. I present an explanation and a more usual implementation.\n\n---\n\n**Explanation**\n\nLet\'s say `nums` looks like this: [12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n\nBecause it\'s not fully sorted, we can\'t do normal binary search. But here comes the trick:\n\n- If target is let\'s say 14, then we adjust `nums` to this, where "inf" means infinity: \n[12, 13, 14, 15, 16, 17, 18, 19, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf, inf] \n\n- If target is let\'s say 7, then we adjust `nums` to this: \n[-inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n\nAnd then we can simply do ordinary binary search.\n\nOf course we don\'t actually adjust the whole array but instead adjust only on the fly only the elements we look at. And the adjustment is done by comparing both the target and the actual element against nums[0].\n\n---\n\n**Code**\n\nIf `nums[mid]` and `target` are *"on the same side"* of `nums[0]`, we just take `nums[mid]`. Otherwise we use -infinity or +infinity as needed.\n\n int search(vector<int>& nums, int target) {\n int lo = 0, hi = nums.size();\n while (lo < hi) {\n int mid = (lo + hi) / 2;\n \n double num = (nums[mid] < nums[0]) == (target < nums[0])\n ? nums[mid]\n : target < nums[0] ? -INFINITY : INFINITY;\n \n if (num < target)\n lo = mid + 1;\n else if (num > target)\n hi = mid;\n else\n return mid;\n }\n return -1;\n }
3,137
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
6,143
24
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code is implementing the Binary Search algorithm to find an element in a rotated sorted array. The approach to solving this problem is to modify the regular Binary Search algorithm to handle the rotated sorted array.\n\nThe intuition behind this approach is that the rotated sorted array can be divided into two parts, one part is still sorted, and the other part is also sorted, but the minimum element of the array is somewhere in the middle of the array. We can identify which part of the array is still sorted by comparing the middle element of the array with the first element of the array. If the middle element is greater than or equal to the first element, then the left part of the array is sorted, and if the middle element is less than the first element, then the right part of the array is sorted.\n\nOnce we have identified which part of the array is sorted, we can check if the target element is present in the sorted part of the array using the regular Binary Search algorithm. If the target element is not present in the sorted part of the array, we can search for it in the other part of the array by recursively calling the same Binary Search algorithm on that part.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(log n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n\n \n int search(vector<int>& nums, int target) {\n int size=nums.size();\n int s=0,e=size-1,m=0;\n while(s<=e){\n m=s+(e-s)/2;\n if(nums[m]==target) return m;\n if(nums[m]>=nums[s]){\n if(nums[m]>=target && nums[s]<=target) e=m-1;\n else s=m+1;}\n else{\n if(nums[m]<=target && nums[e]>=target) s=m+1;\n else e=m-1;\n }\n }\n return -1;\n \n\n \n }\n};\n```
3,138
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
32,004
90
# Intuition:\nThe given problem asks us to find the index of the target element in the given rotated sorted array.\n\n# Approach:\n- The solution provided in the code implements two approaches, Brute force and Binary search.\n\n - The Brute force approach: \n 1. Iterates through the array and checks if the current element is equal to the target. If it is, then it returns the index of that element, otherwise, it returns -1. This approach has a time complexity of O(n).\n\n - The Binary search approach is based on the fact that a rotated sorted array can be divided into two sorted arrays.\n 1. The approach starts with finding the mid element and compares it with the target element. \n 2. If they are equal, it returns the mid index. If the left half of the array is sorted, then it checks if the target lies between the start and the mid, and updates the end pointer accordingly. \n 3. Otherwise, it checks if the target lies between mid and end, and updates the start pointer accordingly. \n 4. If the right half of the array is sorted, then it checks if the target lies between mid and end, and updates the start pointer accordingly. \n 5. Otherwise, it checks if the target lies between start and mid, and updates the end pointer accordingly. \n 6. This process continues until the target element is found, or the start pointer becomes greater than the end pointer, in which case it returns -1. \n 7. This approach has a time complexity of O(log n).\n\n# Complexity:\n\n- Time Complexity:\n 1. The time complexity of the Brute force approach is O(n), where n is the size of the input array.\n 2. The time complexity of the Binary search approach is O(log n), where n is the size of the input array.\n\n- Space Complexity:\nThe space complexity of both approaches is O(1) as we are not using any extra space to store any intermediate results.\n\n---\n\n\n# Code: C++\n## Brute Force:\n```\nclass Solution {\npublic:\n int search(vector<int>& nums, int target) {\n for(int i=0;i<nums.size();i++){\n if(target==nums[i]){\n return i;\n }\n }\n return -1;\n }\n};\n```\n## Binary Search:\n```\nclass Solution {\npublic:\n int search(vector<int>& nums, int target) {\n int start=0,end=nums.size()-1;\n int mid= (start+end)/2;\n while(start<=end){\n mid=(start+end)/2;\n if(target==nums[mid]){\n return mid;\n }\n if(nums[start]<=nums[mid]){\n if(nums[start]<=target && nums[mid]>=target){\n end=mid-1;\n }\n else{\n start=mid+1;\n }\n }\n else{\n if(nums[end]>=target && nums[mid]<=target){\n start=mid+1;\n }\n else{\n end=mid-1;\n }\n }\n }\n return -1;\n }\n};\n\n```\n\n---\n\n# Code: Java\n## Binary Search:\n```\nclass Solution {\n public int search(int[] nums, int target) {\n int start = 0, end = nums.length - 1;\n int mid = (start + end) / 2;\n while (start <= end) {\n mid = (start + end) / 2;\n if (target == nums[mid]) {\n return mid;\n }\n if (nums[start] <= nums[mid]) {\n if (nums[start] <= target && nums[mid] >= target) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n } else {\n if (nums[end] >= target && nums[mid] <= target) {\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n }\n }\n return -1;\n }\n}\n\n```\n\n---\n\n# Code: Python\n## Binary Search:\n```\nclass Solution:\n def search(self, nums, target):\n start, end = 0, len(nums) - 1\n mid = (start + end) / 2\n while start <= end:\n mid = (start + end) / 2\n if target == nums[mid]:\n return mid\n if nums[start] <= nums[mid]:\n if nums[start] <= target and nums[mid] >= target:\n end = mid - 1\n else:\n start = mid + 1\n else:\n if nums[end] >= target and nums[mid] <= target:\n start = mid + 1\n else:\n end = mid - 1\n return -1\n\n```\n\n---\n\n# Code: JavaScript\n## Binary Search:\n```\nvar search = function(nums, target) {\n let start = 0, end = nums.length - 1;\n let mid = Math.floor((start + end) / 2);\n while (start <= end) {\n mid = Math.floor((start + end) / 2);\n if (target === nums[mid]) {\n return mid;\n }\n if (nums[start] <= nums[mid]) {\n if (nums[start] <= target && nums[mid] >= target) {\n end = mid - 1;\n } else {\n start = mid + 1;\n }\n } else {\n if (nums[end] >= target && nums[mid] <= target) {\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n }\n }\n return -1;\n}\n\n```\n> # ***Thanks For Voting***\n
3,139
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
5,007
34
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nArray is sorted and rotated if we are able to find in which part target is present and also whether it is sorted or not then we can search easily by binary search.\n\nFor detailed explanation you can refer to my youtube channel (Hindi Language)\n\n or link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Initialize two pointers `i` and `j` to represent the current search interval, where `i` is the left boundary and `j` is the right boundary.\n\n2. Enter a loop that continues as long as `i` is less than or equal to `j`.\n\n3. Calculate the middle index `mid` as `i + (j - i) / 2`.\n\n4. Check if the element at index `mid` is equal to the target. If it is, return `mid` as the index where the target is found.\n\n5. Check if the left part of the interval (from `i` to `mid`) is sorted:\n\n a. If `nums[mid] >= nums[i]`, then the left part is sorted.\n\n b. Check if the target is within the range of values in the left sorted part (`nums[i]` to `nums[mid]`). If yes, update `j = mid - 1` to search in the left part; otherwise, update `i = mid + 1` to search in the right part.\n\n6. Check if the right part of the interval (from `mid` to `j`) is sorted:\n\n a. If `nums[mid] <= nums[j]`, then the right part is sorted.\n\n b. Check if the target is within the range of values in the right sorted part (`nums[mid]` to `nums[j]`). If yes, update `i = mid + 1` to search in the right part; otherwise, update `j = mid - 1` to search in the left part.\n\n7. If none of the conditions above is satisfied, return `-1` to indicate that the target element is not found in the array.\n\n8. After the loop ends (when `i > j`), return `-1` to indicate that the target element is not found in the rotated sorted array.\n\n# Complexity\n- Time complexity:O(log 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``` C++ []\nclass Solution {\npublic:\n int search(vector<int>& nums, int target) {\n int i=0;\n int j=nums.size()-1;\n while(i<=j){\n int mid=i+(j-i)/2;\n if(nums[mid]==target){\n return mid;\n }\n else if(nums[mid]>=nums[i]){\n if(target>=nums[i]&& target<nums[mid]){\n j=mid-1;\n }\n else\n i=mid+1;\n }\n else if(nums[mid]<=nums[j]){\n if(target>nums[mid]&&target<=nums[j])\n i=mid+1;\n else\n j=mid-1;\n }\n }\n return -1;\n }\n};\n```\n```java []\nclass Solution {\n public int search(int[] nums, int target) {\n int i = 0;\n int j = nums.length - 1;\n while (i <= j) {\n int mid = i + (j - i) / 2;\n if (nums[mid] == target) {\n return mid;\n } else if (nums[mid] >= nums[i]) {\n if (target >= nums[i] && target < nums[mid]) {\n j = mid - 1;\n } else {\n i = mid + 1;\n }\n } else if (nums[mid] <= nums[j]) {\n if (target > nums[mid] && target <= nums[j]) {\n i = mid + 1;\n } else {\n j = mid - 1;\n }\n }\n }\n return -1;\n }\n}\n\n```\n```python []\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n i = 0\n j = len(nums) - 1\n while i <= j:\n mid = i + (j - i) // 2\n if nums[mid] == target:\n return mid\n elif nums[mid] >= nums[i]:\n if target >= nums[i] and target < nums[mid]:\n j = mid - 1\n else:\n i = mid + 1\n elif nums[mid] <= nums[j]:\n if target > nums[mid] and target <= nums[j]:\n i = mid + 1\n else:\n j = mid - 1\n return -1\n\n```\n\n
3,141
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
273
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this algorithm is to utilize the binary search approach, but with a twist to handle the rotation. We divide the array into two parts: one that is sorted and the other that isn\'t. By comparing the target with the elements at the middle and adjusting the pointers based on whether the left or right side is sorted, we can efficiently narrow down the search range.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize two pointers, left and right, to the start and end indices of the array.\n- Enter a binary search loop while left is less than or equal to right.\n- Calculate the middle index, mid, using the formula (left + right) / 2.\n- Check if the element at mid is the target. If so, return mid.\n- Determine which side of the array is sorted: the left side (from left to mid) or the right side (from mid to right).\n- Depending on which side is sorted, check if the target falls within the range of that side. If it does, adjust the pointers to narrow down the search range accordingly.\n- If the target is not found in the current search range, update the pointers and repeat the process.\n- If the loop ends and the target is not found, return -1.\n\n# Complexity\n- Time complexity: **O(log n)** - The algorithm halves the search range in each step, resulting in a logarithmic number of steps.\n\n\n- Space complexity: **O(1)** - The algorithm uses a constant amount of extra space for variables regardless of the input size.\n\n# Code\n```\nclass Solution {\npublic:\n int search(vector<int>& nums, int target) {\n int left = 0;\n int right = nums.size() - 1;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n \n if (nums[mid] == target) {\n return mid; // Found the target\n }\n \n // Check which side is sorted\n if (nums[left] <= nums[mid]) {\n // Left side is sorted\n if (nums[left] <= target && target < nums[mid]) {\n // Target is in the left sorted side\n right = mid - 1;\n } else {\n // Target is in the right unsorted side\n left = mid + 1;\n }\n } else {\n // Right side is sorted\n if (nums[mid] < target && target <= nums[right]) {\n // Target is in the right sorted side\n left = mid + 1;\n } else {\n // Target is in the left unsorted side\n right = mid - 1;\n }\n }\n }\n \n return -1; // Target not found\n }\n};\n\n```\n![upvote img.jpg]()\n
3,142
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
478
9
# 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 static int search(int[] nums, int target) {\n int low = 0;\n int high = nums.length - 1;\n\n while (low <= high) {\n int mid = low + (high - low) / 2;\n\n if (nums[mid] == target) {\n return mid;\n } else if (nums[mid] >= nums[low]) { \n if (target >= nums[low] && target < nums[mid]) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n } else {\n if (target > nums[mid] && target <= nums[high]) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n }\n\n return -1;\n}\n\n}\n```\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository]()\n\n\n\n![e78315ef-8a9d-492b-9908-e3917f23eb31_1674946036.087042.jpeg]()\n
3,145
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
17,064
114
![image]()\n\n```\n/* This is always possible when we are at mid either left half is sorted or right haldf is sorted */\nclass Solution {\npublic:\n int search(vector<int>& arr, int target) {\n int n = arr.size();\n int low = 0, high = n-1;\n long int mid = -1;\n while(low <= high){\n mid = low + (high-low)/2;\n if(arr[mid] == target) return mid;\n if(arr[mid] >= arr[low]){\n /* left half sorted */\n if(target >= arr[low] && target < arr[mid]) high = mid-1;\n else low = mid+1;\n }\n else{\n /* right half is sorted */\n if( target > arr[mid] && target <= arr[high]) low = mid+1;\n else high = mid-1;\n }\n }\n return -1;\n }\n};\n/* If you like the solution please upvote thanku*/\n```\n\nIf you like the solution please upvote thanku
3,146
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,796
9
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nin question, it is given we have to solve it in lon n times. which means we have to use divide and conquer technique.\n if in question complexity is not mentioned , then it is obvious since array is rotated and sorted that is both parts are sorted. we have to eliminate one part so that we can search in right part.\n\n# WHAT IS PIVOT OF AN ROTATED SORTED ARRAY.\nIt is the index of the array at which array get sorted in two halves. example- [4,5,6,7,8]->[8,4,5,6,7], pivot is 4\n# WHY PIVOT????\n we are finding pivot so that we can eliminate the second half and apply search in the correct part.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. firstly we have to find pivot using binary search.\n2. then we have to check whether target is less or greater than pivot.\n3. if target is greater than pivot apply search on right half else left half. [4,5,6,7,8]->[8,4,5,6,7] , target is 6.... search is done on [4,5,6,7]\n4 apply binary search on the half.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(lon n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)- constant \n\n# Code\n```\nclass Solution {\npublic:\n int BinarySearch(vector<int>& arr, int s,int e,int k)\n {\n while(s<=e)\n {\n int mid=(s+e)/2;\n if(arr[mid]==k)\n return mid;\n else if(arr[mid]<k)\n {\n s=mid+1;\n }\n else\n e=mid-1;\n }\n return -1;\n }\n int getPivot(vector<int>& arr)\n {\n int s=0,e=arr.size()-1;\n int mid=(s+e)/2;\n while(s<e)\n {\n if(arr[mid] >= arr[0])\n s=mid+1;\n else\n e=mid;\n mid=(s+e)/2;\n }\n return s;\n }\n int search(vector<int>& arr, int target) {\n int pivot =getPivot(arr);\n if(arr[pivot]<=target && target <= arr[arr.size()-1])\n {\n return BinarySearch(arr,pivot,arr.size()-1,target);\n }\n else\n return BinarySearch(arr,0,pivot-1,target);\n }\n};\n```
3,147
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
601
9
```\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n if not nums:\n return -1\n \n left, right = 0, len(nums) - 1\n\n while left <= right:\n mid = (left + right) // 2\n\n if nums[mid] == target:\n return mid\n\n # Left position\n if nums[left] <= nums[mid]:\n # if target is between start & mid, make right to (mid -1)\n if nums[left] <= target <= nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n\n # Right position\n else:\n # if target is between mid & end, make start to (mid + 1)\n if nums[mid] <= target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n\n return -1\n```
3,148
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,699
22
```\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n if not nums:\n return -1\n \n left, right = 0, len(nums) - 1\n\n while left <= right:\n mid = (left + right) // 2\n\n if nums[mid] == target:\n return mid\n\n # Left position\n if nums[left] <= nums[mid]:\n # if target is between start & mid, make right to (mid -1)\n if nums[left] <= target <= nums[mid]:\n right = mid - 1\n else:\n left = mid + 1\n\n # Right position\n else:\n # if target is between mid & end, make start to (mid + 1)\n if nums[mid] <= target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n\n return -1\n```
3,149
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
2,495
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int search(vector<int>& nums, int target) {\n int low=0;\n int high=nums.size()-1;\n while(low<=high)\n {\n int mid=(low+high)/2;\n if(nums[mid]== target) return mid;\n\n else if(nums[mid]>=nums[low])\n {\n if(nums[mid]>= target and nums[low]<= target) high=mid-1;\n else low = mid+1;\n }\n else{\n if(nums[mid]<= target and nums[high]>= target) low=mid+1;\n else high=mid-1;\n\n }\n }\n return -1;\n \n }\n};\n```
3,150
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,336
5
**Brute force:O(n)**\n```\nclass Solution {\npublic:\n \n int search(vector<int>& nums, int target) \n {\n int n=nums.size();\n \n int fix=-1;\n \n for(int i=0;i<n;i++)\n {\n if(nums[i]==target)\n {\n fix=i;\n break;\n }\n }\n \n return fix;\n }\n};\n```\n\n\n**Binary Search : O(log2n)**\n\n**We simply divide the array from point where curr element is greater than equal to prev one and less than or equal to next one and apply binary search twice...\none on first section and another on right section**\n\n```\nclass Solution {\npublic:\n \nint bs(vector<int>&arr,int n,int find,int start,int end)\n{\n \n \n \n int mid;\n \n while(start<=end)\n {\n mid=start+(end-start)/2;\n \n if(arr[mid]==find)\n {\n return mid;\n }\n else if(arr[mid]<find)\n {\n start=mid+1;\n }\n else\n {\n end=mid-1;\n }\n }\n \n return -1;\n \n \n}\n \n \n int search(vector<int>&arr, int target)\n {\n \n int n=arr.size();\n int s=0;\n\t int e=n-1;\n\t int fix;\n \n\t while(s<=e)\n\t {\n\t int mid=s+(e-s)/2;\n\t \n\t int prev=(mid-1+n)%n;\n\t int next=(mid+1)%n;\n\t \n\t \n\t if((arr[mid]<=arr[prev])&&(arr[mid]<=arr[next]))\n\t {\n\t fix=mid;\n break;\n\t }\n\t else if(arr[mid]<=arr[e])\n\t {\n\t e=mid-1;\n\t }\n\t else if(arr[mid]>=arr[s])\n\t {\n\t s=mid+1;\n\t }\n\t }\n\t \n \n \n int x=bs(arr,n,target,0,fix-1);\n int y=bs(arr,n,target,fix,n-1);\n \n \n \n if((x==y)&&(x==-1))\n {\n return -1;\n }\n \n if(x!=-1)\n {\n return x;\n }\n \n \n return y;\n \n \n \n }\n};\n```\n\n**Thank you**
3,153
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
1,242
5
bin# Complexity\n- Time complexity: O(logN)\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 search(int[] nums, int target) {\n \n int start = 0;\n int end = nums.length-1;\n while(start <= end){\n if(nums[start] == target) return start;\n if(nums[end] == target) return end;\n start ++;\n end--;\n }\n return -1; \n }\n \n}\n```
3,164
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2]. Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums. You must write an algorithm with O(log n) runtime complexity.
Array,Binary Search
Medium
null
6,830
34
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n# simple binary search \n# Complexity\n- Time complexity: O(logn)\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 search(int[] nums, int target) {\n int start=0;\n int end=nums.length-1;\n \n while(start<=end){\n int mid= start+(end-start) /2;\n if(nums[mid]==target) return mid;\n if(nums[start]<=nums[mid]){\n if(target<=nums[mid] && target>=nums[start]){\n end=mid-1;\n }else{\n start=mid+1;\n }\n }\n else{\n if(target>=nums[mid] && target<=nums[end]){ \n start=mid+1;\n }else{\n end=mid-1;\n }\n }\n }\n return -1;\n }\n \n}\n```\nplease upvote this for better solution of other questions![download.jfif]()\n
3,167