🔷 Day 22- 30DaysChallenge(Leetcode Problem): Non-overlapping Intervals 🌟 Problem: Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Note that intervals which only touch at a point are non-overlapping. For example, [1, 2] and [2, 3] are non-overlapping. 🧠Solution: class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort() count = 0 for i in range(1, len(intervals)): if intervals[i][0] < intervals[i-1][1]: if intervals[i][1] < intervals[i-1][1]: intervals[i-1] = intervals[i] else: intervals[i] = intervals[i-1] count += 1 return count #DSA #Python #CodingChallenge #30dayschallenge #Leetcode
How to remove overlapping intervals in Python
More Relevant Posts
-
🔷 Day 23- 30DaysChallenge(Leetcode Problem): Sort Vowels in a String 🌟 Problem: Given a 0-indexed string s, permute s to get a new string t such that: All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i]. The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j]. Return the resulting string. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels. 🧠Solution: class Solution: def sortVowels(self, s: str) -> str: stack = [] vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} for x in s: if x in vowels: stack.append(x) stack.sort(reverse=True) res = '' for x in s: if x in vowels: res += stack.pop() else: res += x return res #DSA #Python #CodingChallenge #30dayschallenge #Leetcode
To view or add a comment, sign in
-
🔷 Day 20- 30DaysChallenge(Leetcode Problem): Merge Sorted Array 🌟 Problem: You are given two integer arrays, nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2, respectively. Merge nums1 and nums2 into a single array sorted in non-decreasing order. The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n. 🧠Solution: class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: tmp_nums1 = nums1[:m] # copy the non zero elements of nums1 p1 = 0 p2 = 0 for p in range(n + m): if p2 >= n or (p1 < m and tmp_nums1[p1] <= nums2[p2]): nums1[p] = tmp_nums1[p1] p1 += 1 else: nums1[p] = nums2[p2] p2 += 1 #DSA #Python #CodingChallenge #30dayschallenge #Leetcode
To view or add a comment, sign in
-
📅 Day 96 Summary: K Closest Points to Origin On Day 96, you successfully solved a medium-difficulty problem titled "K Closest Points to Origin" on GeeksforGeeks. 🎯 Problem Statement Goal: Given an array of points [x, y] and an integer K, return the K closest points to the origin (0,0). 🧠 Solution Approach (Max Heap / Priority Queue) The visible Python code indicates you used a Max Heap (specifically, Python's heapq module combined with negative values to simulate a Max Heap) to maintain the K closest points found so far. Calculate Squared Distance: A helper function squaredDis calculates x2 +y2 for each point. Maintain a Max Heap of Size K: The loop iterates through all points in the input. For each point, it pushes the pair (−distance,point) onto the maxHeap. The negative distance is used because Python's heapq is a Min Heap, and negating the value makes it behave like a Max Heap based on magnitude (the largest negative number is the smallest value, so the point with the largest distance among the K is at the top). If the heap size exceeds K, the element at the top (which is the point with the largest distance among the current K points) is removed using heappop. Final Result: After processing all points, the heap contains the K points with the smallest distances. The final step is to pop all elements from the heap and extract the point coordinates.
To view or add a comment, sign in
-
-
🧩 LeetCode Daily : “Contains Duplicate” Today’s problem was simple in statement but great for revisiting a key Python concept i.e sets. Problem: Given an integer array, return True if any value appears at least twice, otherwise return False. 👉 My Approach: I used a set to track unique numbers as I iterated through the list. If a number was already present in the set, it meant a duplicate was found. Otherwise, I added it to the set and continued. Sometimes, the simplest problems teach the most practical lessons — today’s was a great reminder of the power of Python’s built-in data structures 💪 P.S 1️⃣ Continuing my LeetCode journey, one problem at a time, today marks as day six. P.S 2️⃣ I’m thinking to post LeetCode updates every weekend, and on other days, I’ll be sharing posts about my other learnings and projects. 🚀 Here’s my LeetCode profile 👇 https://lnkd.in/daSxpGmi 🔗 Connect if you are also solving LeetCode problems. 🔁If you think this could help another learner, share it forward. #datastructures #algorithms #LeetCode #python #leetcodeproblem217 #containsDuplicates
To view or add a comment, sign in
-
-
🗓️ Python Daily – Day #1 🎯 Topic: Mastering List Comprehensions 🚀 💡 Concept: Simplify your loops with list comprehensions! Instead of writing this: ```python squares = [] for x in range(10): squares.append(x**2) print(squares) ``` You can write it in **one line** as: ```python squares = [x**2 for x in range(10)] print(squares) ``` Try this mini challenge: Write a list comprehension that creates a list of all **even numbers** between 1 and 50 (inclusive). ✅ Hint: Use a conditional `if` inside your list comprehension! Example: `[x for x in range(10) if x % 2 == 0]` --- 🧩 Answer: ```python evens = [x for x in range(1, 51) if x % 2 == 0] print(evens) ``` List comprehensions are not only concise but often faster and more readable. Make them your new best friend! 😉
To view or add a comment, sign in
-
Day 14 #45Days_of_learning #Exception_handling Exception handling is a mechanism that allows your program to respond to runtime errors (exceptions). It handles the errors by exception so that the program flow can continue normally. Python provides #five keywords for exception handling: #try in try block we write the exception code. #except we need to place the code to handle errors(message gives to users). #else to run code only when no error occurs. #finally used for cleanup actions. gives the result of try block. #raise choose to throw an exception if a condition occurs. #example try: x = int(input("Enter a number: ")) result = 10 / x print("Result is:", result) except ZeroDivisionError: print("Error: You cannot divide by zero!") except ValueError: print("Error: Please enter a valid number.") else: print("Great! No errors occurred.") finally: print("Program execution completed.") #output: 0 Enter a number: 0 ERROR! Error: You cannot divide by zero! Program execution completed. #output: 1.2 Enter a number: 1.2 ERROR! Error: Please enter a valid number. Program execution completed. #output:20 Enter a number: 20 Result is: 0.5 Great! No errors occurred. Program execution completed.
To view or add a comment, sign in
-
🗓️ Python Daily – Day #1 🎯 Topic: Mastering List Comprehensions 🚀 💡 Concept/Quiz/Challenge: Transform this simple for-loop into a single line of code using a **list comprehension**: ```python numbers = [1, 2, 3, 4, 5] squares = [] for n in numbers: squares.append(n**2) print(squares) ``` Rewrite it so that `squares` is created in one line. ✅ Hint: Think about enclosing an expression in square brackets and using a `for` clause inside. 🧩 Answer/Explanation: ```python squares = [n**2 for n in numbers] print(squares) ``` List comprehensions are a compact, readable way to generate lists based on existing iterables. They are not only shorter but often faster than traditional loops! Try adapting this to create lists of cubes, or even filtering lists!
To view or add a comment, sign in
-
🔷 Day 28- 30DaysChallenge(Leetcode Problem): 🌟 Problem: Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized. Return the minimized largest sum of the split. A subarray is a contiguous part of the array. 🧠Solution: class Solution: def splitArray(self, nums: list[int], k: int) -> int: low, high = max(nums), sum(nums) def ok(x): cnt, curr = 1, 0 for v in nums: if curr + v <= x: curr += v else: cnt += 1 curr = v if cnt > k: return False return True while low < high: mid = (low + high) // 2 if ok(mid): high = mid else: low = mid + 1 return low #DSA #Python #CodingChallenge #30dayschallenge #Leetcode
To view or add a comment, sign in
-
🗓️ Python Daily – Day #1 🎯 Topic: Mastering List Comprehensions 🔥 💡 Concept: Transforming lists in one elegant line! List comprehensions let you create new lists by applying an expression to each item in an iterable — cleaner and faster than regular loops. \*\*Example:\*\* Create a list of squares for numbers 1 through 5. ```python squares = \[x\*\*2 for x in range\(1, 6\)\] print\(squares\) # Output: \[1, 4, 9, 16, 25\] ``` \*\*Quiz:\*\* Write a list comprehension to create a list of even numbers between 1 and 20 \(inclusive\). ✅ Hint: Use a condition inside the comprehension to filter even numbers. 🧩 Answer: ```python evens = \[x for x in range\(1, 21\) if x % 2 == 0\] print\(evens\) # \[2, 4, 6, 8, 10, 12, 14, 16, 18, 20\] ```
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development