- 345
- 41 597
Let us code
India
Приєднався 30 тра 2020
Hi, I am a SDE , at one of the Fortune 50 companies!!
The intent of this channel is to motivate the community to code everyday, and also to make their coding rounds-during interview, a bit easier !! :)
Every question has a 1)brute-force approach 2)optimized approach, and the language used is simple English
I try my best to keep my solutions beginner friendly and simple to understand.
thanks for your support!! :)
The intent of this channel is to motivate the community to code everyday, and also to make their coding rounds-during interview, a bit easier !! :)
Every question has a 1)brute-force approach 2)optimized approach, and the language used is simple English
I try my best to keep my solutions beginner friendly and simple to understand.
thanks for your support!! :)
Daily Leetcode Challenge | DEC 25 | Find Largest Value in Each Tree Row
Daily Leetcode Challenge- December 2024 - Day 25
Approach/Topic : DFS/BFS
question link: leetcode.com/problems/find-largest-value-in-each-tree-row/?envType=daily-question&envId=2024-12-25
optimized approach beats 90% of the test cases
Like, share and subscribe
***********************
Hi, I am a SDE , at one of the Fortune 50 companies!!
The intent of this channel is to motivate the community to code everyday, and also to make their coding rounds-during interview, a bit easier !! :)
Every question has a 1)brute-force approach 2)optimized approach, and the language used is simple English
I try my best to keep my solutions beginner friendly and simple to understand.
thanks for your support!! :)
***********************
Leetcode Today Challenge,
Daily Coding Practise,
Leetcode 100 days of code,
Python Daily Coding Challenge,
Daily LeetCoding Challenge ,
daily leetcode challenge,
daily leetcode questions,
daily leetcode problem,
leetcode daily today,
leetcode daily problem today,
leetcode daily challenge,
leetcode daily practise,
leetcode solutions,
letcode python,
leetcode hard problems,
leetcode easy problems,
leetcode medium problems,
leetcode for begineers,
leetcode python problems,
leetcode python,
leetcode python solutions,
leetcode python hard,
leetcode python medium,
leetcode python easy,
leetcode python english,
leetcode python solutions in english
Where to learn dp
where to learn graphs
where to learn dsa
how to start programming
how to start coding
where to learn trees
what is memoisation
what is tabulation
what are graphs
where to learn Operating systems
where to learn dbms
where to learn oops
where to learn computer networks
where to learn low level design
where to learn cs fundamentalS
Gate smashers
Placement guide
How to start programming
where to learn cpp
where to learn python
where to learn javascript
where to learn java
Placement guide
languages to learn
resources to learn data structures
Projects development
Software developer engineer ,
Importance of side projects ,
How to become a machine learning engineer ,
Associate engineer
Data structures Algorithms
College Life, College, Memories
Where to learn dp
where to learn graphs
where to learn dsa
how to start programming
how to start coding
where to learn trees
what is memoization
what is tabulation
what are graphs
where to learn programming
how to start coding
where to learn coding
where to learn DSA
resources to learn programming
how to crack amazon
how to crack placement
what is blockchain
blockchain technology explained
blockchain technology in hindi
web development roadmap
android development roadmap
MERN stack roadmap
roadmap for 2nd years
roadmap for opensource
roadmap for ios development
roadmap to learn DSA
microsoft internship,
microsoft intern 2022,
microsoft internship India,
microsoft internship experience
microsoft,software engineer
#leetcode #leet_preparation_tips #leetcodesolution #coding #interview
#CodingInterview #NovemberLeetCodingChallenge #Google #Amazon #programming #march #codinglife #meta #faang #maang
Approach/Topic : DFS/BFS
question link: leetcode.com/problems/find-largest-value-in-each-tree-row/?envType=daily-question&envId=2024-12-25
optimized approach beats 90% of the test cases
Like, share and subscribe
***********************
Hi, I am a SDE , at one of the Fortune 50 companies!!
The intent of this channel is to motivate the community to code everyday, and also to make their coding rounds-during interview, a bit easier !! :)
Every question has a 1)brute-force approach 2)optimized approach, and the language used is simple English
I try my best to keep my solutions beginner friendly and simple to understand.
thanks for your support!! :)
***********************
Leetcode Today Challenge,
Daily Coding Practise,
Leetcode 100 days of code,
Python Daily Coding Challenge,
Daily LeetCoding Challenge ,
daily leetcode challenge,
daily leetcode questions,
daily leetcode problem,
leetcode daily today,
leetcode daily problem today,
leetcode daily challenge,
leetcode daily practise,
leetcode solutions,
letcode python,
leetcode hard problems,
leetcode easy problems,
leetcode medium problems,
leetcode for begineers,
leetcode python problems,
leetcode python,
leetcode python solutions,
leetcode python hard,
leetcode python medium,
leetcode python easy,
leetcode python english,
leetcode python solutions in english
Where to learn dp
where to learn graphs
where to learn dsa
how to start programming
how to start coding
where to learn trees
what is memoisation
what is tabulation
what are graphs
where to learn Operating systems
where to learn dbms
where to learn oops
where to learn computer networks
where to learn low level design
where to learn cs fundamentalS
Gate smashers
Placement guide
How to start programming
where to learn cpp
where to learn python
where to learn javascript
where to learn java
Placement guide
languages to learn
resources to learn data structures
Projects development
Software developer engineer ,
Importance of side projects ,
How to become a machine learning engineer ,
Associate engineer
Data structures Algorithms
College Life, College, Memories
Where to learn dp
where to learn graphs
where to learn dsa
how to start programming
how to start coding
where to learn trees
what is memoization
what is tabulation
what are graphs
where to learn programming
how to start coding
where to learn coding
where to learn DSA
resources to learn programming
how to crack amazon
how to crack placement
what is blockchain
blockchain technology explained
blockchain technology in hindi
web development roadmap
android development roadmap
MERN stack roadmap
roadmap for 2nd years
roadmap for opensource
roadmap for ios development
roadmap to learn DSA
microsoft internship,
microsoft intern 2022,
microsoft internship India,
microsoft internship experience
microsoft,software engineer
#leetcode #leet_preparation_tips #leetcodesolution #coding #interview
#CodingInterview #NovemberLeetCodingChallenge #Google #Amazon #programming #march #codinglife #meta #faang #maang
Переглядів: 6
Відео
Daily Leetcode Challenge | DEC 25 | Hindi | Find Largest Value in Each Tree Row
Переглядів 4
Daily Leetcode Challenge- December 2024 - Day 25 Approach/Topic : DFS/BFS question link: leetcode.com/problems/find-largest-value-in-each-tree-row/?envType=daily-question&envId=2024-12-25 optimized approach beats 90% of the test cases optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to mo...
Daily Leetcode Challenge | DEC 23 | Minimum Number of Operations to Sort a Binary Tree by Level
Переглядів 1704 години тому
Daily Leetcode Challenge- December 2024 - Day 23 Approach/Topic : DFS question link: leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/description/?envType=daily-question&envId=2024-12-23 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the comm...
Daily Leetcode Challenge | DEC 22 | Find Building Where Alice and Bob Can Meet
Переглядів 644 години тому
Daily Leetcode Challenge- December 2024 - Day 22 Approach/Topic : heap-sort question link: leetcode.com/problems/find-building-where-alice-and-bob-can-meet/?envType=daily-question&envId=2024-12-22 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to code everyday,...
Daily Leetcode Challenge | DEC 21 | JAVA+PYTHON | Maximum Number of K-Divisible Components
Переглядів 1149 годин тому
Daily Leetcode Challenge- December 2024 - Day 21 Approach/Topic : DFS question link: leetcode.com/problems/maximum-number-of-k-divisible-components/description/?envType=daily-question&envId=2024-12-21 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to code every...
Daily Leetcode Challenge | DEC 20 | Reverse Odd Levels of Binary Tree
Переглядів 299 годин тому
Daily Leetcode Challenge- December 2024 - Day 20 Approach/Topic : DFS question link: leetcode.com/problems/reverse-odd-levels-of-binary-tree/?envType=daily-question&envId=2024-12-20 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to code everyday, and also to ma...
Daily Leetcode Challenge | DEC 20 | Hindi | Reverse Odd Levels of Binary Tree
Переглядів 139 годин тому
Daily Leetcode Challenge- December 2024 - Day 20 Approach/Topic : DFS question link: leetcode.com/problems/reverse-odd-levels-of-binary-tree/?envType=daily-question&envId=2024-12-20 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to code everyday, and also to ma...
Daily Leetcode Challenge | DEC 19 | Hindi | Max Chunks To Make Sorted
Переглядів 14312 годин тому
Daily Leetcode Challenge- December 2024 - Day 19 question link: leetcode.com/problems/max-chunks-to-make-sorted/?envType=daily-question&envId=2024-12-19 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to code everyday, and also to make their coding rounds-during...
Daily Leetcode Challenge | DEC 19 | Beats 100% solutions | Max Chunks To Make Sorted
Переглядів 12912 годин тому
Daily Leetcode Challenge- December 2024 - Day 19 question link: leetcode.com/problems/max-chunks-to-make-sorted/?envType=daily-question&envId=2024-12-19 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to code everyday, and also to make their coding rounds-during...
Daily Leetcode Challenge | DEC 18 | Final Prices With a Special Discount in a Shop
Переглядів 8516 годин тому
Daily Leetcode Challenge- December 2024 - Day 18 Approach/Topic : stack question link: leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/description/?envType=daily-question&envId=2024-12-18 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to co...
Daily Leetcode Challenge | DEC 18 | Hindi | Final Prices With a Special Discount in a Shop
Переглядів 3516 годин тому
Daily Leetcode Challenge- December 2024 - Day 18 Approach/Topic : stack question link: leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/description/?envType=daily-question&envId=2024-12-18 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to co...
Daily Leetcode Challenge | DEC 17 | Construct String With Repeat Limit
Переглядів 8619 годин тому
Daily Leetcode Challenge- December 2024 - Day 17 Approach/Topic : heap question link: leetcode.com/problems/construct-string-with-repeat-limit/description/?envType=daily-question&envId=2024-12-17 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to code everyday, ...
Daily Leetcode Challenge | DEC 17 | Hindi | Construct String With Repeat Limit
Переглядів 2619 годин тому
Daily Leetcode Challenge- December 2024 - Day 17 Approach/Topic : heap question link: leetcode.com/problems/construct-string-with-repeat-limit/description/?envType=daily-question&envId=2024-12-17 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community to code everyday, ...
Daily Leetcode Challenge | DEC 16 | Hindi | Final Array State After K Multiplication Operations I
Переглядів 7419 годин тому
Daily Leetcode Challenge- December 2024 - Day 16 Approach/Topic : heap question link: leetcode.com/problems/final-array-state-after-k-multiplication-operations-i/description/?envType=daily-question&envId=2024-12-16 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community...
Daily Leetcode Challenge | DEC 16 | Final Array State After K Multiplication Operations I
Переглядів 5819 годин тому
Daily Leetcode Challenge- December 2024 - Day 16 Approach/Topic : heap question link: leetcode.com/problems/final-array-state-after-k-multiplication-operations-i/description/?envType=daily-question&envId=2024-12-16 optimized approach beats 90% of the test cases Like, share and subscribe Hi, I am a SDE , at one of the Fortune 50 companies!! The intent of this channel is to motivate the community...
Weekly Contest 428 | Maximize Amount After Two Days of Conversions
Переглядів 219День тому
Weekly Contest 428 | Maximize Amount After Two Days of Conversions
Weekly Contest 428 | Button with Longest Push Time
Переглядів 153День тому
Weekly Contest 428 | Button with Longest Push Time
Daily Leetcode Challenge | DEC 15 | Medium | Maximum Average Pass Ratio
Переглядів 63День тому
Daily Leetcode Challenge | DEC 15 | Medium | Maximum Average Pass Ratio
Daily Leetcode Challenge | DEC 14 | Medium | Continuous Subarrays
Переглядів 155День тому
Daily Leetcode Challenge | DEC 14 | Medium | Continuous Subarrays
Daily Leetcode Challenge | DEC 13 | Find Score of an Array After Marking All Elements
Переглядів 36День тому
Daily Leetcode Challenge | DEC 13 | Find Score of an Array After Marking All Elements
Daily Leetcode Challenge | DEC 13 | Hindi | Find Score of an Array After Marking All Elements
Переглядів 290День тому
Daily Leetcode Challenge | DEC 13 | Hindi | Find Score of an Array After Marking All Elements
Daily Leetcode Challenge | DEC 12 | Take Gifts From the Richest Pile
Переглядів 95День тому
Daily Leetcode Challenge | DEC 12 | Take Gifts From the Richest Pile
Daily Leetcode Challenge | DEC 12 | Hindi | Take Gifts From the Richest Pile
Переглядів 29День тому
Daily Leetcode Challenge | DEC 12 | Hindi | Take Gifts From the Richest Pile
Daily Leetcode Challenge | DEC 11 | Maximum Beauty of an Array After Applying Operation
Переглядів 9314 днів тому
Daily Leetcode Challenge | DEC 11 | Maximum Beauty of an Array After Applying Operation
Daily Leetcode Challenge | DEC 10 | PART-2 | Longest Special Substring That Occurs Thrice I
Переглядів 11814 днів тому
Daily Leetcode Challenge | DEC 10 | PART-2 | Longest Special Substring That Occurs Thrice I
Daily Leetcode Challenge | DEC 10 | PART-1 | Longest Special Substring That Occurs Thrice I
Переглядів 12914 днів тому
Daily Leetcode Challenge | DEC 10 | PART-1 | Longest Special Substring That Occurs Thrice I
Daily Leetcode Challenge | DEC 9 | Python | Special Array II
Переглядів 6114 днів тому
Daily Leetcode Challenge | DEC 9 | Python | Special Array II
Daily Leetcode Challenge | DEC 9 | Hindi | Special Array II
Переглядів 4914 днів тому
Daily Leetcode Challenge | DEC 9 | Hindi | Special Array II
Daily Leetcode Challenge | DEC 8 | Two Best Non-Overlapping Events
Переглядів 17014 днів тому
Daily Leetcode Challenge | DEC 8 | Two Best Non-Overlapping Events
Daily Leetcode Challenge | DEC 7 | English | Minimum Limit of Balls in a Bag
Переглядів 3614 днів тому
Daily Leetcode Challenge | DEC 7 | English | Minimum Limit of Balls in a Bag
English Explanation: ua-cam.com/video/x2DuetSbuvI/v-deo.htmlsi=dWjrVtKIeJ2_WlKp
Hindi Explanation: ua-cam.com/video/DjUar4XnYng/v-deo.htmlsi=TLBQS0y__-hLG0MM
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: Optional[TreeNode]) -> List[int]: queue=[] if(root!=None): queue.append((root,0)) ans=[] #BFS while(queue): node,lvl=queue.pop() if(len(ans)<(lvl+1)): ans.append(node.val) else: ans[lvl]=max(ans[lvl],node.val) if(node.left!=None): queue.append((node.left,lvl+1)) if(node.right!=None): queue.append((node.right,lvl+1)) return ans
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: Optional[TreeNode]) -> List[int]: queue=[] if(root!=None): queue.append((root,0)) ans=[] #BFS while(queue): node,lvl=queue.pop() if(len(ans)<(lvl+1)): ans.append(node.val) else: ans[lvl]=max(ans[lvl],node.val) if(node.left!=None): queue.append((node.left,lvl+1)) if(node.right!=None): queue.append((node.right,lvl+1)) return ans
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: Optional[TreeNode]) -> List[int]: ans=[] def dfs(root,level=0): if(root==None): return if(len(ans)<level+1): ans.append(root.val) else: ans[level]=max(ans[level],root.val) dfs(root.left,level+1) dfs(root.right,level+1) dfs(root,0) return ans
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: Optional[TreeNode]) -> List[int]: ans=[] def dfs(root,level=0): if(root==None): return if(len(ans)<level+1): ans.append(root.val) else: ans[level]=max(ans[level],root.val) dfs(root.left,level+1) dfs(root.right,level+1) dfs(root,0) return ans
Thanku for the explanation
Glad it helped!
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def minimumOperations(self, root: Optional[TreeNode]) -> int: levelEle=defaultdict(list) countOfSwaps=0 def countSwaps(original): nonlocal countOfSwaps n=len(original) target=sorted(original) originalPosition={original[i]:i for i in range(n)} for i in range(n): if(original[i]!=target[i]): countOfSwaps+=1 swapIndex=originalPosition[target[i]] original[swapIndex]=original[i] #original[i]=target[i] originalPosition[original[i]]=swapIndex def dfs(root,level=0): if(root==None): return levelEle[level].append(root.val) dfs(root.left,level+1) dfs(root.right,level+1) dfs(root) print(levelEle) for i in levelEle.values(): countSwaps(i) return countOfSwaps # original=[7,6,8,5]->[5,6,8,7]->[5,6,8,7]->[5,6,7,8] # target =[5,6,7,8]
Please comment here, if you need Hindi Explanation of This Solution
//java import java.util.*; import java.lang.Math; class Solution { public int[] leftmostBuildingQueries(int[] heights, int[][] queries) { int q=queries.length; int n=heights.length; int[] ans=new int[q]; Arrays.fill(ans,-1); List<List<List<Integer>>> queryStore=new ArrayList<>(n); for(int i=0;i<n;i++){queryStore.add(new ArrayList<>());} PriorityQueue<List<Integer>> minHeap=new PriorityQueue<>(q,(a,b)->a.get(0)-b.get(0)); for(int i=0;i<q;i++){ int b=Math.max(queries[i][0],queries[i][1]); int a=Math.min(queries[i][0],queries[i][1]); if(a==b || heights[a]<heights[b]){ans[i]=b;} else{ queryStore.get(b).add(Arrays.asList(Math.max(heights[a],heights[b]),i)); } } for(int i=0;i<n;i++){ while(!minHeap.isEmpty() && minHeap.peek().get(0)<heights[i]){ ans[minHeap.peek().get(1)]=i; minHeap.poll(); } for(var qry:queryStore.get(i)){ minHeap.add(qry); } } return ans; } }
#Python #TC=O(n+q+qlogq)=O(n+qlogq)=O(qlogq) #SC=O(n+q) import heapq class Solution: def leftmostBuildingQueries(self, heights: List[int], queries: List[List[int]]) -> List[int]: q=len(queries) n=len(heights) ans=[-1 for _ in range(q)] #O(q) queryStore=[[] for _ in range(n)] #O(n+q) minHeap=[] #O(q) for i in range(q): #O(q) a,b=min(queries[i]),max(queries[i]) if(a==b or heights[b]>heights[a]): ans[i]=b else: queryStore[b].append((max(heights[b],heights[a]),i)) print(ans) print(queryStore) for i in range(n): #O(n) while(minHeap and minHeap[0][0]<heights[i]): __,qryIndex=heapq.heappop(minHeap) ans[qryIndex]=i for query in queryStore[i]: heapq.heappush(minHeap,query) return ans
please comment here, if you need a video with Hindi Explanation.
No need to explain in Hindi..thx for explaining in English ❤
//java // e=len(edges) // Time complexity: O(n+e) // Space complexity: O(e) import java.util.*; import java.lang.Math; class Solution { Map<Integer,List<Integer>> tree=new HashMap<>(); int ans; int[] nodeValues;int k; ///////////////////////////////////// private long dfs(int node,int parent){ long sumOfSubTree=0; for(int i:tree.get(node)){ if(i!=parent){ sumOfSubTree+=dfs(i,node); } } if((sumOfSubTree+nodeValues[node])%k==0){ ans+=1; return 0; } return sumOfSubTree+nodeValues[node]; } //////////////////////////////////////// public int maxKDivisibleComponents(int n, int[][] edges, int[] values, int k) { this.ans=0;this.k=k; this.nodeValues=values; for(int[] i:edges){ if(!tree.containsKey(i[0])){ tree.put(i[0],new ArrayList<>()); } tree.get(i[0]).add(i[1]); if(!tree.containsKey(i[1])){ tree.put(i[1],new ArrayList<>()); } tree.get(i[1]).add(i[0]); } if(tree.containsKey(0)){ dfs(0,-1); } return Math.max(ans,1); } }
#python #e=len(edges) # Time complexity: O(n+e) # Space complexity: O(e) from collections import defaultdict class Solution: def maxKDivisibleComponents(self, n: int, edges: List[List[int]], values: List[int], k: int) -> int: ans=0 tree=defaultdict(list) for i,j in edges: tree[i].append(j) tree[j].append(i) #print(tree) def dfs(node,parent): nonlocal ans sumOfSubTree=0 for i in tree[node]: if(i!=parent): sumOfSubTree+=dfs(i,node) if((sumOfSubTree+values[node])%k==0): ans+=1 return 0 return sumOfSubTree+values[node] dfs(0,-1) return max(ans,1)
We have ai to do it 😂😂😂
Only basic AI tools are FREE, so its your choice, whether you want to risk your carrier, by solely depending on AI tools.
@darshankumar5546 what you are learning now will be replaced by AI... DON'T BE DUMP IN LEARNING THIS ⁉️ Definitely what you are writing now will be replaced. No point in learning this. It may not happen immediately but definitely in the next 3-4 years. Don't risk your career too. It's career not carrier 😕
@@darshankumar5546 Don't be a programmer be a software developer.
English Explanation: ua-cam.com/video/CMFvX3lmWv8/v-deo.html
Hindi Explanation: ua-cam.com/video/AAYzImGzg5c/v-deo.html
from collections import defaultdict class Solution: def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: levelEle=defaultdict(list) def dfs(root,level=0): if(root==None): return if(level%2==1): levelEle[level].append(root.val) dfs(root.left,level+1) dfs(root.right,level+1) dfs(root) #print(levelEle) def dfs2(root,level=0): if(root==None): return if(level%2==1): root.val=levelEle[level].pop() dfs2(root.left,level+1) dfs2(root.right,level+1) dfs2(root) return root
from collections import defaultdict class Solution: def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: levelEle=defaultdict(list) def dfs(root,level=0): if(root==None): return if(level%2==1): levelEle[level].append(root.val) dfs(root.left,level+1) dfs(root.right,level+1) dfs(root) #print(levelEle) def dfs2(root,level=0): if(root==None): return if(level%2==1): root.val=levelEle[level].pop() dfs2(root.left,level+1) dfs2(root.right,level+1) dfs2(root) return root
Happy To Mention, My java,Python Solutions beat 100% of the solutions, in terms of both TC,SC .😃
import java.lang.Math; class Solution { public int maxChunksToSorted(int[] arr) { int noOfChunk=0; int TotalEleInChunk=0; int maxEleOfChunk=-1; int TotalEleInVariousChunk=0; for(int i:arr){ maxEleOfChunk=Math.max(i,maxEleOfChunk); TotalEleInChunk+=1; if(TotalEleInChunk==(maxEleOfChunk+1-TotalEleInVariousChunk)){ noOfChunk+=1; TotalEleInVariousChunk+=TotalEleInChunk; TotalEleInChunk=0; maxEleOfChunk=-1; } } return noOfChunk; } }
import java.lang.Math; class Solution { public int maxChunksToSorted(int[] arr) { int noOfChunk=0; int TotalEleInChunk=0; int maxEleOfChunk=-1; int TotalEleInVariousChunk=0; for(int i:arr){ maxEleOfChunk=Math.max(i,maxEleOfChunk); TotalEleInChunk+=1; if(TotalEleInChunk==(maxEleOfChunk+1-TotalEleInVariousChunk)){ noOfChunk+=1; TotalEleInVariousChunk+=TotalEleInChunk; TotalEleInChunk=0; maxEleOfChunk=-1; } } return noOfChunk; } }
#PYTHON SOLUTION class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: noOfChunk=0 TotalEleInChunk=0 maxEleOfChunk=-1 TotalEleInVariousChunk=0 for i in arr: maxEleOfChunk=max(i,maxEleOfChunk) TotalEleInChunk+=1 if(TotalEleInChunk==(maxEleOfChunk+1-TotalEleInVariousChunk)): noOfChunk+=1 TotalEleInVariousChunk+=TotalEleInChunk TotalEleInChunk=0 maxEleOfChunk=-1 print(i,maxEleOfChunk,TotalEleInChunk,TotalEleInVariousChunk,noOfChunk) return noOfChunk #[0,1,2,3,4,5] # [2,1,0,4,3,5] # 0,1,2 # 3,4 # 5
#PYTHON SOLUTION class Solution: def maxChunksToSorted(self, arr: List[int]) -> int: noOfChunk=0 TotalEleInChunk=0 maxEleOfChunk=-1 TotalEleInVariousChunk=0 for i in arr: maxEleOfChunk=max(i,maxEleOfChunk) TotalEleInChunk+=1 if(TotalEleInChunk==(maxEleOfChunk+1-TotalEleInVariousChunk)): noOfChunk+=1 TotalEleInVariousChunk+=TotalEleInChunk TotalEleInChunk=0 maxEleOfChunk=-1 print(i,maxEleOfChunk,TotalEleInChunk,TotalEleInVariousChunk,noOfChunk) return noOfChunk #[0,1,2,3,4,5] # [2,1,0,4,3,5] # 0,1,2 # 3,4 # 5
Hindi Explanation: ua-cam.com/video/KYBwEo6ENH0/v-deo.html
English Explanation: ua-cam.com/video/82Qr3SDSvIM/v-deo.html
# tc=O(n) # sc=O(n) class Solution: def finalPrices(self, prices: List[int]) -> List[int]: stack=[] ans=[price for price in prices] #print(ans) n=len(prices) for i in range(n): while(stack and stack[-1][0]>=prices[i]): originalprice,index=stack.pop() ans[index]=(originalprice-prices[i]) #print('originalPrice=',originalprice,'new price=',ans[index],'discount=',prices[i]) stack.append((prices[i],i)) #print(stack) #print(ans) return ans
# tc=O(n) # sc=O(n) class Solution: def finalPrices(self, prices: List[int]) -> List[int]: stack=[] ans=[price for price in prices] #print(ans) n=len(prices) for i in range(n): while(stack and stack[-1][0]>=prices[i]): originalprice,index=stack.pop() ans[index]=(originalprice-prices[i]) #print('originalPrice=',originalprice,'new price=',ans[index],'discount=',prices[i]) stack.append((prices[i],i)) #print(stack) #print(ans) return ans
# tc=O(n2) # sc=O(n) class Solution: def finalPrices(self, prices: List[int]) -> List[int]: ans=[] n=len(prices) for i in range(n): discount=0 for j in range(i+1,n): if(prices[j]<=prices[i]): discount=prices[j] break ans.append(prices[i]-discount) return ans # prices= # [8,4,6,2,3] # ans= # [4,2,4,2,3]
# tc=O(n2) # sc=O(n) class Solution: def finalPrices(self, prices: List[int]) -> List[int]: ans=[] n=len(prices) for i in range(n): discount=0 for j in range(i+1,n): if(prices[j]<=prices[i]): discount=prices[j] break ans.append(prices[i]-discount) return ans # prices= # [8,4,6,2,3] # ans= # [4,2,4,2,3]
चुकी आपने ऐसे विषय हिंदी में समझाने की कोसिस की है जो की सराहनीय है धन्यवाद | किन्तु समझाने में कुछ त्रुटियाँ हैं जैसे की आप बहुत तेजी से बोलते हैं | विषय को कैसे समझाना चाहिए यह आप Bharat Acharya Education के विडियो से सीख सखते हैं विडियो लिंक :> ua-cam.com/video/UWekjor55pc/v-deo.htmlsi=XD8yIBNu2QLU5O3s
English Explanation: ua-cam.com/video/bPWsmfO2qUA/v-deo.html
Hindi Explanation: ua-cam.com/video/Dpaz84zT4V4/v-deo.html
#approach -2 (better than optimal leetcode solution): # tc=O(n+26+26*log(26))=O(n) # sc=O(26+26)=O(const) import heapq class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: freq=[0 for i in range(26)] asciiOf_a=ord('a') for i in s: index=ord(i)-ord('a') freq[index]+=1 maxHeap=[] for i in range(26): if(freq[i]!=0): maxHeap.append([-i,freq[i]]) heapq.heapify(maxHeap) #print(freq) ans='' #print(maxHeap) while(maxHeap): index,frequency=heapq.heappop(maxHeap) index*=-1 character=chr(index+asciiOf_a) while(frequency!=0): if(ans and ans[-1]==character): #insert next largest character if(len(maxHeap)==0): return ans nextLargestCharacter=chr(maxHeap[0][0]*(-1)+asciiOf_a) maxHeap[0][1]-=1 if(maxHeap[0][1]==0): heapq.heappop(maxHeap) ans+=nextLargestCharacter #insert 'character' repeatLimit or lower, times NoOfcharsToBeWritten=min(repeatLimit,frequency) frequency-=NoOfcharsToBeWritten ans+=character*NoOfcharsToBeWritten return ans
#approach -2 (better than optimal leetcode solution): # tc=O(n+26+26*log(26))=O(n) # sc=O(26+26)=O(const) import heapq class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: freq=[0 for i in range(26)] asciiOf_a=ord('a') for i in s: index=ord(i)-ord('a') freq[index]+=1 maxHeap=[] for i in range(26): if(freq[i]!=0): maxHeap.append([-i,freq[i]]) heapq.heapify(maxHeap) #print(freq) ans='' #print(maxHeap) while(maxHeap): index,frequency=heapq.heappop(maxHeap) index*=-1 character=chr(index+asciiOf_a) while(frequency!=0): if(ans and ans[-1]==character): #insert next largest character if(len(maxHeap)==0): return ans nextLargestCharacter=chr(maxHeap[0][0]*(-1)+asciiOf_a) maxHeap[0][1]-=1 if(maxHeap[0][1]==0): heapq.heappop(maxHeap) ans+=nextLargestCharacter #insert 'character' repeatLimit or lower, times NoOfcharsToBeWritten=min(repeatLimit,frequency) frequency-=NoOfcharsToBeWritten ans+=character*NoOfcharsToBeWritten return ans
#approach -1 # tc=O(n+26*n)=O(n) # sc=O(26)=O(const) class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: freq=[0 for i in range(26)] asciiOf_a=ord('a') for i in s: index=ord(i)-ord('a') freq[index]+=1 #print(freq) ans='' def nextLargestChar(index): nonlocal freq for i in range(index-1,-1,-1): if(freq[i]!=0): freq[i]-=1 return chr(i+asciiOf_a) return '-1' for i in range(25,-1,-1): if(freq[i]==0): continue character=chr(i+asciiOf_a) while(freq[i]!=0): if(ans and ans[-1]==character): #insert next largest character nextLargestCharacter=nextLargestChar(i) if(nextLargestCharacter=='-1'): return ans ans+=nextLargestCharacter #insert 'character' repeatLimit or lower, times frequency=min(repeatLimit,freq[i]) freq[i]-=frequency ans+=character*frequency return ans # ab vs ac => ac > ab # ab vs abc => abc > ab
#approach -1 # tc=O(n+26*n)=O(n) # sc=O(26)=O(const) class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: freq=[0 for i in range(26)] asciiOf_a=ord('a') for i in s: index=ord(i)-ord('a') freq[index]+=1 #print(freq) ans='' def nextLargestChar(index): nonlocal freq for i in range(index-1,-1,-1): if(freq[i]!=0): freq[i]-=1 return chr(i+asciiOf_a) return '-1' for i in range(25,-1,-1): if(freq[i]==0): continue character=chr(i+asciiOf_a) while(freq[i]!=0): if(ans and ans[-1]==character): #insert next largest character nextLargestCharacter=nextLargestChar(i) if(nextLargestCharacter=='-1'): return ans ans+=nextLargestCharacter #insert 'character' repeatLimit or lower, times frequency=min(repeatLimit,freq[i]) freq[i]-=frequency ans+=character*frequency return ans # ab vs ac => ac > ab # ab vs abc => abc > ab
English Explanation: ua-cam.com/video/_jZhgq0B57o/v-deo.html
Hindi Explanation: ua-cam.com/video/-siSTSZ1Dyo/v-deo.html
import heapq class Solution: def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]: minheap=[] n=len(nums) for i in range(n): heapq.heappush(minheap,(nums[i],i)) #print(minheap) for i in range(k): #print('k=',k) value,indexx=minheap[0] value*=multiplier nums[indexx]=value heapq.heapreplace(minheap,(value,indexx)) #print(minheap) return nums
import heapq class Solution: def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]: minheap=[] n=len(nums) for i in range(n): heapq.heappush(minheap,(nums[i],i)) #print(minheap) for i in range(k): #print('k=',k) value,indexx=minheap[0] value*=multiplier nums[indexx]=value heapq.heapreplace(minheap,(value,indexx)) #print(minheap) return nums
#tc=O(n+klogn) #sc=O(n) import heapq class Solution: def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]: minheap=[] n=len(nums) for i in range(n): #O(n) minheap.append((nums[i],i)) heapq.heapify(minheap) #O(n) print(minheap) for i in range(k): print('k=',k) value,indexx=heapq.heappop(minheap) value*=multiplier nums[indexx]=value heapq.heappush(minheap,(value,indexx)) print(minheap) return nums
#tc=O(n+klogn) #sc=O(n) import heapq class Solution: def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]: minheap=[] n=len(nums) for i in range(n): #O(n) minheap.append((nums[i],i)) heapq.heapify(minheap) #O(n) print(minheap) for i in range(k): print('k=',k) value,indexx=heapq.heappop(minheap) value*=multiplier nums[indexx]=value heapq.heappush(minheap,(value,indexx)) print(minheap) return nums
contest link: leetcode.com/contest/weekly-contest-428/ Please let me know, if you need Solutions in Hindi , also.
from collections import defaultdict import heapq class Solution: def maxAmount(self, initialCurrency: str, pairs1: List[List[str]], rates1: List[float], pairs2: List[List[str]], rates2: List[float]) -> float: graph=defaultdict(lambda:defaultdict(int)) for i in range(len(pairs1)): fromm,too=pairs1[i] rate=rates1[i] graph[(fromm,1)][(too,1)]=rate graph[(too,1)][(fromm,1)]=1/rate if(too!=initialCurrency): graph[(too,1)][(too,2)]=1 if(fromm!=initialCurrency): graph[(fromm,1)][(fromm,2)]=1 for i in range(len(pairs2)): fromm,too=pairs2[i] rate=rates2[i] graph[(fromm,2)][(too,2)]=rate graph[(too,2)][(fromm,2)]=1/rate amount=defaultdict(int) #print(graph) # Using Dijkstra's algorithm maxHeap=[(-1,(initialCurrency,1))] while(maxHeap): value,(currency,day)=heapq.heappop(maxHeap) value*=-1 if(amount[(currency,day)]>value): continue #print(currency,day,amount[(currency,day)],value) amount[(currency,day)]=value # visiting all the nodes , adjacent to current node for node,rate in graph[(currency,day)].items(): nextCurrency,nextDay=node if(nextDay<day): continue nextValue=value*rate if(nextValue>amount[node]): heapq.heappush(maxHeap,(-1*nextValue,node)) #print(amount) return max( amount[(initialCurrency,2)], 1) # # let us say currencies are :A,B,C # in my solution, these will be the nodes: # (A,1),(B,1),(C,1) # representing day1 nodes # (A,2),(B,2),(C,2) # representing day2 nodes
Please comment , if you need the video in Hindi Language Also
Please comment , if you need the video in Hindi Language Also
class Solution: def buttonWithLongestTime(self, events: List[List[int]]) -> int: ans=[events[0][0],events[0][1]] n=len(events) for i in range(1,n): timeTaken=events[i][1]-events[i-1][1] if(timeTaken>ans[1]): ans[0]=events[i][0] ans[1]=timeTaken elif(timeTaken==ans[1]): ans[0]=min(ans[0],events[i][0]) return ans[0]
# tc=O(klogn+nlogn)=O(nlogn) # sc=O(n) import heapq class Solution: def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: sumOfPassRatios=0 n=len(classes) minHeap=[] for passStudents,totalStudents in classes: passRatio=(passStudents/totalStudents) sumOfPassRatios+=passRatio #if a extraStudents is added, what will be new passRatio newPassRatio=(passStudents+1)/(totalStudents+1) diff=newPassRatio-passRatio #difference between new ratio and original heapq.heappush(minHeap,(-diff,passStudents+1,totalStudents+1)) #-ve sign to simulate max heap #print('original avg pass ratio:,sumOfPassRatios/n) #print('heap:',minHeap) for i in range(extraStudents): maxDiff,passStudents,totalStudents=heapq.heappop(minHeap) maxDiff*=-1 #print('adding:',maxDiff) sumOfPassRatios+=maxDiff #if a extraStudents is added, what will be new passRatio newPassRatio=(passStudents+1)/(totalStudents+1) diff=newPassRatio-(passStudents/totalStudents) #difference between new ratio and original heapq.heappush(minHeap,(-diff,passStudents+1,totalStudents+1)) return sumOfPassRatios/n # class 1 # 1/2=0.5 # if 1 student is added: 2/3=0.66 # diff= 0.16 # class 2 # 3/5=0.6 # if 1 student is added: 4/6=0.66 # diff= 0.06 # its best to add a student in class 1, as diff is highest. # after adding a student in class 1: # class 1 # 2/3=0.66 # if 1 student is added: 3/4=0.75 # diff= 0.09 # class 2 # 3/5=0.6 # if 1 student is added: 4/6=0.66 # diff= 0.06
# tc= O(n) # sc =O(n) from collections import deque class Solution: def continuousSubarrays(self, nums: List[int]) -> int: minQue=deque() maxQue=deque() l,r=0,0 countt=0 n=len(nums) for r in range(n): #heapq.heappush(minQue,(nums[r],r)) while(minQue and minQue[-1][0]>nums[r]): minQue.pop() minQue.append((nums[r],r)) #heapq.heappush(maxQue,(-nums[r],r)) while(maxQue and maxQue[-1][0]<nums[r]): maxQue.pop() maxQue.append((nums[r],r)) if(abs(maxQue[0][0]-minQue[0][0])>2): #print('->',minQue,maxQue) while(minQue and maxQue and abs(maxQue[0][0]-minQue[0][0])>2): l+=1 while(minQue and minQue[0][1]<l): minQue.popleft() while(maxQue and maxQue[0][1]<l): maxQue.popleft() #print(minQue,maxQue) countt+=(r-l+1) #print(nums[l:r+1],countt) return countt # nums = [5,4,2,4] # minQue=[5,4] # after adding 2: # minQue=[2] # after adding 4: # minQue=[2,4]