🚀 Day 29 of #100DaysOfCode – LeetCode Problem #643: Maximum Average Subarray I 🧩 Problem: Given an integer array nums and an integer k, find the contiguous subarray of length k that has the maximum average value. 💡 Approach: This problem is a great example of the Sliding Window Technique 🪟 Calculate the sum of the first k elements. Then slide the window by one element at a time — subtract the element that goes out, add the new one coming in. Keep track of the maximum sum seen. Return the maximum average (maxSum / k). 💻 Java Code: class Solution { public double findMaxAverage(int[] nums, int k) { double sum = 0; for (int i = 0; i < k; i++) { sum += nums[i]; } double max = sum; for (int i = k; i < nums.length; i++) { sum += nums[i] - nums[i - k]; max = Math.max(max, sum); } return max / k; } } ⏱️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) This one reinforces how sliding window optimizations can drastically simplify what looks like a brute-force problem!
"100DaysOfCode: LeetCode Problem #643 - Maximum Average Subarray I"
More Relevant Posts
-
Day 27 of #100DaysOfCode – LeetCode Problem #496: Next Greater Element I 🧩 Problem: Given two arrays nums1 and nums2, where nums1 is a subset of nums2, find the next greater element for each element of nums1 in nums2. If no greater element exists, return -1. 💡 Approach: Use a stack to track the next greater element for all numbers in nums2. Store results in a map for O(1) lookup when iterating nums1. This gives an efficient O(n) solution. 💻 Java Code: class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> mpp = new HashMap<>(); Stack<Integer> st = new Stack<>(); for (int num : nums2) { while (!st.isEmpty() && st.peek() < num) { mpp.put(st.pop(), num); } st.push(num); } while (!st.isEmpty()) mpp.put(st.pop(), -1); int[] ans = new int[nums1.length]; for (int i = 0; i < nums1.length; i++) ans[i] = mpp.get(nums1[i]); return ans; } } ⏱️ Complexity: Time: O(nums1.length + nums2.length) Space: O(nums2.length) ✅ Result: Accepted (Runtime: 0 ms) This problem highlights how monotonic stacks can efficiently solve next-greater-element scenarios without nested loops.
To view or add a comment, sign in
-
🚀 Day 32 of #100DaysOfCode – LeetCode Problem #697: Degree of an Array 🧩 Problem: Given a non-empty array of non-negative integers, the degree of the array is the maximum frequency of any element. The goal is to find the smallest possible length of a contiguous subarray that has the same degree as the entire array. 💡 Approach: To solve this efficiently: Track the first and last occurrence of each element. Track their frequency count. Identify elements that contribute to the array’s maximum degree. For each of those elements, compute the subarray length = last[i] - first[i] + 1. Return the minimum of those lengths. 💻 Java Code: class Solution { public int findShortestSubArray(int[] nums) { Map<Integer, Integer> count = new HashMap<>(); Map<Integer, Integer> first = new HashMap<>(); int degree = 0, bestLen = nums.length; for (int i = 0; i < nums.length; i++) { int num = nums[i]; first.putIfAbsent(num, i); count.put(num, count.getOrDefault(num, 0) + 1); degree = Math.max(degree, count.get(num)); } for (int i = 0; i < nums.length; i++) { int num = nums[i]; if (count.get(num) == degree) { int len = i - first.get(num) + 1; bestLen = Math.min(bestLen, len); } } return bestLen; } } ⏱️ Complexity: Time: O(n) Space: O(n) ✅ Result: Accepted (Runtime: 0 ms) This problem beautifully blends hashmaps and frequency analysis to derive insights efficiently — a perfect example of thinking beyond brute force!
To view or add a comment, sign in
-
🚀 Day 34 of #100DaysOfCode – LeetCode Problem #228: Summary Ranges 🧩 Problem: Given a sorted, unique integer array nums, return the smallest list of ranges that covers all numbers in the array exactly. Each range is represented as: "a->b" if the range covers more than one number. "a" if it covers a single number. 📘 Example: Input: nums = [0,1,2,4,5,7] Output: ["0->2", "4->5", "7"] 💡 Approach: We traverse the array while tracking the start of each range. Whenever we detect a break (i.e., the next number isn’t consecutive), we close the range and store it. 🔍 Steps: Initialize start = nums[0]. Traverse the array. If the next element isn’t consecutive, push "start->current" (or "start" if equal). Move to the next starting number and continue. 💻 Java Code: class Solution { public List<String> summaryRanges(int[] nums) { List<String> result = new ArrayList<>(); if (nums.length == 0) return result; int i = 0; while (i < nums.length) { int start = nums[i]; int j = i; while (j + 1 < nums.length && nums[j + 1] == nums[j] + 1) { j++; } if (start == nums[j]) { result.add(String.valueOf(start)); } else { result.add(start + "->" + nums[j]); } i = j + 1; } return result; } } ⏱️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 3 ms) It’s a simple yet elegant problem — a great reminder that clean logic often beats complex tricks
To view or add a comment, sign in
-
🚀 Day 30 of #100DaysOfCode – LeetCode Problem #88: Merge Sorted Array 🧩 Problem: You’re given two sorted arrays, nums1 and nums2, and need to merge them into a single sorted array — in-place inside nums1. The catch? You can’t return a new array, and nums1 already contains extra space for nums2. 💡 Approach: To avoid overwriting elements in nums1, we use a three-pointer approach: Start from the end of both arrays. Compare the elements and place the larger one at the back (nums1[pMerge]). Move pointers accordingly until all elements are merged. 💻 Java Code: class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int p1 = m - 1, p2 = n - 1, pMerge = m + n - 1; while (p2 >= 0) { if (p1 >= 0 && nums1[p1] > nums2[p2]) { nums1[pMerge--] = nums1[p1--]; } else { nums1[pMerge--] = nums2[p2--]; } } } } ⏱️ Complexity: Time: O(m + n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) A simple yet elegant example of solving array problems in-place using smart pointer manipulation!
To view or add a comment, sign in
-
💡 LeetCode 1768 – Merge Strings Alternately 💡 Today, I solved LeetCode Problem #1768, a delightful string manipulation problem that strengthens the fundamentals of character traversal and string building using StringBuilder in Java. 🧩 Problem Overview: You’re given two strings, word1 and word2. Your task is to merge them alternately — take one character from each string in turn, and if one string is longer, append its remaining characters at the end. 👉 Examples: Input → word1 = "abc", word2 = "pqr" → Output → "apbqcr" Input → word1 = "ab", word2 = "pqrs" → Output → "apbqrs" Input → word1 = "abcd", word2 = "pq" → Output → "apbqcd" 💡 Approach: 1️⃣ Use two pointers i and j to iterate through both strings. 2️⃣ Append one character from word1, then one from word2, alternately. 3️⃣ Continue until both strings are fully traversed. 4️⃣ Return the merged string using StringBuilder.toString(). ⚙️ Complexity Analysis: ✅ Time Complexity: O(n + m) — Each character from both strings is processed once. ✅ Space Complexity: O(n + m) — For the resulting merged string. ✨ Key Takeaways: Reinforced understanding of two-pointer traversal and StringBuilder for efficient string concatenation. Showed how simple looping logic can elegantly handle strings of unequal lengths. Practiced writing clean, readable, and efficient code for basic string problems. 🌱 Reflection: Even simple problems like this one are valuable for sharpening algorithmic thinking and code clarity. Mastering these fundamental string operations lays the groundwork for tackling more advanced text-processing challenges later on. 🚀 #LeetCode #1768 #Java #StringManipulation #TwoPointerTechnique #DSA #ProblemSolving #CleanCode #AlgorithmicThinking #DailyCoding #ConsistencyIsKey
To view or add a comment, sign in
-
-
🚀 Day 18 of My DSA Journey — Rotate String | Valid Anagram | Sort Characters by Frequency (LeetCode #796, #242, #451) Today, I tackled three interesting String problems that sharpened my understanding of string manipulation, frequency counting, and sorting logic in Java 💡 🧩 Problem 1: Rotate String (LeetCode #796) 🎯 Goal: Check if one string can be obtained by rotating another. 👉 Example: s = "abcde", goal = "cdeab" → ✅ true 💭 Approach: If lengths differ → return false. If (s + s) contains goal → it’s a rotated version. ✨ Key Takeaway: Clever use of concatenation simplifies rotation logic. 🧩 Problem 2: Valid Anagram (LeetCode #242) 🎯 Goal: Check if two strings are anagrams. 👉 Example: s = "anagram", t = "nagaram" → ✅ true 💭 Approach: Use an integer array of size 26. Increment counts for s, decrement for t. If all counts are 0 → valid anagram! ✨ Key Takeaway: ASCII-based frequency counting is both fast and memory-efficient. 🧩 Problem 3: Sort Characters by Frequency (LeetCode #451) 🎯 Goal: Sort characters in descending order of frequency. 👉 Example: s = "Aabb" → ✅ Output: "bbAa" 💭 Approach: Count frequency of each character. Store in a list of (char, count) pairs. Sort list by count (descending). ✨ Key Takeaway: Learned how sorting and frequency analysis can work together elegantly. 💬 Reflection: These problems taught me the power of simple but strategic operations like string concatenation, ASCII arithmetic, and sorting logic — all crucial for writing clean, optimized code. #DSA #Java #LeetCode #CodingJourney #ProblemSolving #StringManipulation #100DaysOfDSA #RotateString #ValidAnagram #FrequencySort
To view or add a comment, sign in
-
🚀 Day 31 of #100DaysOfCode – LeetCode Problem #704: Binary Search 🧩 Problem: Given a sorted array and a target value, find the index of the target using an algorithm with O(log n) time complexity. If the target doesn’t exist, return -1. 💡 Approach: This is a classic Binary Search problem. We use two pointers (i and j) to represent the current search range. Calculate the middle index mid. If nums[mid] equals the target → return mid. If target > nums[mid] → search the right half. Else → search the left half. Repeat until the range is empty. 💻 Java Code: class Solution { public int search(int[] nums, int target) { int i = 0, j = nums.length - 1; while (i <= j) { int mid_i = i + (j - i) / 2; int mid_val = nums[mid_i]; if (target < mid_val) { j = mid_i - 1; } else if (target > mid_val) { i = mid_i + 1; } else { return mid_i; } } return -1; } } ⏱️ Complexity: Time: O(log n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) Binary Search — simple, efficient, and one of the most fundamental algorithms every developer must master.
To view or add a comment, sign in
-
💡 LeetCode 1528 – Shuffle String 💡 Today, I solved LeetCode Problem #1528: Shuffle String, which tests how well you can handle index mapping and string reconstruction in Java — an elegant exercise in array manipulation and string handling. ✨ 🧩 Problem Overview: You’re given a string s and an integer array indices. Each character at position i in s must be moved to position indices[i] in the new string. Return the final shuffled string. 👉 Example: Input → s = "codeleet", indices = [4,5,6,7,0,2,1,3] Output → "leetcode" 💡 Approach: 1️⃣ Create a char array of the same length as s. 2️⃣ Loop through each character in s, placing it at the position specified by indices[i]. 3️⃣ Convert the filled character array back to a string. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Single pass through the string. ✅ Space Complexity: O(n) — For the result character array. ✨ Key Takeaways: Reinforced understanding of index mapping between arrays and strings. Practiced how to reconstruct a string efficiently without using extra data structures. A great example of how simple iteration can solve structured reordering problems cleanly. 🌱 Reflection: Sometimes, challenges like this remind us that not every problem requires a complex algorithm — precision, clarity, and clean mapping logic often do the job best. Staying consistent with such problems builds both confidence and coding discipline. 🚀 #LeetCode #1528 #Java #StringManipulation #ArrayMapping #DSA #ProblemSolving #CleanCode #CodingJourney #AlgorithmicThinking #ConsistencyIsKey
To view or add a comment, sign in
-
-
💡 Day 31/100 Days Today’s problem was “Valid Palindrome” 🪞 The challenge was to check if a string reads the same forward and backward after removing all non-alphanumeric characters and ignoring case differences. This helped strengthen my understanding of string manipulation and the two-pointer technique in Java. 🧠 Key Features: Cleaned the string using regex to remove unwanted characters. Applied two-pointer logic to compare characters from both ends. Simple, efficient, and elegant — a great example of how logic matters more than length of code. ⚙️ Time Complexity: O(n) → Each character checked once. 💾 Space Complexity: O(n) → For the cleaned string (or O(1) in in-place approach). ✨ Takeaway: This problem reinforced how small optimizations — like using pointers instead of extra data structures — make algorithms more efficient. Every problem is a step closer to cleaner and smarter code! #Day31Of100 #DSA #Java #ProblemSolving #TwoPointer #CodingJourney #100DaysOfCode #LearningEveryday
To view or add a comment, sign in
-
-
✅ Day 35 of #100DaysOfCode Challenge 📘 LeetCode Problem 112: Path Sum 🧩 Problem Statement: Given the root of a binary tree and an integer targetSum, return true if there exists a root-to-leaf path whose sum of node values equals targetSum. Example: Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: Path 5 → 4 → 11 → 2 gives the sum = 22 ✅ 💡 Simple Approach: If the tree is empty → return false If it’s a leaf node → check if its value equals targetSum Otherwise → subtract node value and check left and right recursively 💻 Easiest Java Code: class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null && root.val == sum) return true; sum = sum - root.val; return hasPathSum(root.left, sum) || hasPathSum(root.right, sum); } } ⚙ Complexity: ⏱ Time: O(n) → visit each node once 💾 Space: O(h) → recursion stack (h = height of tree) 🌿 Small code, big concept — recursion makes trees easy 🌱 #Day35 #100DaysOfCode #LeetCode #Java #DSA #BinaryTree #Recursion #CodingChallenge
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