👉 LeetCode 367: Valid Perfect Square. Binary search problem - this time to check if a number is a perfect square without using any built-in square root function. 👇 Here’s my implementation: class Solution { public boolean isPerfectSquare(int num) { if(num == 1){ return true; } int left = 1, right = num/2; while(left<=right){ int mid = left + (right-left)/2; if(mid == num/mid && num%mid == 0){ return true; }else if(mid < num/mid){ left = mid + 1; }else{ right = mid - 1; } } return false; } } 👉 Step-by-step logic: 1. Handle the edge case when num is 1. 2. Use binary search between 1 and num/2. 3. Calculate mid, then check if mid * mid == num. .To avoid overflow, the code uses num/mid instead of mid * mid. 4. If it matches perfectly and num % mid == 0, return true. 5. Adjust search boundaries accordingly until you find it or exhaust all options. 👉 Time Complexity:O(log n) — binary search halves the range each time. 👉 Space Complexity:O(1) — only a few integer variables are used. #LeetCode #Java #ProblemSolving #BinarySearch #Coding
How to check if a number is a perfect square using binary search in Java.
More Relevant Posts
-
#100DaysOfCode – Day 66 String Manipulation & Primitive Decomposition 🧩 Task: Given a valid parentheses string, decompose it into its primitive components and then remove the outermost parentheses from each component. Example: Input: s = "(()())(())" Primitive Decomposition: "(()())" + "(())" After removing outermost parentheses: "()()" + "()" Output: "()()()" My Approach: I iterated through the string while keeping a counter to track the balance of open parentheses. When an opening parenthesis ( was found, I incremented the counter. If the count was greater than 1, it meant this parenthesis was not an outermost one, so I appended it to the result. When a closing parenthesis ) was found, I only appended it if the counter was greater than 1 before decrementing. This ensures the final closing parenthesis of a primitive part is excluded. This simple counter-based approach effectively identifies and removes the correct parentheses without needing a more complex data structure like a stack. Time Complexity: O(N) Space Complexity: O(N) Sometimes, a simple counter is all you need to elegantly handle nested structures. It can be a clean and efficient alternative to more complex data structures for certain problems. #takeUforward #100DaysOfCode #Java #ProblemSolving #LeetCode #DataStructures #Algorithms #StringManipulation #CodeNewbie
To view or add a comment, sign in
-
-
✅Day 42 : Leetcode 154 - Find Minimum in Rotated Sorted Array-2 #60DayOfLeetcodeChallenge 🧩 Problem Statement You are given an array nums that is sorted in ascending order and then rotated between 1 and n times. The array may contain duplicates. Your task is to find and return the minimum element in the rotated sorted array. You must minimize the number of overall operations as much as possible. 💡 My Approach I used a modified binary search technique to handle both rotation and duplicates. Initialize two pointers — low = 0 and high = n - 1. Calculate the middle index mid = low + (high - low) / 2. Update the answer as ans = min(ans, nums[mid]). If nums[low] == nums[mid] && nums[mid] == nums[high], move both low++ and high-- to skip duplicates. If the left half is sorted (nums[low] <= nums[mid]), update the answer and move to the right half (low = mid + 1). Otherwise, move to the left half (high = mid - 1). Continue until low > high. This efficiently finds the minimum even when duplicates exist. ⏱️ Time Complexity Worst Case: O(n) — when many duplicates exist. Average Case: O(log n) — behaves like binary search when duplicates are few. #BinarySearch #LeetCode #RotatedArray #Java #DSA #ProblemSolving #CodingPractice #LeetCodeHard
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
-
💡 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 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 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!
To view or add a comment, sign in
-
Problem 27 : LeetCode 🎯 LeetCode Problem #645 Solved — Set Mismatch (Cyclic Sort Approach) 🧩 Today, I solved another interesting LeetCode Easy problem — “Set Mismatch”, which deepened my understanding of in-place sorting and index mapping using the Cyclic Sort technique. 🔍 Problem Overview Given an integer array nums where numbers are supposed to be from 1 to n, one number is duplicated, and one number is missing. The task: Find both numbers using O(n) time and O(1) space. 💡 My Approach — Cyclic Sort Technique I treated the array like a self-mapping structure where each number x should ideally be placed at index x - 1. If the current element isn’t in its correct place and its target isn’t already filled, I swap it. After the array is sorted in place, any index i where arr[i] != i + 1 indicates: arr[i] → the duplicate number i + 1 → the missing number ⚙️ Results ✅ Runtime: 3 ms — Beats 79.76% of Java submissions ✅ Memory: 47.45 MB — Beats 6.28% of submissions ✅ Complexity: O(n) time | O(1) space ✅ Status: Accepted ✅ (All 49 test cases passed) 🧩 Tech Stack Java | Cyclic Sort | Array Manipulation | In-Place Algorithm | DSA Another problem that reinforces my confidence in index-based logic and memory-efficient coding patterns — vital skills for backend and system optimization. #LeetCode #Java #ProblemSolving #CyclicSort #DataStructures #Algorithms #InPlaceAlgorithm #BackendDevelopment #SpringBoot #DSA #LearningInPublic #CodingJourney Question Url : https://lnkd.in/dixwjFE3
To view or add a comment, sign in
-
-
✅Day 40 : Leetcode 81 - Search in Rotated Sorted Array - 2 #60DayOfLeetcodeChallenge 🧩 Problem Statement You are given an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index k such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]. Given the array nums after rotation and an integer target, return true if target is present in nums, otherwise return false. You must reduce the number of overall operations as much as possible. 💡 My Approach Use a modified binary search since the array is rotated. Initialize low = 0 and high = n - 1. While low <= high: Compute mid = low + (high - low) / 2. If nums[mid] == target, return true. If nums[low] == nums[mid] && nums[mid] == nums[high], increment low and decrement high to skip duplicates. If the left half is sorted (nums[low] <= nums[mid]): Check if target lies in this range; if yes, move high = mid - 1, else move low = mid + 1. Else, the right half is sorted: If target lies in this range, move low = mid + 1, else move high = mid - 1. If no match is found, return false. ⏱️ Time Complexity Average Case: O(log n) Worst Case (due to duplicates): O(n) #BinarySearch #LeetCode #Array #Rotation #Java #CodingPractice #DataStructures
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
-
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