🔷 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
Merging Two Sorted Arrays in Python for Leetcode Challenge
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 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
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
-
🚀 Day 4/100 — Cracked LeetCode 1611: Minimum One Bit Operations to Make Integers Zero 🔥 Today’s challenge was a deep dive into bit manipulation and recursion. LeetCode 1611 looked deceptively simple—but beneath the surface, it’s a clever twist on Gray code transformations. 🔍 Problem Summary Transform an integer n into 0 using two constrained bit-flipping operations. The trick? You can only flip the rightmost bit, or flip the i-th bit if the (i-1)th is 1 and all lower bits are 0. 🧠 Key Insight This problem maps beautifully to recursive Gray code logic. For any number n, we recursively reduce it by flipping the highest set bit and subtracting the operations needed for the remainder. 📈 What I Learned Bitwise recursion can be elegant and powerful. Understanding binary patterns unlocks optimization. Python’s bit_length() is a hidden gem for bit-level logic. 🔧 Next Steps I’ll be documenting more of these insights as part of my 100-day challenge. If you’re into algorithmic puzzles or want to collaborate on clean, modular solutions—let’s connect! #100DaysOfCode #LeetCode #Python #BitManipulation #GrayCode #CodingChallenge #TechJourney #ScarBuilds
To view or add a comment, sign in
-
-
#96day of #100DaysOfCode 🌱 LeetCode 109: Convert Sorted List to Binary Search Tree Today’s challenge was about building balance — literally! Given a sorted linked list, we need to convert it into a height-balanced BST 🌳 🧠 Key Idea: The middle element of the list becomes the root. Left half forms the left subtree, right half forms the right subtree. Use slow–fast pointers to find the middle efficiently. 📈 Complexity: Time: O(n log n) Space: O(log n) (recursion stack) 💬 Learning: Balance matters — in trees, in code, and in life 🌿 Sometimes, the middle point creates the strongest foundation. #LeetCode #DSA #BinarySearchTree #LinkedList #CodingChallenge #Python #Algorithm #LeetCodeDaily #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 104 Problem: Flatten Binary Tree to Linked List 🌳➡️📄 This problem is a beautiful blend of tree traversal and pointer manipulation. The goal is to transform a binary tree into a linked list following preorder traversal, while modifying the tree in-place. 🧠 Problem Summary: You're given the root of a binary tree. Your task → Flatten the tree into a linked list such that: Each node’s right pointer acts as the “next” pointer. Each node’s left pointer is always None. The resulting order must follow preorder traversal: Root → Left → Right ⚙️ My Approach: I used a recursive DFS approach that processes nodes in a way that supports pointer restructuring: 1️⃣ Flatten left subtree 2️⃣ Flatten right subtree 3️⃣ If the current node has a left subtree: Temporarily store root.right Move root.left to root.right Nullify the left pointer Traverse to the end of this new right chain Attach the original right subtree there This ensures the node order becomes preorder while maintaining pointer correctness. 📌 Key Observations: Although preorder is Root → Left → Right, the flattening requires processing children first. Doing operations in-place ensures optimal space usage. Traversing to the end of the newly attached right subtree ensures that both left and right parts remain connected in correct order. 📈 Complexity: Time: O(n) — Each node is visited once Space: O(h) — Recursion stack (height of the tree) ✨ Key Takeaway: Flattening a binary tree becomes simple once you understand pointer realignment. First flatten both subtrees → then stitch them together → and the final structure becomes a clean preorder linked list. 🌳➡️🪜 🔖 #DSA #100DaysOfCode #Day104 #BinaryTrees #PreorderTraversal #TreeFlattening #Recursion #LeetCode #ProblemSolving #Python #CodingJourney #TechCommunity #LearningEveryday
To view or add a comment, sign in
-
-
Day 31 / 100 – Add Strings (LeetCode #415) Today’s challenge was all about simulating manual addition without using any built-in integer conversions. Given two numbers as strings, the task was to return their sum — also as a string. This problem really emphasized the importance of breaking problems into small, logical steps rather than relying on shortcuts. 🔍 Key Learnings Recreated the digit-by-digit addition process using ASCII values. Practiced handling carry-over efficiently while iterating backward. Strengthened my understanding of string manipulation and arithmetic logic. 💭 Thought of the Day True problem-solving isn’t about using built-ins — it’s about understanding how things work underneath. Today reminded me that mastery grows when we rebuild the basics from scratch, not when we avoid them. 🔗 Problem Link: https://lnkd.in/gHMt9vj9 #100DaysOfCode #Day31 #LeetCode #Python #ProblemSolving #StringManipulation #Algorithms #DataStructures #CodingChallenge #CodeEveryday #TechGrowth #LearningJourney
To view or add a comment, sign in
-
-
🧠 Day 38 / 100 – Recursion: Factorial of a Number (LeetCode-#509) Today’s challenge was all about recursion — one of the most elegant concepts in programming. I revisited the Factorial problem, which beautifully demonstrates how a big problem can be broken into smaller subproblems. The idea is simple: 👉 The factorial of n is n * factorial(n-1) until n becomes 1. But the real challenge lies in understanding the flow of recursive calls and how the call stack unwinds to give the final result. This problem reminded me that recursion isn’t just about repeating a function — it’s about trusting the process and thinking in terms of smaller steps to solve complex problems. 🔍 Key Learnings Every recursive function must have a base case to prevent infinite loops. The call stack stores each recursive call until it’s resolved. Recursion is a natural fit for problems that can be divided into smaller, similar subproblems. 💭 Thought of the Day Recursion teaches patience and structure. Sometimes, you need to trust that solving the smaller version of a problem will help you conquer the big one — both in code and in life 💫. 🔗 Reference Problem:https://lnkd.in/g3yNGDbJ #100DaysOfCode #Day38 #LeetCode #Python #Recursion #Factorial #ProblemSolving #CodingChallenge #Algorithms #ProgrammingMindset #DataStructures #CleanCode #LearnByDoing #TechGrowth #PythonProgramming
To view or add a comment, sign in
-
-
🚀 Day 36 of #100DaysOfDSA Solved LeetCode Problem #39 – Combination Sum 🔢✨ 📌 Problem Insight: Given a set of distinct integers and a target number, the task is to find all unique combinations of numbers that add up to the target. Each number can be used multiple times. A great problem to strengthen backtracking and recursion concepts. 💡 Key Learnings: Practiced backtracking to explore all valid combinations. Understood how to reuse elements by controlling the recursive index. Learned efficient pruning — stop recursion when sum exceeds the target. Time complexity: O(2ⁿ) (since all paths are explored). Space complexity: O(target) (recursion stack). 📌 Approach (short): Use recursion to explore every combination. If sum equals target → store it. If sum exceeds target → backtrack. Continue exploring remaining candidates. 👉 Backtracking problems teach patience and logic — finding all valid paths one step at a time 🚀 #LeetCode #DSA #ProblemSolving #100DaysChallenge #Day36 #CodingJourney #Python #Backtracking
To view or add a comment, sign in
-
-
🚀 Day 33 of #100DaysOfCode — LeetCode + HackerRank Edition! Today’s challenge was a classic twist on binary search — searching in a rotated sorted array. 🔗 Problem: search(self, nums: List[int], target: int) (LeetCode) 📌 Challenge: Given a rotated sorted array, find the index of a target value in O(log n) time. 🔍 Approach: → Used binary search with a twist: at each step, determined which half of the array is sorted → If the left half is sorted, checked if the target lies within it → If not, searched the right half — and vice versa → Carefully updated low, high, and recalculated mid inside the loop → Avoided brute-force by leveraging the sorted structure of one half at every step 💡 What made it click: → Realized that one half is always sorted, even after rotation → Visualized the array and dry-ran examples like [4,5,6,7,0,1,2] to understand the logic → Fixed a key bug: I was calculating mid only once — moving it inside the loop made everything work! → Debugging this helped me appreciate how small details (like mid placement) can make or break binary search 📚 What I learned: ✅ Binary search can be adapted to rotated arrays with clever logic ✅ Always recalculate mid after updating low and high ✅ Dry runs are powerful for catching logic bugs Have you tackled rotated binary search before? Did you use recursion, iteration, or something else? Let’s swap strategies 💬 #Day33 #LeetCode #BinarySearch #RotatedArray #ProblemSolving #Python #DebuggingJourney #CleanCode #LearnToCode #CodeNewbie #SoftwareEngineering #TechJourney #100DaysOfCode
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