Пікірлер
@HariKrishnan-yj8yy
@HariKrishnan-yj8yy 5 күн бұрын
FAANG ipo MAANG aaiducha😂
@salihedneer8975
@salihedneer8975 5 күн бұрын
@Tony2169-y
@Tony2169-y 5 күн бұрын
Mango!
@indiccoder
@indiccoder 5 күн бұрын
Is O for OpenAI?
@Tony2169-y
@Tony2169-y 5 күн бұрын
Yup
@indiccoder
@indiccoder 6 күн бұрын
CPP Solution: class Solution { public: bool canVisitAllRooms(vector<vector<int>>& rooms) { // Initialize a stack with the first room (room 0) stack<int> keys; keys.push(0); // Create a set to track visited rooms unordered_set<int> visited; // Perform a depth-first search using the stack while (!keys.empty()) { // Get the next key (room) from the stack int key = keys.top(); keys.pop(); // If the room hasn't been visited yet if (visited.find(key) == visited.end()) { // Mark the room as visited visited.insert(key); // Add all keys (rooms) from the current room to the stack for (int nextKey : rooms[key]) { keys.push(nextKey); } } } // Return true if all rooms have been visited, otherwise false return visited.size() == rooms. Size(); } };
@Vijaykrishnan2000
@Vijaykrishnan2000 4 күн бұрын
Topo sort
@indiccoder
@indiccoder 6 күн бұрын
Java Solution: class Solution { public boolean canVisitAllRooms(List<List<Integer>> rooms) { // Initialize a stack with the first room (room 0) Stack<Integer> keys = new Stack<>(); keys.push(0); // Create a set to track visited rooms Set<Integer> visited = new HashSet<>(); // Perform a depth-first search using the stack while (!keys.isEmpty()) { // Get the next key (room) from the stack int key = keys.pop(); // If the room hasn't been visited yet if (!visited.contains(key)) { // Mark the room as visited visited.add(key); // Add all keys (rooms) from the current room to the stack for (int nextKey : rooms.get(key)) { keys.push(nextKey); } } } // Return true if all rooms have been visited, otherwise false return visited.size() == rooms. Size(); } }
@indiccoder
@indiccoder 6 күн бұрын
Python Solution: class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: # Initialize a stack with the first room (room 0). keys = [0] # Create a set to track visited rooms. visited = set() # Perform a depth-first search using the stack. while keys: # Get the next key (room) from the stack. key = keys.pop() # If the room hasn't been visited yet: if key not in visited: # Mark the room as visited. visited.add(key) # Add all keys (rooms) from the current room to the stack. keys.extend(rooms[key]) # Return True if all rooms have been visited, otherwise False. return len(rooms) == len(visited)
@indiccoder
@indiccoder 7 күн бұрын
CPP Solution: class Solution { public: int countPalindromicSubsequence(std::string s) { int res = 0; std::set<char> unique_chars(s.begin(), s.end()); // Collect unique characters in the string for (char ch : unique_chars) { size_t l = s.find(ch); // Find the first occurrence of the character size_t r = s.rfind(ch); // Find the last occurrence of the character if (r > l + 1) { // Check if there are characters in between std::unordered_set<char> between_chars(s.begin() + l + 1, s.begin() + r); // Collect unique characters between l and r res += between_chars.size(); // Add the count of unique characters } } return res; // Return the total count } };
@indiccoder
@indiccoder 7 күн бұрын
Java Solution: class Solution { public int countPalindromicSubsequence(String s) { int res = 0; // Iterate through characters 'a' to 'z' for (char ch = 'a'; ch <= 'z'; ch++) { int l = s.indexOf(ch); // Find the first occurrence of the character int r = s.lastIndexOf(ch); // Find the last occurrence of the character if (r > l + 1) { // Check if there are characters in between HashSet<Character> uniqueChars = new HashSet<>(); for (int i = l + 1; i < r; i++) { uniqueChars.add(s.charAt(i)); // Collect unique characters between l and r } res += uniqueChars.size(); // Add the count of unique characters } } return res; // Return the total count } }
@indiccoder
@indiccoder 7 күн бұрын
Python Solution: class Solution: def countPalindromicSubsequence(self, s: str) -> int: res = 0 # Iterate over unique characters in the string for ch in set(s): l, r = s.find(ch), s.rfind(ch) # Find first and last occurrence of the character if r > l + 1: # Check if there are characters in between res += len(set(s[l+1:r])) # Count unique characters between l and r return res # Return the total count
@indiccoder
@indiccoder 7 күн бұрын
CPP Solution: class Solution { public: int waysToSplitArray(vector<int>& nums) { // Calculate the total sum of the array long long totalSum = 0; for (int num : nums) { totalSum += num; } // Initialize left sum and count of valid splits long long leftSum = 0; int splits = 0; // Iterate through the array except the last element for (size_t i = 0; i < nums.size() - 1; ++i) { // Add the current element to the left sum leftSum += nums[i]; // Check if the left sum is greater than or equal to the right sum if (leftSum >= totalSum - leftSum) { // Increment the count of valid splits ++splits; } } // Return the total count of valid splits return splits; } };
@indiccoder
@indiccoder 7 күн бұрын
Java Solution: class Solution { public int waysToSplitArray(int[] nums) { // Calculate the total sum of the array long totalSum = 0; for (int num : nums) { totalSum += num; } // Initialize left sum and count of valid splits long leftSum = 0; int splits = 0; // Iterate through the array except the last element for (int i = 0; i < nums.length - 1; i++) { // Add the current element to the left sum leftSum += nums[i]; // Check if the left sum is greater than or equal to the right sum if (leftSum >= totalSum - leftSum) { // Increment the count of valid splits splits++; } } // Return the total count of valid splits return splits; } }
@indiccoder
@indiccoder 7 күн бұрын
Python Solution: class Solution: def waysToSplitArray(self, nums: List[int]) -> int: # Calculate the total sum of the array totalSum = sum(nums) # Initialize left sum and count of valid splits leftSum = 0 splits = 0 # Iterate through the array except the last element for num in nums[:-1]: # Add the current element to the left sum leftSum += num # Check if the left sum is greater than or equal to the right sum if leftSum >= totalSum - leftSum: # Increment the count of valid splits splits += 1 # Return the total count of valid splits return splits
@indiccoder
@indiccoder 7 күн бұрын
CPP Solution: class Solution { public: string shiftingLetters(string s, vector<vector<int>>& shifts) { int n = s.length(); vector<int> delta(n + 1, 0); // Initialize the difference array for cumulative shifts // Process each shift operation for (const auto& shift : shifts) { int start = shift[0], end = shift[1], dir = shift[2]; if (dir == 0) { // Backward shift delta[start] -= 1; delta[end + 1] += 1; } else { // Forward shift delta[start] += 1; delta[end + 1] -= 1; } } int shift = 0; // To keep track of cumulative shifts // Apply the shifts to each character in the string for (int i = 0; i < n; i++) { shift += delta[i]; // Update cumulative shift at index i // Calculate the new character with wrapping around s[i] = (char)((s[i] - 'a' + shift % 26 + 26) % 26 + 'a'); } return s; // Return the modified string } };
@indiccoder
@indiccoder 7 күн бұрын
Java Solution: class Solution { public String shiftingLetters(String s, int[][] shifts) { int n = s.length(); int[] delta = new int[n + 1]; // Initialize the difference array for cumulative shifts // Process each shift operation for (int[] shift : shifts) { int start = shift[0], end = shift[1], dir = shift[2]; if (dir == 0) { // Backward shift delta[start] -= 1; delta[end + 1] += 1; } else { // Forward shift delta[start] += 1; delta[end + 1] -= 1; } } char[] result = s.toCharArray(); // Convert the string to a character array for in-place modification int shift = 0; // To keep track of cumulative shifts // Apply the shifts to each character in the string for (int i = 0; i < n; i++) { shift += delta[i]; // Update cumulative shift at index i // Calculate the new character with wrapping around result[i] = (char)((result[i] - 'a' + shift % 26 + 26) % 26 + 'a'); } return new String(result); // Convert the character array back to a string } }
@indiccoder
@indiccoder 7 күн бұрын
Python Solution: class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: n = len(s) delta = [0] * (n + 1) # Initialize the difference array for cumulative shifts # Process each shift operation for start, end, dir in shifts: if dir == 0: # Backward shift delta[start] -= 1 delta[end + 1] += 1 else: # Forward shift delta[start] += 1 delta[end + 1] -= 1 # Convert the string to a mutable list s = list(s) shift = 0 # To keep track of cumulative shifts # Apply the shifts to each character in the string for i in range(n): shift += delta[i] # Update cumulative shift at index i # Calculate the new character with wrapping around s[i] = chr((ord(s[i]) - ord('a') + shift) % 26 + ord('a')) return ''.join(s) # Join the modified list back into a string
@sibiranganath
@sibiranganath 8 күн бұрын
Best video for the problem in tamil Need more video like this
@indiccoder
@indiccoder 7 күн бұрын
Thank you, Bro!
@mohanp7469
@mohanp7469 9 күн бұрын
nice...
@indiccoder
@indiccoder 7 күн бұрын
Thank you, Bro!
@madhumitha_ravichandran26
@madhumitha_ravichandran26 10 күн бұрын
Very easy to understand the logic..Thanks bro
@indiccoder
@indiccoder 10 күн бұрын
You're welcome. I'm glad the video helped 😁
@indiccoder
@indiccoder 11 күн бұрын
CPP Solution: class Solution { public: std::vector<int> vowelStrings(std::vector<std::string>& words, std::vector<std::vector<int>>& queries) { // Define a set of vowels std::unordered_set<char> vowels{'a', 'e', 'i', 'o', 'u'}; int n = words.size(); // Total number of words std::vector<int> prefixCount(n + 1, 0); // Prefix sum array // Calculate prefix sums for words starting and ending with vowels for (int i = 0; i < n; ++i) { if (vowels.count(words[i].front()) && vowels.count(words[i].back())) { prefixCount[i + 1] = prefixCount[i] + 1; } else { prefixCount[i + 1] = prefixCount[i]; } } std::vector<int> result; // Process each query to get the count of valid words in the range for (const auto& query : queries) { int l = query[0], r = query[1]; result.push_back(prefixCount[r + 1] - prefixCount[l]); } return result; } };
@indiccoder
@indiccoder 11 күн бұрын
Java Solution: class Solution { public int[] vowelStrings(String[] words, int[][] queries) { // Define a set of vowels Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); int n = words.length; // Total number of words int[] prefixCount = new int[n + 1]; // Prefix sum array // Calculate prefix sums for words starting and ending with vowels for (int i = 0; i < n; i++) { String word = words[i]; if (vowels.contains(word.charAt(0)) && vowels.contains(word.charAt(word.length() - 1))) { prefixCount[i + 1] = prefixCount[i] + 1; } else { prefixCount[i + 1] = prefixCount[i]; } } int[] result = new int[queries.length]; // Process each query to get the count of valid words in the range for (int i = 0; i < queries.length; i++) { int l = queries[i][0], r = queries[i][1]; result[i] = prefixCount[r + 1] - prefixCount[l]; } return result; } }
@indiccoder
@indiccoder 11 күн бұрын
Python Solution: class Solution: def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: # Define a set of vowels vowels = set(['a', 'e', 'i', 'o', 'u']) run = 0 # Running count of valid words N = len(words) # Total number of words runCount = [0] * (N + 1) # Prefix sum array to store running counts # Calculate prefix sums for words starting and ending with vowels for i, word in enumerate(words): if word[0] in vowels and word[-1] in vowels: # Check vowel condition run += 1 runCount[i + 1] = run # Update prefix sum array result = [] # List to store query results # Process each query to get the count of valid words in the range for l, r in queries: result.append(runCount[r + 1] - runCount[l]) # Calculate result for range return result
@satwiksukhavasi54
@satwiksukhavasi54 11 күн бұрын
Nice work buddy
@indiccoder
@indiccoder 11 күн бұрын
Thank you! 😄
@MohanDiaries-h6u
@MohanDiaries-h6u 11 күн бұрын
Well explained...... post vidoes category wise like, arrays , linked List , stack .
@indiccoder
@indiccoder 10 күн бұрын
Sure bro, I'll do that soon 😁
@MohanDiaries-h6u
@MohanDiaries-h6u 11 күн бұрын
You are awesome bro ...........
@indiccoder
@indiccoder 11 күн бұрын
CPP Solution: class Solution { public: vector<int> successfulPairs(vector<int>& spells, vector<int>& potions, long long success) { sort(potions.begin(), potions.end()); // Sort the potions array for binary search int n = potions.size(); // Total number of potions vector<int> res; // Result vector to store the count of successful pairs for (int spell : spells) { int l = 0, u = n - 1; // Initialize binary search boundaries while (l <= u) { // Perform binary search int m = l + (u - l) / 2; // Calculate the middle index if ((long long) potions[m] * spell < success) { // Check if the pair is unsuccessful l = m + 1; // Move to the right half } else { u = m - 1; // Move to the left half } } res.push_back(n - l); // Store the count of successful pairs for the spell } return res; // Return the result vector } };
@indiccoder
@indiccoder 11 күн бұрын
Java Solution: class Solution { public int[] successfulPairs(int[] spells, int[] potions, long success) { Arrays.sort(potions); // Sort the potions array for binary search int n = potions.length; // Total number of potions int[] res = new int[spells.length]; // Result array to store the count of successful pairs for (int i = 0; i < spells.length; i++) { int spell = spells[i]; int l = 0, u = n - 1; // Initialize binary search boundaries while (l <= u) { // Perform binary search int m = l + (u - l) / 2; // Calculate the middle index if ((long) potions[m] * spell < success) { // Check if the pair is unsuccessful l = m + 1; // Move to the right half } else { u = m - 1; // Move to the left half } } res[i] = n - l; // Store the count of successful pairs for the spell } return res; // Return the result array } }
@indiccoder
@indiccoder 11 күн бұрын
Python Solution: class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions.sort() # Sort the potions array for binary search n = len(potions) # Total number of potions res = [] # Result array to store the number of successful pairs for each spell for spell in spells: l, u = 0, n-1 # Initialize binary search boundaries while l <= u: # Perform binary search m = l + (u - l) // 2 # Calculate the middle index if potions[m] * spell < success: # Check if the pair is unsuccessful l = m + 1 # Move to the right half else: u = m - 1 # Move to the left half res.append(n - l) # Append the count of successful pairs for the spell return res # Return the result array
@MohanDiaries-h6u
@MohanDiaries-h6u 12 күн бұрын
Your teaching makes me understand better than other tamil channel. I here to watch your videos . Thank you so much for contribution
@MohanDiaries-h6u
@MohanDiaries-h6u 12 күн бұрын
Awesome man ......!
@MohanDiaries-h6u
@MohanDiaries-h6u 12 күн бұрын
well explained , very nice
@indiccoder
@indiccoder 12 күн бұрын
Thank you! I'm glad you liked it 😊
@indiccoder
@indiccoder 12 күн бұрын
CPP Solution: class Solution { public: int longestCommonSubsequence(string text1, string text2) { int m = text1.size(), n = text2.size(); // Get lengths of both strings vector<vector<int>> grid(m + 1, vector<int>(n + 1, 0)); // Initialize DP grid with zeros for (int i = 1; i <= m; i++) { // Traverse each character in text1 for (int j = 1; j <= n; j++) { // Traverse each character in text2 if (text1[i - 1] == text2[j - 1]) { // Characters match grid[i][j] = grid[i - 1][j - 1] + 1; // Add 1 to the diagonal value } else { // Characters don't match grid[i][j] = max(grid[i - 1][j], grid[i][j - 1]); // Take max from top or left cell } } } return grid[m][n]; // Return the bottom-right value as the result } };
@indiccoder
@indiccoder 12 күн бұрын
Java Solution: class Solution { public int longestCommonSubsequence(String text1, String text2) { int m = text1.length(), n = text2.length(); // Get lengths of both strings int[][] grid = new int[m + 1][n + 1]; // Initialize DP grid with zeros for (int i = 1; i <= m; i++) { // Traverse each character in text1 for (int j = 1; j <= n; j++) { // Traverse each character in text2 if (text1.charAt(i - 1) == text2.charAt(j - 1)) { // Characters match grid[i][j] = grid[i - 1][j - 1] + 1; // Add 1 to the diagonal value } else { // Characters don't match grid[i][j] = Math.max(grid[i - 1][j], grid[i][j - 1]); // Take max from top or left cell } } } return grid[m][n]; // Return the bottom-right value as the result } }
@indiccoder
@indiccoder 12 күн бұрын
Python Solution: class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m, n = len(text1), len(text2) # Get lengths of both strings grid = [[0 for j in range(n+1)] for i in range(m+1)] # Initialize DP grid with zeros for i in range(1, m+1): # Traverse each character in text1 for j in range(1, n+1): # Traverse each character in text2 if text1[i-1] == text2[j-1]: # Characters match grid[i][j] = grid[i-1][j-1] + 1 # Add 1 to the diagonal value else: # Characters don't match grid[i][j] = max(grid[i-1][j], grid[i][j-1]) # Take the max from top or left cell return grid[-1][-1] # Return the bottom-right value as the result
@indiccoder
@indiccoder 13 күн бұрын
Java Solution: class Solution { public int countGoodStrings(int low, int high, int zero, int one) { int mod = 1000000007; // Modulo to prevent overflow int[] ways = new int[high + 1]; // Array to store ways to construct strings of each length ways[0] = 1; // Base case: 1 way to construct an empty string // Calculate ways for each length up to 'high' for (int i = 1; i <= high; i++) { if (i - zero >= 0) { ways[i] = (ways[i] + ways[i - zero]) % mod; // Add ways by appending 'zero' } if (i - one >= 0) { ways[i] = (ways[i] + ways[i - one]) % mod; // Add ways by appending 'one' } } int result = 0; // Sum up the valid ways for lengths between 'low' and 'high' for (int i = low; i <= high; i++) { result = (result + ways[i]) % mod; } return result; // Return the total count } }
@indiccoder
@indiccoder 13 күн бұрын
CPP Solution: class Solution { public: int countGoodStrings(int low, int high, int zero, int one) { const int mod = 1000000007; // Modulo to prevent overflow vector<int> ways(high + 1, 0); // Array to store ways to construct strings of each length ways[0] = 1; // Base case: 1 way to construct an empty string // Calculate ways for each length up to 'high' for (int i = 1; i <= high; i++) { if (i - zero >= 0) { ways[i] = (ways[i] + ways[i - zero]) % mod; // Add ways by appending 'zero' } if (i - one >= 0) { ways[i] = (ways[i] + ways[i - one]) % mod; // Add ways by appending 'one' } } int result = 0; // Sum up the valid ways for lengths between 'low' and 'high' for (int i = low; i <= high; i++) { result = (result + ways[i]) % mod; } return result; // Return the total count } };
@indiccoder
@indiccoder 13 күн бұрын
Python Solution: class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: mod = 10**9+7 # Modulo to prevent overflow and keep the result within limits ways = [0] * (high + 1) # Array to store the number of ways to build strings of each length ways[0] = 1 # Base case: 1 way to construct an empty string # Loop through each length from 1 to 'high' and calculate the number of ways to construct it for i in range(1, high + 1): if i - zero >= 0: # If the current length is greater than or equal to 'zero' ways[i] = (ways[i] + ways[i - zero]) % mod # Add the ways of the previous length (i - zero) if i - one >= 0: # If the current length is greater than or equal to 'one' ways[i] = (ways[i] + ways[i - one]) % mod # Add the ways of the previous length (i - one) # Return the sum of valid ways for lengths between 'low' and 'high' (inclusive) return sum(ways[low:high + 1]) % mod
@xMrEleven
@xMrEleven 14 күн бұрын
GOLang Solution ; func findMinArrowShots(points [][]int) int { sort.Slice(points, func(i, j int) bool { if points[i][1] == points[j][1] { return points[i][0] < points[j][0] } return points[i][1] < points[j][1] }) end := -1 arrow := 0 for _ , point := range points { if point[0] > end { arrow++ end = point[1] } } return arrow }
@sathishg3636
@sathishg3636 16 күн бұрын
super explnation broo
@indiccoder
@indiccoder 13 күн бұрын
Thank you, bro! 😁
@indiccoder
@indiccoder 16 күн бұрын
Python Solution: class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: # Sort the balloons by their end positions # This helps us group overlapping balloons together points.sort(key=lambda balloon: balloon[1]) # Initialize the count of arrows and the end of the last burst balloon arrows, end = 0, -float('inf') # Iterate through each balloon for balloon in points: # If the current balloon's start is after the last balloon's end if balloon[0] > end: arrows += 1 # Increment the arrow count end = balloon[1] # Update the end to the current balloon's end # Return the total number of arrows needed return arrows
@indiccoder
@indiccoder 16 күн бұрын
Java Solution: class Solution { public int findMinArrowShots(int[][] points) { // Sort balloons by their end points Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1])); int arrows = 0; // Count of arrows needed long end = Long.MIN_VALUE; // Track the end of the last balloon burst for (int[] balloon : points) { // If the current balloon starts after the last end point if (balloon[0] > end) { arrows++; // Increment arrow count end = balloon[1]; // Update the end point } } return arrows; // Return total arrows needed } }
@indiccoder
@indiccoder 16 күн бұрын
CPP Solution: class Solution { public: int findMinArrowShots(std::vector<std::vector<int>>& points) { // Sort balloons by their end points std::sort(points.begin(), points.end(), [](const std::vector<int>& a, const std::vector<int>& b) { return a[1] < b[1]; }); int arrows = 0; // Count of arrows needed long long end = LLONG_MIN; // Track the end of the last balloon burst for (const auto& balloon : points) { // If the current balloon starts after the last end point if (balloon[0] > end) { arrows++; // Increment arrow count end = balloon[1]; // Update the end point } } return arrows; // Return total arrows needed } };
@themythofsisyphos
@themythofsisyphos 17 күн бұрын
Those who understood the solution, try to solve it using 1D array. It will help you understand DP more. Thanks for the clear explanation.
@indiccoder
@indiccoder 17 күн бұрын
Hey everyone! Starting from this video, the CPP Solution will also be provided. Please find the CPP solution with the same logic in the comments below.
@indiccoder
@indiccoder 17 күн бұрын
Python Solution: class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: # Sort intervals by their end value intervals.sort(key=lambda x: x[1]) erase, end = 0, -float('inf') # Initialize counters for interval in intervals: if interval[0] < end: # Overlap detected erase += 1 else: end = interval[1] # Update end to current interval's end return erase # Return count of intervals to remove
@indiccoder
@indiccoder 17 күн бұрын
CPP Solution: class Solution { public: int eraseOverlapIntervals(vector<vector<int>>& intervals) { // Sort the intervals based on their end values in ascending order sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; }); int erase = 0; // Variable to count the number of overlapping intervals to be erased int end = INT_MIN; // Variable to track the end value of the last non-overlapping interval // Iterate through each interval in the sorted list for (const auto& interval : intervals) { // If the start value of the current interval is less than the end of the last interval, // it indicates an overlap if (interval[0] < end) { erase++; // Increment the count of intervals to erase } else { // Update the end value to the current interval's end // This marks the current interval as part of the non-overlapping set end = interval[1]; } } // Return the total number of intervals that need to be removed to eliminate overlaps return erase; } };
@indiccoder
@indiccoder 17 күн бұрын
Java Solution: class Solution { public int eraseOverlapIntervals(int[][] intervals) { // Sort the intervals based on their end values in ascending order // This ensures we process the interval that ends the earliest first Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1])); int erase = 0; // Variable to count the number of overlapping intervals to be erased int end = Integer.MIN_VALUE; // Variable to track the end value of the last non-overlapping interval // Iterate through each interval in the sorted list for (int[] interval : intervals) { // If the start value of the current interval is less than the end of the last interval, // it indicates an overlap if (interval[0] < end) { erase++; // Increment the count of intervals to erase } else { // Update the end value to the current interval's end // This marks the current interval as part of the non-overlapping set end = interval[1]; } } // Return the total number of intervals that need to be removed to eliminate overlaps return erase; } }
@enter486
@enter486 18 күн бұрын
bro in Python code, we are updating the q values in 21 & 23, doesn't this affect the exit condition of for loop in len(q) ?
@indiccoder
@indiccoder 18 күн бұрын
Great question! In Python, when we create a for variable in range(len(data_structure)) loop, the range of values for the variable is determined at the time the loop is created. Therefore, even if the length of the data structure changes during the loop, it does not affect the number of iterations the loop executes
@b466y
@b466y 18 күн бұрын
Bro if the queue is getting updated with new children, how it is going to calculate level max of the same level. since new children are from new level added to the queue. I could not understand.
@indiccoder
@indiccoder 18 күн бұрын
Great Question, Bro! In Python, when we use "for i in range(len(data_structure))": the range is generated at the time the for loop is created and does not dynamically update. So, even if the queue grows as children are added, the loop only executes the same number of times as there were nodes in the current level at the time of the loop's creation (i.e., when the range was defined). This is because the queue only contained the current level's nodes at the time the for loop was created. However, in Java and C++, the for loop condition can dynamically update when we use "i < queue.size()". To avoid this, we adjust the code slightly by first calculating the number of nodes in the current level before creating the for loop with a line like "int size = q.size();". Then, we use "i < size" as the loop condition. This ensures the for loop executes exactly as many times as there are nodes in the current level, regardless of any changes to the queue during the loop execution.
@b466y
@b466y 18 күн бұрын
@@indiccoder Ohhh understood now, great video! keep posting.
@indiccoder
@indiccoder 19 күн бұрын
Python Solution: class Solution: def largestValues(self, root: Optional[TreeNode]) -> List[int]: if not root: return [] # Return empty list if tree is empty levelMax = [] # List to store max values for each level queue = deque([root]) # Initialize queue with the root node while queue: currMax = queue[0].val # Start with the first node's value for the level for i in range(len(queue)): # Process all nodes in the current level node = queue.popleft() # Remove the front node currMax = max(currMax, node.val) # Update max value for the level if node.left: queue.append(node.left) # Add left child if exists if node.right: queue.append(node.right) # Add right child if exists levelMax.append(currMax) # Store the max value of the level return levelMax # Return the list of largest values
@indiccoder
@indiccoder 19 күн бұрын
CPP Solution: class Solution { public: vector<int> largestValues(TreeNode* root) { if (!root) { return {}; // If tree is empty, return an empty vector } vector<int> levelMax; // To store max values for each level queue<TreeNode*> q; // Queue for level-order traversal q.push(root); // Start with the root while (!q.empty()) { int currMax = INT_MIN; // Initialize current level max to minimum integer value int size = q.size(); // Number of nodes in the current level for (int i = 0; i < size; ++i) { TreeNode* node = q.front(); q.pop(); currMax = max(currMax, node->val); // Update the max value for the level if (node->left) { q.push(node->left); // Add left child to the queue if it exists } if (node->right) { q.push(node->right); // Add right child to the queue if it exists } } levelMax.push_back(currMax); // Append the max value of the current level to the result } return levelMax; // Return the vector of largest values for each level } };