Day - 28 Median of Two Sorted Arrays The problem - Find the Median of two sorted arrays. Example : nums1 = [1,3], nums2 = [2] -> 2.0 nums = [1,2], nums2 = [3,4] -> 2.5 Brute force - Merge both arrays and find the Median. Approach Used - Two Pointers •) Initialize n=nums1.length, m=nums2.length, i=0,j=0. •) Track two variables, m1(current middle element), m2(previous middle element). •) Loop until we reach the median position, count from 0 to (n+m)/2. •) In each iteration, save current m1 as m2.Compare elements at i and j. 1 - If both arrays have elements remaining, pick smaller one and move that pointer. 2 - If only nums1 has elements, take from nums1(i++). 3 - If only nums2 has elements, take from nums2(j++). •) After loop ends, if total length is odd, median = m1, if total length is even, median = (m1+m2)/2. •) Return the median. Complexity - Time - O(m+n), we iterate until median position. Space - O(1), we use pointers. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
Median of Two Sorted Arrays Algorithm
More Relevant Posts
-
Day - 34 Longest Common Prefix The problem - Write a function to find the longest common prefix string amongst an array of strings. Example : strs = [“flower”,”flow”,”flight”] -> “fl” strs=[“dog”,”racecar”,”car”] -> “” Brute force - Compare all the characters at each position across the strings, but the time complexity will be O(S), S is sum of all characters and require multiple traversals. Approach Used - Horizontal Scanning •) Handle edge case: if array is null or empty, return "". •) Initialise pref = strs[0], prefLen = prefix.length(). •) while(prefLen > s.length()) or pref doesn't match the beginning of s (or prefix is longer than s) 1 - Reduce prefix length by 1 (prefLen--). 2 - If prefLen becomes 0, no common prefix exists - return "". 3 - Update prefix to pref.substring(0, prefLen). 4 - Continue to next string. •) Return the final pref. Complexity - Time - O(S), total number of characters in all strings. Space - O(1), only used variables. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 15 – Static Array vs Dynamic Array (and why Arrays still rule in DSA) “Why learn static arrays when we already have ArrayList / dynamic arrays?” 🤔 => And today I realized this clearly while solving: 🧠 Problem: First Negative Number in every Window (size = K) This problem is solved efficiently using: ✅ Static Array ✅ Sliding Window ✅ Queue for tracking negatives Logic : private static List<Integer> findFirstNegativeNumInSubArray(int[] arr, int k) { List<Integer> result = new ArrayList<>(); Queue<Integer> queue = new LinkedList<>(); int left = 0; for (int right = 0; right < arr.length; right++) { // Add negative numbers to queue if (arr[right] < 0) { queue.offer(arr[right]); } // When window size is reached if (right - left + 1 == k) { // Add first negative or 0 result.add(queue.isEmpty() ? 0 : queue.peek()); // Remove element going out of window if (!queue.isEmpty() && arr[left] == queue.peek()) { queue.poll(); } left++; // slide window } } return result; } Dynamic arrays make life easy. Static arrays make you a strong problem solver. Master arrays → master DSA → master backend performance 💪 #Day15 #Java #Arrays #SlidingWindow #DSA #ProblemSolving #JavaDeveloper #CodingJourney #Consistency #Microservices
To view or add a comment, sign in
-
Day 33/100 – LeetCode Challenge ✅ Problem: #1292 Maximum Side Length of a Square with Sum Less than or Equal to Threshold Difficulty: Medium Language: Java Approach: Prefix Sum + Binary Search on Square Size Time Complexity: O(m × n × log(min(m, n))) Space Complexity: O(m × n) Key Insight: Use 2D prefix sum to quickly compute sum of any square submatrix in O(1). For each cell, binary search the maximum square side length starting at that cell with sum ≤ threshold. Solution Brief: Built prefix sum matrix psum for O(1) submatrix sum queries. For each possible starting cell, used binary search to find largest valid square. Tracked global maximum side length across all positions. Optimizing submatrix queries with prefix sum. #LeetCode #Day33 #100DaysOfCode #BinarySearch #Java #Algorithm #CodingChallenge #ProblemSolving #MaxSquareSide #MediumProblem #PrefixSum #Matrix #Optimization #DSA
To view or add a comment, sign in
-
-
🚀 𝗗𝗮𝘆 𝟵 – 𝗖𝗼𝗻𝘁𝗶𝗻𝘂𝗶𝗻𝗴 𝗠𝘆 𝗗𝗮𝘁𝗮 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲𝘀 & 𝗔𝗹𝗴𝗼𝗿𝗶𝘁𝗵𝗺𝘀 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 Today, I worked on Selection Sort, a simple yet important sorting algorithm that helped me understand comparison-based sorting and in-place array manipulation. 📘 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗜 𝗪𝗼𝗿𝗸𝗲𝗱 𝗢𝗻 𝗧𝗼𝗱𝗮𝘆: Selection Sort – Sort the given array by repeatedly selecting the minimum element from the unsorted part and placing it at the correct position. 🚀 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: 𝗦𝗲𝗹𝗲𝗰𝘁𝗶𝗼𝗻 𝗦𝗼𝗿𝘁 (𝗜𝘁𝗲𝗿𝗮𝘁𝗶𝘃𝗲) 𝗜𝗱𝗲𝗮 ➔ Divide the array into sorted and unsorted parts ➔ Find the minimum element from the unsorted portion ➔ Swap it with the first element of the unsorted part ➔ Repeat until the array is sorted 🧠 𝗦𝘁𝗲𝗽-𝗯𝘆-𝗦𝘁𝗲𝗽 ➔ Start from the first index ➔ Assume the current index holds the minimum value ➔ Compare it with the remaining elements ➔ Update the minimum index when a smaller value is found ➔ Swap the minimum element with the current index ➔ Continue for all elements in the array ⏱️ 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: Time Complexity: O(n²) Space Complexity: O(1) (In-place sorting) 🧠 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝘀 ➔ Learned how in-place sorting works ➔ Understood comparison-based sorting logic ➔ Improved confidence with nested loops ➔ Strengthened fundamentals of array manipulation Gurugubelli Vijaya Kumar Manoj Kumar Reddy Parlapalli 10000 Coders #Day9 #DSA #SelectionSort #Java #Arrays #SortingAlgorithms #ProblemSolving #CodingJourney #LearningByDoing #TimeComplexity
To view or add a comment, sign in
-
-
🔥 Day 74/100 of #100DaysOfCode – Sliding Window Maximum: Deque for O(n)! Today solved a classic problem requiring efficient maximum tracking in a moving window: ✅ Problem 239: Sliding Window Maximum Task: Return the maximum in each sliding window of size k in O(n) time. Approach: Monotonic decreasing deque (Double-ended Queue): Store indices (not values) in deque, maintaining decreasing order of values Remove out-of-window indices from front Remove smaller elements from back before adding new index Front of deque always holds current window’s max Key Insight: A deque lets us efficiently maintain candidates for maximum while sliding the window, avoiding repeated O(k) scans. Complexity: O(n) time, O(k) extra space — optimal linear solution. A powerful example of using the right data structure to maintain order while supporting efficient insertions and deletions from both ends! 📊🔍 #100DaysOfCode #LeetCode #Java #Deque #SlidingWindow #MonotonicQueue #Algorithms #CodingInterview
To view or add a comment, sign in
-
-
🚀 Day 21 of #100DaysOfCode 🧩 Problem: Find Median of Two Sorted Arrays (LeetCode #4, Hard) 💡 Concept: Given two sorted arrays, the goal is to find the median of the combined dataset after merging both arrays. 🛠 Approach (Merge + Sort): 1️⃣ Create a new array to store elements from both input arrays. 2️⃣ Copy all elements from nums1 and nums2 into the new array. 3️⃣ Sort the merged array using Bubble Sort to maintain order. 4️⃣ Determine the median: If total length is even, return the average of the two middle elements. If odd, return the middle element directly. 🔥 Performance: ✅ Accepted on LeetCode ⚡ Runtime: 52 ms 💾 Memory: 48.81 MB 📊 Complexity: ⏱ Time: O((m + n)²) — due to bubble sort 💾 Space: O(m + n) — extra array used for merging #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #Consistency #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
-
Day - 50 Intersection of Two Linked Lists The problem - Given the heads of two singly linked lists, return the node at which the two lists intersect. If they don't intersect, return null. Example : listA = [4,1,8,4,5], listB = [5,6,1,8,4,5] → true, intersect at node 8 Brute force - Use HashSet to store nodes from one list, check second list, but the space complexity will be O(n). Approach Used - •) Initialize two pointers: listA = headA, listB = headB. •) While (listA != listB), 1 - If listA != null, move to next, listA = listA.next, else switch to headB. 2 - If listB != null, move to next: listB = listB.next, else switch to headA. •) Return listA. Complexity - Time - O(m + n), both pointers traverse at most m+n nodes. Space - O(1), only used pointers. Note - By switching heads, each pointer travels exactly the same total distance (Length A + Length B). This syncs them up so they hit the intersection at the exact same time! #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
🌱 My Spring Journey : @Value Annotation in Spring This annotation is basically used to inject values into simple-type Spring bean properties. 🔹 There are different ways of injecting simple values into Spring bean properties : -> To inject direct values into Spring bean properties. -> To inject values gathered from a properties file. -> To inject system property values like os.name, os.version, etc. -> To inject environment variable values into Spring bean properties. 🔹 We can provide direct values to the @Value annotation, or we can specify a key using a placeholder @Value("${...}"). Difference between @Autowired and @Value : -> @Autowired is used to inject one Spring bean class object into a property (HAS-A relationship) of another Spring bean class. -> @Value is used to inject simple values into the properties of a Spring bean class. 🔹 Internal working : -> The moment the IOC container is created, it internally creates a built-in object called the Environment object, which dynamically collects : -> Key-value pairs defined in the configured properties file. -> Key-value pairs of fixed system properties. -> Environment variable names and their values. Later, these values are injected into Spring bean properties based on the @Value annotation. #SpringFramework #SpringBoot #Java #BackendDevelopment #DependencyInjection #LearningInPublic #MySpringJourney
To view or add a comment, sign in
-
📅 Day 53 of #100DaysOfLeetCode Problem: 840. Magic Squares In Grid Difficulty: Medium 🔍 Problem Insight A 3×3 magic square must: Contain distinct numbers from 1 to 9 Have the same sum for all rows, columns, and both diagonals The task is to count how many such 3×3 subgrids exist inside a given grid. 💡 Key Observations Magic squares are strictly limited to 3×3 Any number outside 1–9 immediately invalidates the square Duplicate values break the magic condition Grid size is small, allowing safe sliding-window checks ⚙️ Approach Slide a 3×3 window across the grid For each window: Use a HashSet to ensure values are unique and within 1–9 Compute the target sum from the first row Validate: All rows All columns Both diagonals Count all valid magic squares ⏱️ Complexity Time: O(m × n) Space: O(1) #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
To view or add a comment, sign in
-
-
🚀 Day 16 - 100Days of DSA Problem Statement : ✅ Sum of subarrays of size K ✅ Average of subarrays of size K At first, calculating the sum or average of every subarray looked simple… but using nested loops makes it slow and inefficient for large inputs. That’s when I learned about the Sliding Window technique – a powerful optimization used in many real-world and interview problems. 🧠 Approach: Sliding Window Technique 1️⃣ Create a window of size k 2️⃣ Calculate the sum of the first window 3️⃣ Slide the window one step at a time 4️⃣ Subtract the element going out 5️⃣ Add the element coming in Code template to solve similar problems: int maxSum=0,windowSum=0; List<Integer> list = new ArrayList<>(); for(int right=0;right<size;right++) { maxSum = maxSum+arr[right]; } list.add(maxSum); for(int right=size;right<arr.length;right++) { maxSum+=arr[right]; maxSum-=arr[right-size]; list.add(maxSum); } ⏱ Time & Space Complexity Time Complexity: 🟢 O(n) – each element is processed once Space Complexity: 🟢 O(1) – only a few variables used (constant extra space) #Day16 #SlidingWindow #DSA #Java #ProblemSolving #CodingJourney #JavaDeveloper #BackendDevelopment #Algorithms #Consistency
To view or add a comment, sign in
Explore related topics
- Approaches to Array Problem Solving for Coding Interviews
- Problem Solving Techniques for Developers
- Common Algorithms for Coding Interviews
- How to Use Arrays in Software Development
- Solving Sorted Array Coding Challenges
- LeetCode Array Problem Solving Techniques
- Tips for Finding Simple Solutions to Complex Problems
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