Day 11/30 – LeetCode streak Today’s problem: Sort Integers by The Number of 1 Bits You have to sort an array by popcount first (fewer 1s come earlier), and if two numbers have the same count, sort them by their actual value. Instead of using 'Arrays.sort' with a comparator, I tried writing the sort logic myself with insertion sort: - For each element, treat it as 'key' and move larger elements (based on custom “bit count, then value” order) one step to the right. - 'Swap(a, b)' returns true if 'a' should come after 'b' in the final order, using a manual 'countBits' function to compare the number of 1s. - If bit counts differ, the one with more 1s is considered “greater”; if they’re equal, compare the raw integers. Day 11 takeaway: This was a nice chance to practice writing a custom sort order from scratch—once the comparison rule is clear (“by 1-bits, then by value”), the rest is just plugging that into any sorting algorithm. #leetcode #dsa #java #bitmanipulation #sorting
Sorting Integers by 1 Bits and Value
More Relevant Posts
-
Day 12/30 – LeetCode streak Today’s problem: Number of Steps to Reduce a Number in Binary Representation to One Rules are simple: if the number is even, divide by 2; if it’s odd, add 1. But doing this by simulating the whole number each time is slow and messy. The trick is to walk the binary string from right to left and just count how many operations each bit contributes, while carrying a 1 when we “add 1”: - Ignore index 0 (most significant bit); we stop at 'i > 0'. - For each bit, compute 'bit = (s.charAt(i) - '0') + carry'. - If 'bit' is '1', it’s effectively odd → we need '+1' then '/2' → 'steps += 2' and set 'carry = 1'. - If 'bit' is '0' or '2', it’s even → just '/2' → 'steps += 1', 'carry' stays as is. - After the loop, if there’s still a carry, add one more step because we effectively turned something like '"111"' into '"1000"' and need one last divide to reach '1'. Day 12 takeaway: Instead of repeatedly mutating the number, counting how many times each bit causes “+1 then /2” vs “just /2” gives an O(n), no-conversion solution that feels much cleaner once the carry idea clicks. #leetcode #dsa #java #bitmanipulation #consistency
To view or add a comment, sign in
-
-
Day 41 - Find Pivot Index Solved using a prefix sum approach. First computed the total sum of the array, then traversed once while maintaining a running left sum. For each index, the right sum is calculated using total - left - nums[i]. If both sums match, that index is the pivot. Time Complexity: O(n) #Day41 #LeetCode #Java #PrefixSum #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 18/100 – Find the Difference of Two Arrays. Today I solved the problem Find the Difference of Two Arrays. 🔹 Problem: Given two integer arrays nums1 and nums2, return a list of two lists: Elements present in nums1 but not in nums2 Elements present in nums2 but not in nums1 Example: Input: nums1 = [1,2,3] nums2 = [2,4,6] Output: [[1,3], [4,6]]. 🧠 Approach: 1️⃣ First convert both arrays into HashSet to remove duplicates and allow fast lookup. 2️⃣ Traverse set1 If an element is not present in set2, add it to result list a. 3️⃣ Traverse set2 If an element is not present in set1, add it to result list b. 4️⃣ Return both lists as result. HashSet helps because checking presence takes O(1) time. ⏱ Time Complexity Creating sets → O(n + m) Checking elements → O(n + m) ✅ Overall Time Complexity: O(n + m) ✅ Space Complexity: O(n + m). ✨ What I Learned: How to use HashSet to remove duplicate elements from arrays. How HashSet provides O(1) lookup time, making comparisons faster. How to find unique elements between two arrays efficiently. Improved understanding of Set operations and array traversal in Java. #Day18 #100DaysOfCode #LeetCode #Java #DSA #Consistency
To view or add a comment, sign in
-
-
Day 14/30 – LeetCode streak Today’s problem: Concatenation of Consecutive Binary Numbers You need the decimal value of '1' + '2' + '3' + ... + 'n' written in binary back-to-back, all under mod (10^9 + 7). Core trick: treat “concatenate in binary” as shift + OR: * When you append 'i' to the right, you’re really shifting the current result left by 'bits(i)' and OR-ing 'i' into the free space. * The number of bits only increases when 'i' hits a power of two (1, 2, 4, 8, …), so you just track 'bits' and bump it whenever '(i & (i - 1)) == 0'. Day 14 takeaway: Once you see that “stick this binary to the right” is the same as “shift by its bit length and OR”, the whole problem becomes a clean for-loop plus the power-of-two trick—no string building or big integer juggling needed. #leetcode #dsa #java #bitmanipulation #consistency
To view or add a comment, sign in
-
-
LeetCode 83 — Remove Duplicates from Sorted List This problem gives the head of a sorted linked list and asks to remove all duplicate values so that each element appears only once. Since the list is already sorted, duplicate values always appear next to each other. The task is simply to skip repeated nodes while keeping the original order of the list. Example : Input : 1 → 1 → 2 → 3 → 3 Output : 1 → 2 → 3 Approach used — Single Pass Pointer Traversal Because the list is sorted, the solution can be done in one traversal. Two pointers are used during traversal : - One pointer (a) keeps track of the last unique node. - Another pointer (b) scans the list forward. When both nodes have the same value, the duplicate node is skipped. When a new value appears, the unique node is connected to it. At the end, the last node’s next pointer is set to null to ensure the list ends correctly. This approach works in O(n) time and O(1) extra space. #leetcode #datastructures #linkedlist #java #problemSolving
To view or add a comment, sign in
-
-
Day 8 Today I solved “Check if Binary String Has at Most One Segment of Ones” on LeetCode. At first glance, the problem looks simple: Given a binary string, check whether it contains only one continuous segment of '1's. Example: "110" → Valid (one segment of 1s) "1001" → Invalid (two separate segments of 1s) While solving it, I realized an interesting observation: 👉 If a binary string has more than one segment of 1s, the pattern "01" must appear before another "1". So instead of counting segments explicitly, we can simply check whether '01' appears and is followed by another '1'. This turns the problem into a very efficient linear scan with O(n) time complexity. 💡 Key takeaway: Sometimes the simplest solution comes from recognizing patterns in the string rather than simulating the whole process. Also happy to see my solution running at 0 ms runtime (100% faster) 🚀 #LeetCode #DSA #ProblemSolving #Java #CodingJourney #BinaryStrings
To view or add a comment, sign in
-
-
Day 23/30 – LeetCode streak Problem: Find All Possible Stable Binary Arrays I A binary array of length 'zero + one' is stable if it uses exactly 'zero' zeros and 'one' ones, and no run of identical bits is longer than 'limit'. Core idea DP state: * 'dp[z][o][0]' = ways to build a stable array with 'z' zeros and 'o' ones, ending in '0'. * 'dp[z][o][1]' = ways to build a stable array with 'z' zeros and 'o' ones, ending in '1'. * To end in '0' at '(z, o)', you must come from some '(z − k, o, 1)' and append a run of 'k' zeros, where '1 ≤ k ≤ limit' and 'k ≤ z'. * Similarly, to end in '1' at '(z, o)', come from '(z, o − k, 0)' and append 'k' ones. * These transitions are range sums over previous states. Instead of recomputing the full sum each time, use a sliding window idea so each state is computed in 'O(1)'. Transitions (sliding window view) For 'z ≥ 1' and 'o ≥ 1': * Ending with '0': sum of states where we append up to 'limit' zeros after a sequence ending in '1'. * Ending with '1': sum of states where we append up to 'limit' ones after a sequence ending in '0'. Day 23 takeaway: This problem is a solid example of combining DP on counts of zeros and ones with run-length constraints, and optimizing naive range-sum transitions using a sliding window — a pattern that appears in many sequence-counting DP problems. #leetcode #dsa #java #dynamicprogramming #consistency
To view or add a comment, sign in
-
-
Day 20 of Daily DSA 🚀 Solved LeetCode 179: Largest Number ✅ Approach: Converted all integers to strings and used a custom comparator while sorting. For two numbers a and b, we compare: a + b vs b + a This ensures the order that forms the largest possible number. Edge Case Handled 💡 If the highest element after sorting is "0", then the entire array contains zeros → return "0" instead of "000". ⏱ Complexity: • Time: O(n log n) — sorting with custom comparator • Space: O(n) — string array 📊 LeetCode Stats: • Runtime: 6 ms (Beats 96.21%) ⚡ • Memory: 44.96 MB (Beats 76.86%) Comparator-based problems really sharpen logical thinking 🔥 #DSA #LeetCode #Java #ProblemSolving #DailyCoding #Sorting #Consistency
To view or add a comment, sign in
-
-
Day 20/30 – LeetCode streak Problem: Check if Binary String Has at Most One Segment of Ones A valid string can have ones only in a single continuous block, and the input has no leading zeros, so it always starts with '1'. Core idea Since 's' starts with '1', any second segment of ones must look like: '1...1 0...0 1...1' → which necessarily contains "01" at the point where ones restart. So if "01" appears anywhere, there are at least two segments of ones → return false. If "01" never appears, all ones are in a single prefix (possibly followed by zeros), so return true. This reduces to a single substring check in 'O(n)' time and 'O(1)' space. Day 20 takeaway: Instead of explicitly counting segments, spotting the forbidden pattern "01" turns the whole logic into a one-line string check that’s still fully correct and optimal. #leetcode #dsa #java #strings #consistency
To view or add a comment, sign in
-
-
LeetCode 24 — Swap Nodes in Pairs This problem gives the head of a linked list. The task is to swap every two adjacent nodes and return the head of the modified list. One important constraint is that the node values cannot be modified — only the nodes themselves can be rearranged. Example : Input : 1 → 2 → 3 → 4 Output : 2 → 1 → 4 → 3 Each pair of adjacent nodes is swapped while keeping the rest of the list structure intact. Approach used — Pairwise Pointer Manipulation A dummy node is placed before the head to simplify pointer operations, especially for the first pair. During traversal : - first represents the first node of the pair - second represents the second node of the pair For every pair : - The first node is connected to the node after the pair. - The second node is linked before the first node. - The previous node is connected to the new head of the pair. After swapping, the pointer moves forward to process the next pair. This process continues until fewer than two nodes remain. This approach swaps nodes in O(n) time with O(1) extra space. #leetcode #datastructures #linkedlist #java #problemSolving
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