Remove Invalid Parentheses Explained using Stacks | Leetcode 301 (Valid Parentheses) Code in JAVA

Sdílet
Vložit
  • čas přidán 7. 09. 2024

Komentáře • 167

  • @leetcode7091
    @leetcode7091 Před 2 lety +4

    The way it is explained, its amazing, one can understand how to approach solution. Thanks for the video.

  • @mohitsingla6604
    @mohitsingla6604 Před 3 lety +7

    Great explanation, @Pepcoding you can add time and space complexity as well in the video for more details.

  • @KaustubhPande
    @KaustubhPande Před 3 lety +14

    Nicely explained. Thank you. But, the runtime is quite high. It exceeds the time limit on Leetcode.

    • @Pepcoding
      @Pepcoding  Před 3 lety +2

      There may be an edge case which might be missing, kindly analyse it once again, you'll find it. If you like our efforts, will you like to write a review about us here - g.page/Pepcoding/review?rc

    • @harshitasingh963
      @harshitasingh963 Před 3 lety +1

      Happened with me too. I tried running it on Jupyter notebook and it works just fine but the time taken is horrendous

    • @amitbajpai6265
      @amitbajpai6265 Před 2 lety

      Use this code
      it is only 5% percent faster but passes all the test cases.......
      class Solution:
      def removeInvalidParentheses(self, s: str) -> List[str]:
      def removals(s,stack):
      for i in s:
      if(i=="("):
      stack.append(i)
      elif(i==")"):
      if(len(stack)==0 or stack[-1]==")"):
      stack.append(i)
      else:
      stack.pop()
      return stack

      rmarr=removals(s,[])

      ans=[]
      def recursion(s,rmarr,idx):
      if(idx==len(rmarr)):
      if(len(removals(s,[]))==0):
      ans.append(s)
      return

      for i in range(len(s)):
      if(s[i]==rmarr[idx]):
      if(i==0):
      recursion(s[:i]+s[i+1:],rmarr,idx+1)
      else:
      if(s[i]!=s[i-1]):
      recursion(s[:i]+s[i+1:],rmarr,idx+1)

      recursion(s,rmarr,0)
      if(len(ans)==0):
      ans=[""]
      return set(ans)

  • @priyanjanchaurasia
    @priyanjanchaurasia Před 3 lety +12

    TLE can be resolved if we pass another HashSet object in the recursive function to track if the string has been visited before. If the string is visited,simply return. otherwise, put the string in HashSet and then perform rest of the operation. :Just add following condition at the very first line of recursive function.
    if(visited.contains(s))
    return;
    add value into "visited" structure right before the For loop.

    • @shukanshah5159
      @shukanshah5159 Před 3 lety +4

      Here is the code for reference.
      public static void solution(String s, int maxRemovalAllowed, Set ans, Set visited ) {
      if(visited.contains(s))
      return;
      visited.add(s);
      if(maxRemovalAllowed == 0) {
      if(getInvalidParentheses(s) == 0) {
      ans.add(s);
      }
      return;
      }
      for(int i = 0; i< s.length() ; i++) {
      String left = s.substring(0,i);
      String right = s.substring(i+1);
      solution(left+right, maxRemovalAllowed-1,ans,visited);
      }
      }

    • @sulthanmogal9692
      @sulthanmogal9692 Před 2 lety

      Thank u bruh😍😍

  • @Elon-musk-007
    @Elon-musk-007 Před 3 lety +28

    Sir this code gives TLE on platform (C++)

    • @mayankjain-901
      @mayankjain-901 Před 3 měsíci

      I used same approach and it got submitted on leetcode.

  • @atul9130
    @atul9130 Před 2 lety +4

    For Those getting TLE exception , just add a check in method to not visit same string twice as below and it will pass :
    void getValids(String s, Set set, int mr){
    if(visited.contains(s)) return;
    visited.add(s);
    if( mr == 0 ) {
    int now = getMinRemoval(s);
    if( now == 0){
    set.add(s);
    }
    return;
    }

    for( int i = 0 ; i < s.length() ; i++){
    if(Character.isLetter(s.charAt(i))) continue;
    String left = s.substring(0, i);
    String right = s.substring(i+1);
    getValids(left+right, set, mr-1);
    }
    }

  • @prashanttrivedi6957
    @prashanttrivedi6957 Před rokem

    Sir it amazing I like your teaching style thanks sir I have watched all level1 vedio and now I am here..

  • @Aniadiakh
    @Aniadiakh Před 3 lety

    Thanks for the Video and the explanation. Just to add you can also modify the getMin() to calculate min without a stack as follows -
    private int getMin(String s) {
    int left =0;
    int right = 0;
    for (int i=0;i 0) left--;
    else right++;
    }
    }
    return left+right;
    }

  • @abhi-shake9309
    @abhi-shake9309 Před 4 lety +4

    Sir if possible try to upload atleast 5 videos a day..It would be a great help to us. Loving these videos🔥

    • @Pepcoding
      @Pepcoding  Před 4 lety +6

      beta kal 5 aai thi. aj bhi aaengi

  • @MohanRaj-vp1zt
    @MohanRaj-vp1zt Před 3 lety +15

    Tried this solution, it works on IDE but leetcode shall give TLE.

  • @ishwarjha3633
    @ishwarjha3633 Před 7 měsíci

    For TLE leetcode just add a check if the set contains the string as Visited set.
    private void removeUtil(String s, int mr, List ans, HashSet set) {
    if(set.contains(s)) {
    return;
    }
    set.add(s);
    if(mr == 0 && getMin(s) == 0) {
    ans.add(s);
    }
    for(int i=0; i

  • @harshsingh4063
    @harshsingh4063 Před 3 lety

    Your backtracing algorithm approach is one of the best

    • @Pepcoding
      @Pepcoding  Před 3 lety

      I am glad you liked it. I also hope that you are watching till end and trying to understand the what, how and especially why of the problem.
      If you like our efforts, we request a review
      g.page/Pepcoding/review?rc
      You can subscribe to our channel here
      czcams.com/users/Pepcodingabout?view_as=subscriber

  • @sarveshkaushal4585
    @sarveshkaushal4585 Před 3 lety +1

    Sir ji- sab kuchh bhool jaye, chahe Gajani ban jaye, but str.subtring(0, i) and str.substring(i+1) kabhi nahi bhool sakta. Aap har question me substring() pe itna zor lagate ho.Thanks another great video.

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Haha..
      Keep watching and keep learning😊🙏

  • @ankitranjan88
    @ankitranjan88 Před 3 lety +1

    The Best Explanation...Even A Very Beginner Can Understand it.

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Glad you think so! and If you like our efforts, please upvote the comments written by the students about Pepcoding here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )

  • @akashmishra5553
    @akashmishra5553 Před 3 lety +1

    Sir, you are doing a great job. Thank you!

    • @Pepcoding
      @Pepcoding  Před 3 lety

      So nice of you. keep motivating, keep learning and keep loving Pepcoding😊

  • @ShahidHussain-dh3pg
    @ShahidHussain-dh3pg Před měsícem

    Nice explanation.

  • @harshvachhani4922
    @harshvachhani4922 Před měsícem

    Great video sir.

  • @nitinasthana1740
    @nitinasthana1740 Před 3 lety +3

    Great explanation! Cheers.
    But this is not exactly Leetcode 301. Out there the input can have the alphabets as well.
    Example input: "(a)())()" Output: "(a)()()", "(a())()"

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Alright, noted.

    • @vaibhavdanagariya6250
      @vaibhavdanagariya6250 Před 3 lety

      same

    • @ialgorithms
      @ialgorithms Před rokem

      Continuing the above discussion:
      s = "(a)())()"
      The modification in the getMin function is as follows [Python]:
      def getMin(self, s):
      stack = []
      for i in s:
      if i == "(":
      stack.append(i)
      elif i == ")":
      if stack and stack[-1] == '(':
      stack.pop()
      else:
      stack.append(i)
      return len(stack)
      But it will give TLE for # s = "((()((s((((()". An optimization is needed which is discussed in other comments.

  • @ankushgupta630
    @ankushgupta630 Před 3 lety +2

    Please discuss the BFS approach too .

  • @Ankit-hs9nb
    @Ankit-hs9nb Před 2 lety

    class Solution:
    def removeInvalidParentheses(self, s):

    level = {s}
    print(level)
    while True:
    valid = []
    for elem in level:
    print(elem)
    if self.isValid(elem):
    valid.append(elem)
    if valid:
    return valid
    # initialize an empty set
    new_level = set()
    # BFS
    for elem in level:
    for i in range(len(elem)):
    new_level.add(elem[:i] + elem[i + 1:])
    level = new_level
    def isValid(self,s):
    count = 0
    for c in s:
    if c == '(':
    count += 1
    elif c == ')':
    count -= 1
    if count < 0:
    return False
    return count == 0

  • @prakashshukla3558
    @prakashshukla3558 Před 3 lety

    Lol muje bhi height ki spelling 30 saal mai yaad hui hai ... awesome channel, awesome content.

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Thank you so much and If you like the content could you post something on LinkedIn about us? This will help us in reaching out to more people and help a lot of other students as well
      Something like this
      Sumeet Malik from Pepcoding is making all his content freely available to the community
      You can check it out here - www.pepcoding.com/resources
      /
      Also, this is the youtube channel - czcams.com/users/Pepcodingplaylists?view_as=subscriber

  • @anantbhargava9049
    @anantbhargava9049 Před rokem

    We can add irrespective if answer is present is hashset or not because hashset will take care of duplicates by default

  • @sciphilo754
    @sciphilo754 Před 3 lety +2

    Amazing content!!

  • @curiouswatcher4626
    @curiouswatcher4626 Před 3 lety +2

    one of the most iconic lines by sumeet sir : "chala chala sa lag raha hai " .
    Edit : Great explanation sir .

    • @Pepcoding
      @Pepcoding  Před 3 lety +1

      Glad to know that you liked the content and thank you for appreciating.
      The love and respect which I get from you people keep me highly motivated and the same I am able to forward It to you people through my videos.
      So, keep motivating, keep learning and keep loving Pepcoding😊

  • @shoaibalam7855
    @shoaibalam7855 Před rokem +1

    My life summed up at 10:14

  • @rhythmjayee9707
    @rhythmjayee9707 Před 3 lety

    Got TLE on leetcode for this solution
    here is the updated code
    public List removeInvalidParentheses(String s) {
    List ls=new ArrayList();
    int minRemoval=getMinRemovals(s);
    HashMap set=new HashMap();
    getValidAns(s,set,ls,minRemoval);
    return ls;
    }
    public void getValidAns(String s, HashMap set, List ls,int minRemoval){
    if(minRemoval==0){
    if(getMinRemovals(s)==0){
    ls.add(s);
    }
    return;
    }
    for(int i=0;i

  • @abdulbaseermahmood1591

    Salute you, sir, for great content!

    • @Pepcoding
      @Pepcoding  Před 3 lety

      If you like our efforts, please upvote the comments written by the students about Pepcoding here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )

  • @mukultaneja7243
    @mukultaneja7243 Před 4 lety +4

    Great explanation sir !
    Sir, isn't it becoming too much complex by removing any random "mra" brackets from the string and then again checking if its valid in the base case and then checking if the string exists ? If instead we remove the same type of bracket before it, I think it will become too much optimized, as it will make the correct strings only.

  • @adityaojha2701
    @adityaojha2701 Před 3 lety +1

    Very well explained!!

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Thankyou beta!
      I am glad you liked it. I also hope that you are watching till the end and trying to understand the what, how, and especially why of the problem. If you like our efforts, will you like to write a few words about us here (www.quora.com/How-do-I-start-learning-or-strengthen-my-knowledge-of-data-structures-and-algorithms )

  • @PankajKP
    @PankajKP Před 4 lety +1

    Sir hum isko is way me kr skte hain? jaise har recursive call me hum current index i include(not remove,k) or not include(remove,k-1)??

  • @user-hd4zr4il6s
    @user-hd4zr4il6s Před rokem

    i tried the code in leetcode and it showed time limit exceed. will someone help?

  • @AniketYadav-nu3fb
    @AniketYadav-nu3fb Před 2 lety +1

    Leetcode 301 (JAVA SOLUTION - Invalid parentheses)
    class Solution {
    public List removeInvalidParentheses(String str) {
    List ans = new ArrayList();
    HashSet hash = new HashSet();
    int min_removal = getMin(str);
    solution(str, min_removal, hash, ans);
    return ans;
    }

    public static void solution(String str, int min_removal_allowed, HashSet hash, List ans){
    if(hash.contains(str)){
    return;
    }

    hash.add(str);

    if(min_removal_allowed == 0){
    int mrn = getMin(str); // min removal now
    if(mrn == 0){

    ans.add(str);

    }
    return;
    }


    for(int i = 0; i

    • @LOVE-kf9xi
      @LOVE-kf9xi Před rokem

      Solution works , but I can't understand ,how? You are not handling alphabets , but still it is getting accepted, how? Do we not need to worry about the alphabets? Please explain🙏

  • @mehulbisht9708
    @mehulbisht9708 Před 4 lety +3

    20:49 if someone missed it , here is how the isValid() method was defined. 😂

  • @ialgorithms
    @ialgorithms Před rokem

    Leetcode 301: Python solution
    class Solution:
    def removeInvalidParentheses(self, s: str) -> List[str]:
    ans = set()
    mra = self.getMin(s)
    self.solution(s, mra, ans, set())
    return list(ans)
    def solution(self, s, mra, ans, visited):
    if s in visited:
    return
    visited.add(s)
    if mra == 0:
    mrnow = self.getMin(s)
    if mrnow == 0:
    if s not in ans:
    ans.add(s)
    return
    for i in range(len(s)):
    left = s[0:i]
    right = s[i+1:]
    self.solution(left+right, mra-1, ans, visited)
    def getMin(self, s):
    stack = []
    for i in s:
    if i == "(":
    stack.append(i)
    elif i == ")":
    if stack and stack[-1] == '(':
    stack.pop()
    else:
    stack.append(i)
    return len(stack)
    # "((()((s((((()"

  • @bhatnagarcapital
    @bhatnagarcapital Před 4 lety +3

    Sir ek hi dil hai kitni baar jeetoge ❤️

  • @abhinavgupta3913
    @abhinavgupta3913 Před 3 lety +2

    bhiya iska koi optimised solution h kya ..kyuki agar worst case le hum to ye 11 length se upar wali string ke liye TLE de rha h

  • @noobCoder26
    @noobCoder26 Před rokem

    thanks for the soln and explaination sir . I just want to ask whats the time complexity of the soln ?

  • @shadab5azhar
    @shadab5azhar Před 2 lety

    Very well explained

  • @jigarlove2113
    @jigarlove2113 Před 3 lety

    sir aap kha se padhe ye sab. just mind blowing . already completed your recursion video. im in NIT bhopal but your are better than out professor. :)

    • @Pepcoding
      @Pepcoding  Před 3 lety +1

      The love and respect which I get from you people keep me highly motivated and the same I am able to forward It to you people through my videos.
      So, keep motivating and Keep loving😊

  • @VKBMath
    @VKBMath Před 3 lety +1

    Great teacher

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Glad you think so!

    • @Pepcoding
      @Pepcoding  Před 3 lety

      I am glad you liked it. I also hope that you are watching till end and trying to understand the what, how and especially why of the problem.
      If you like our efforts, we request a review
      g.page/Pepcoding/review?rc
      You can subscribe to our channel here
      czcams.com/users/Pepcodingabout?view_as=subscriber
      For clearing your doubts, you can join our community on telegram
      t.me/pepcoding

  • @Raj_Patel21
    @Raj_Patel21 Před 3 lety

    One Flaw found in the solution:
    We are removing the character immediately but we also need to keep it and start looking from the next index
    here is my Python3 code accepted on Leetcode
    class Solution:
    def removeInvalidParentheses(self, s: str) -> List[str]:
    '''
    To find Minimum number of characters
    '''
    def findMin(s):
    st = []
    for i in s:
    if i not in ["(", ")"]: continue
    if not st:
    st.append(i)
    else:
    if i == ")" and st[-1] == "(":
    st.pop()
    else:
    st.append(i)
    return len(st)
    def helper(start_idx, remaining, mask):
    if remaining == 0:
    found_str = ''.join([s[i] for i in range(len(mask)) if mask[i] == 1])
    # Checking if found string is valid or not
    if findMin(found_str) == 0:
    ans.add(found_str)
    return
    if start_idx == len(s):
    return
    '''
    2 choices remove that character or not
    Remove -> mask[] = 0 and remaining - 1
    Keep -> mask[] = 1
    In both cases we advance start_idx by 1
    '''
    # Skipping characters other than '(' and')'
    if s[start_idx] in [')', '(']:
    mask[start_idx] = 0
    helper(start_idx + 1, remaining - 1, mask)
    mask[start_idx] = 1
    helper(start_idx + 1, remaining, mask)
    ans = set()
    invalid_count = findMin(s)
    helper(0, invalid_count, [1 for _ in range(len(s))])
    return list(ans)

  • @pluviophile762
    @pluviophile762 Před 3 lety +3

    sir this solution is giving TLE on leetcode

  • @jatinsingh1368
    @jatinsingh1368 Před 3 lety +1

    for removing tle try to use set
    for checking each and very string wheteher it is valid or not
    Here is The Code:
    class Solution {
    public:
    string str;
    vector ans;
    int clen;
    // checking the
    bool isValid(string s)
    {
    stack st;
    int f=1;
    for(int i=0;s[i];i++)
    {
    if(s[i]=='(')
    st.push(s[i]);
    else if(s[i]==')')
    {
    if(!st.empty())
    {
    if(st.top()=='(')
    {
    st.pop();
    }
    else
    {
    f=0;
    break;

    }
    }
    else
    {
    f=0;
    break;
    }

    }
    }
    if(f==1 && st.size()==0)
    return true;
    else
    return false;
    }
    set se;
    void all(int k,int i,string bw)
    {

    if(k==0 && bw.size()==clen)
    {
    // if string is repeated then neglect it
    if(se.find(bw)!=se.end())
    return;
    else
    se.insert(bw);
    //cout

  • @ashwaniponia3817
    @ashwaniponia3817 Před 4 lety +2

    Great explanation sir!
    one suggestion please include the time complexity analysis of the algorithm.

    • @Pepcoding
      @Pepcoding  Před 4 lety +2

      Hanji, I am missing out on an important thing. Bhool ja rha hun. Karunga isse aage ki videos mei

  • @444not
    @444not Před 3 lety +4

    One optimization - no need to check for valid string if it’s already in set.

  • @sourabhsharma9070
    @sourabhsharma9070 Před 4 lety

    very nice explaination!

  • @nishantdehariya5769
    @nishantdehariya5769 Před 6 měsíci

    nice sir but
    giving TLE for long strings leetcode 301

  • @rajatverma1888
    @rajatverma1888 Před 2 lety

    public class RemoveInvalidParenthesis {

    private static int getMin(String str) {
    Stack st=new Stack();
    for(int i=0;i

  • @sara1khan157
    @sara1khan157 Před 3 lety

    how about space complexity is it N {for stack } how much for internal stack {used for recursive calls } is it N ??

  • @santoshr15
    @santoshr15 Před 3 lety +5

    Hi, I tried solving this on Leetcode but after 93 test cases it says time limit exceeded. I followed the same approach as explained in the video. Please do advice what can be done. I can share the code if needed. Thanks

    • @Ankit-hs9nb
      @Ankit-hs9nb Před 2 lety

      class Solution:
      def removeInvalidParentheses(self, s):

      level = {s}
      print(level)
      while True:
      valid = []
      for elem in level:
      print(elem)
      if self.isValid(elem):
      valid.append(elem)
      if valid:
      return valid
      # initialize an empty set
      new_level = set()
      # BFS
      for elem in level:
      for i in range(len(elem)):
      new_level.add(elem[:i] + elem[i + 1:])
      level = new_level
      def isValid(self,s):
      count = 0
      for c in s:
      if c == '(':
      count += 1
      elif c == ')':
      count -= 1
      if count < 0:
      return False
      return count == 0

  • @rohandevaki4349
    @rohandevaki4349 Před 2 lety +1

    this is giving TLE , update your answer

  • @udaykumar555
    @udaykumar555 Před 2 lety

    Mazaa aaya bhai....awesome

    • @Pepcoding
      @Pepcoding  Před 2 lety

      For better eperience visit on nados.pepcoding.com
      Also follow us on our Instagram account to stay tuned.
      instagram.com/pepcoding/

  • @aparna8338
    @aparna8338 Před 4 lety

    Great explanation sir

    • @Pepcoding
      @Pepcoding  Před 4 lety +1

      I am glad you liked it. I also hope that you are watching till end and trying to understand the what, how and especially why of the problem.
      If you like my efforts, I request a review
      g.page/Pepcoding/review?rc

  • @RiteshKumar-nt5sj
    @RiteshKumar-nt5sj Před rokem

    Sir please come back😭😭

  • @champ121991
    @champ121991 Před 2 lety

    Great.. But whats the time complexity of this?

  • @prashantbisht2219
    @prashantbisht2219 Před 2 lety

    If anyone is looking for leetcode solution for the same.
    class Solution:

    def backTrack(self, curr , ans, minRemove,visited ):
    if minRemove == 0 :
    if self.minPR(curr) == 0:
    ans.add(curr)
    return
    for i in range(len(curr)):
    if curr[i] not in [ '(',')']: continue
    l = curr[0:i]+curr[i+1:]
    if not l in visited :
    visited.add(l)
    self.backTrack(curr[0:i]+curr[i+1:],ans,minRemove-1, visited)
    def minPR(self, s ):
    left,right = 0,0
    for par in s:
    if par == '(':
    left += 1
    elif par == ')':
    if left == 0 :
    right += 1
    else:
    left -= 1
    return right+left
    def removeInvalidParentheses(self, s: str) -> List[str]:
    ans = set()
    visited = set()
    self.backTrack(s,ans, self.minPR(s),visited)


    return ans if ans else [""]

  • @rohanyelpale3365
    @rohanyelpale3365 Před 2 lety

    maza aagaya :)

  • @ghanibhai1630
    @ghanibhai1630 Před 3 lety

    i think we can use memoziation approch also

  • @whitedracarys7613
    @whitedracarys7613 Před 4 lety +2

    Sir foundation ke baad koi book follow kr sakte hai any suggestion?

    • @Pepcoding
      @Pepcoding  Před 4 lety

      yar book se kahin acha hai, aap leetcode, codechef, codeforces karein. ye practical sa kaam hai. books are inferior to actually solving problems

  • @PradeepKumarIIITD
    @PradeepKumarIIITD Před 4 lety

    loved it sir...

    • @Pepcoding
      @Pepcoding  Před 4 lety

      Please like share and subscribe as well.

  • @aklogisticals40
    @aklogisticals40 Před 3 lety

    getting TLE on leetcode using same code, can anyone help me.

  • @rahulbhatia3075
    @rahulbhatia3075 Před 4 lety

    Great content

  • @mrprime557
    @mrprime557 Před 2 lety

    Good explanation, but not the most optimized solution. Getting TLE on leetcode

    • @Pepcoding
      @Pepcoding  Před 2 lety

      Glad to know that you like our explanation.
      Visit - nados.pepcoding.com and sign up to NADOS.
      For structured content and better experience.
      Don't forget to follow us on Instagram instagram.com/pepcoding/

  • @jatinbhatoya8420
    @jatinbhatoya8420 Před 2 lety

    your solutionis giving tle on leetcode

    • @Pepcoding
      @Pepcoding  Před 2 lety

      leetcode ki alag playlist bna rhe hain yar.

  • @alankruthisaieni2562
    @alankruthisaieni2562 Před 2 lety +1

    To get out from out of memory error, Keep a visited hashset to keep track of each string traversed so far if it is already traversed return.
    if(visited.contains(str)){
    return;
    }
    visited.add(str);

  • @411_danishranjan9
    @411_danishranjan9 Před 3 lety

    sir, isme aapne backtrack to kiya hi nhi.
    jab ek elment hata kar call lagai, uske baad wo normal ho sake, taaki wo dusri call laga sake, (yeh to aapne kiya hi nhi).

  • @ghanibhai1630
    @ghanibhai1630 Před 3 lety

    just find opening and closing bracket count and if (>) then (-) if )>( then )-(

  • @kartikaymahajan9591
    @kartikaymahajan9591 Před 3 lety

    what is it's time complexity?

  • @karnifazil
    @karnifazil Před 4 lety

    Excellent!

  • @sourabhsharma9070
    @sourabhsharma9070 Před 4 lety +1

    sir bs video me ek chiz ki kami hai ki app hmesha complexity ko btana bhul jate ho..it's obvious but it completes the whole explaination structure!

    • @ankitamehra5045
      @ankitamehra5045 Před 4 lety

      Hi Sourabh sir has told that backtracking has a general formula - levels to the power of options. hope it helps

    • @Pepcoding
      @Pepcoding  Před 4 lety

      hanji. Ab lag rha hai ki sare questions ki redo kaise karoon. Aage se bnaunga

    • @shubhamsharma-sf6lx
      @shubhamsharma-sf6lx Před 4 lety

      @@Pepcoding commnet section me daalke pin krdo , redo krne ki jroorat nhi :)

  • @aakashyadav6228
    @aakashyadav6228 Před 3 lety

    Sir how is this a backtracking solution ?

  • @learningsarthak5946
    @learningsarthak5946 Před 3 lety +1

    yeh test case kaise pass karenge?
    Input: s = "(a)())()"
    Output: ["(a())()","(a)()()"]

  • @loserfruit9663
    @loserfruit9663 Před 3 lety

    Awesome

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Thankyou beta!
      I am glad you liked it. I hope that you are watching till the end and trying to understand what, how, and especially why of the problem.
      If you like our efforts, will you like to write a few words about us here (www.quora.com/What-are-the-good-websites-to-learn-data-structures-and-algorithms )

  • @shubhramishra4568
    @shubhramishra4568 Před 3 lety +1

    Java Solution accepted on leetcode
    class Solution {

    List result= new ArrayList();
    HashSet visited;
    public List removeInvalidParentheses(String s) {

    if(s.length() ==0){
    return result;
    }
    visited = new HashSet();
    int mra = findInvalidRemoval(s);
    getValidList(s,mra);
    return result;

    }

    public void getValidList(String s,int minRemoval){

    if(visited.contains(s)){
    return ;
    }
    visited.add(s);
    if(minRemoval == 0){

    //check string formed is valid
    int valid = findInvalidRemoval(s);

    if(valid == 0){
    result.add(s);
    }
    return ;
    }


    for(int i=0;i

  • @ghanibhai1630
    @ghanibhai1630 Před 3 lety

    i did it on my own

  • @lakshrustagi507
    @lakshrustagi507 Před 2 lety

    cpp solution without tle::: i have done an optimisation to cut down rechecking of similar subproblem by using a map.
    class Solution {
    public:
    vector ans;
    unordered_map map;
    int get_min(string s)
    {
    stack st;
    for (int i = 0; i < s.size(); i++)
    {
    if (s[i] == '(')st.push('(');
    else if (s[i] == ')')
    {
    if (st.size())
    {
    if (st.top() == '(')
    {
    st.pop();
    }
    else
    {
    st.push(')');
    }
    }
    else
    {
    st.push(')');
    }
    }
    }
    return st.size();
    }
    void solve2(string s,int minimum_removal_allowed)
    {
    if(map[s]!=0)//for checking that string is already exist in map or not
    return;
    else
    map[s]++;
    if(minimum_removal_allowed==0)
    {
    int minimum_removal_now=get_min(s);
    if(minimum_removal_now==0)
    {
    ans.push_back(s);
    }
    return;
    }
    for(int i=0;i

    • @Pepcoding
      @Pepcoding  Před 2 lety

      Post your queries on Community post of nados.io
      Our mentors and alumni will guide you and help you out.

  • @sara1khan157
    @sara1khan157 Před 3 lety

    time complexity : N* 2^N ??

  • @muhammadmustafamustafa2442

    what was the concept of hashset in easy wording ???

    • @Pepcoding
      @Pepcoding  Před 3 lety

      Beta, I regret to inform you that, I won't be able to answer/solve the personal doubts of each and every student over here. For clearing your doubts, you can join our community on telegram - t.me/pepcoding.

  • @swapnildhiman6585
    @swapnildhiman6585 Před 2 lety

    ❤️

  • @himanshuchhikara4918
    @himanshuchhikara4918 Před 3 lety

    sir time complexity kya hogi recursion fn ki

  • @ioftheneedle
    @ioftheneedle Před 3 lety

    mast explanation, lol @ character and which

  • @shubhamsharma-sf6lx
    @shubhamsharma-sf6lx Před 4 lety

    Sir please please parallel 2-3 dp ki super mast questions daaldo.

  • @code7434
    @code7434 Před 4 lety

    PLease add Median of Two Sorted Arrays

  • @adwaitkulkarni
    @adwaitkulkarni Před 3 lety

    TLE on leetcode

  • @vaibhavdanagariya6250
    @vaibhavdanagariya6250 Před 3 lety

    Sir

  • @ecea009abhishekshyam8
    @ecea009abhishekshyam8 Před 3 lety

    sir dont

  • @shubhamrawat7895
    @shubhamrawat7895 Před 4 lety

    Noice.

  • @vanditkhuranapvt
    @vanditkhuranapvt Před 3 lety

    Sir TLE kaise resolve karein iski?

    • @Pepcoding
      @Pepcoding  Před 3 lety +1

      Beta, I regret to inform you that, I won't be able to answer/solve the personal doubts of each and every student over here. For clearing your doubts, you can join our community on telegram - t.me/pepcoding.

    • @psettii
      @psettii Před 3 lety +1

      Please use the below solution
      class Solution {
      List result = new ArrayList();
      Set set1 = new HashSet();
      public List removeInvalidParentheses(String s) {
      int minRemovals = getMinRemoval(s);
      System.out.println(minRemovals);
      Set set = new HashSet();
      removeInvalidParenthesesRecursion(s, minRemovals, set);
      return result;
      }
      private void removeInvalidParenthesesRecursion(String s, int min, Set set){
      if(min == 0){
      int minRemovalAllowed = getMinRemoval(s);
      if(minRemovalAllowed == 0){
      if(!set.contains(s)){
      set.add(s);
      result.add(s);
      }
      }
      return;
      }
      for(int i = 0; i < s.length(); i++){
      String left = s.substring(0, i);
      String right = s.substring(i+1);
      if(!set1.contains(left+right)){
      set1.add(left+right);
      removeInvalidParenthesesRecursion(left+right , min - 1, set);
      }
      }
      }
      private int getMinRemoval(String str){
      Stack stack = new Stack();
      for(int i = 0; i < str.length(); i++ ){
      char currentChar = str.charAt(i);
      if(currentChar == '('){
      stack.push(currentChar);
      }
      if(currentChar == ')'){
      if(!stack.isEmpty() && stack.peek() == '('){
      stack.pop();
      } else {
      stack.push(')');
      }
      }
      }
      return stack.size();
      }
      }

    • @ankursuri3853
      @ankursuri3853 Před 3 lety

      @@psettii Thanks for the solution!

  • @loserfruit9663
    @loserfruit9663 Před 3 lety

    Wchich

  • @mukulkumar9664
    @mukulkumar9664 Před 4 lety

    Great Video Sir !!!

    • @Pepcoding
      @Pepcoding  Před 4 lety +1

      So nice of you. May i request you to post us a reveiw?
      g.page/Pepcoding/review?rc

    • @mukulkumar9664
      @mukulkumar9664 Před 4 lety

      @@Pepcoding Done, Please check