Day 24 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Convert Binary to Decimal We were given a binary number. Task was to convert it into decimal. Binary uses base 2. Decimal uses base 10. So the idea is simple. Each binary digit represents a power of 2. Example: Binary 1011 1×2³ + 0×2² + 1×2¹ + 1×2⁰ = 8 + 0 + 2 + 1 = 11 💻 Brute Force Approach 🔹️Take the binary number as a string. 🔹️Start from the rightmost digit. 🔹️Maintain a base variable (starting from 1). 🔹️If the digit is '1', add base to result. 🔹️Multiply base by 2 after each step. 🔹️Continue till all digits are processed. Time Complexity: O(n) Space Complexity: O(1) 💻 Optimal Approach (Using Built-in Functions) Instead of manual conversion, we can use built-in functions. 🔹️Convert binary string directly to integer. 🔹️Specify base 2 during conversion. 🔹️Language handles the calculation internally. Time Complexity: O(n) Space Complexity: O(1) 📚 What I learned today: ▫️Binary numbers are just powers of 2. ▫️Right-to-left traversal helps in base calculations. ▫️Built-in functions can simplify many tasks. ▫️Understanding manual logic still matters for interviews. Day 24 completed. Bit manipulation basics getting clearer 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
Binary to Decimal Conversion Challenge
More Relevant Posts
-
🚀 Day 68 of LeetCode Problem Solving Journey — 100 Days LeetCode Challenge Today, I solved LeetCode #50 — Pow(x, n) using C++, under the guidance of Trainer NEKAL SINGH SALARIA Singh at REGex Software Services. 🔍 Problem Summary: Implement pow(x, n), which calculates x raised to the power n (xⁿ). 🧠 Approach Used (Binary Exponentiation): I used the Binary Exponentiation (Fast Power) method to efficiently compute the result: If n is even → xn=(xn/2)2x^n = (x^{n/2})^2xn=(xn/2)2 If n is odd → xn=x×(xn−1)x^n = x \times (x^{n-1})xn=x×(xn−1) Repeatedly divide n by 2 to reduce the number of multiplications This method significantly reduces the number of operations compared to normal multiplication. 📚 Key Learnings of the Day ✔ Binary Exponentiation optimizes power calculations ✔ Dividing the exponent reduces time complexity ✔ Handling negative powers requires converting the result to reciprocal ✔ Mathematical insights can greatly improve algorithm performance ⏱ Complexity • Time Complexity: O(log n) • Space Complexity: O(1) (iterative approach) 💡 Optimization Insight: Using simple multiplication would take O(n) time, but Binary Exponentiation reduces it to O(log n), making it far more efficient for large powers. The consistency continues — see you on Day 69 🚀 #Day68 #100DaysLeetCodeChallenge #LeetCode #RegexSoftwareServices #NekalSingh #ProblemSolving #DSA #CPlusPlus #CodingChallenge #ProgrammingJourney #Math #KeepGrowing
To view or add a comment, sign in
-
-
🚀 Day 82 of LeetCode Problem Solving Journey — 100 Days LeetCode Challenge Today, I solved LeetCode #35 — Search Insert Position using C++, under the guidance of Trainer NEKAL SINGH SALARIA Singh at REGex Software Services. 🔍 Problem Summary: Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it should be inserted to maintain sorted order. 🧠 Approach Used (Binary Search): I used the binary search algorithm to achieve optimal performance: Initialize low = 0 and high = n - 1 Calculate mid = (low + high) / 2 If nums[mid] == target → return mid If nums[mid] < target → search in right half Else → search in left half If target is not found → return low as the insertion index This approach efficiently narrows down the search space. 📚 Key Learnings of the Day ✔ Binary search reduces time complexity significantly ✔ Works only on sorted arrays ✔ Returning low gives correct insert position ✔ Divide-and-conquer improves performance ⏱ Complexity • Time Complexity: O(log n) • Space Complexity: O(1) 💡 Optimization Insight: Binary search is already the optimal approach for this problem since it meets the required O(log n) time complexity. Consistency is the real power — see you on Day 83 🚀 #Day82 #100DaysLeetCodeChallenge #LeetCode #RegexSoftwareServices #NekalSingh #ProblemSolving #DSA #CPlusPlus #CodingChallenge #ProgrammingJourney #BinarySearch #KeepGrowing
To view or add a comment, sign in
-
-
🚀 Day 15 of My DSA Journey | Top K Frequent Elements 🔥 Today, I solved one of the most important and frequently asked problems on LeetCode — Top K Frequent Elements. 💡 Problem Understanding Given an integer array, we need to return the k most frequent elements. Sounds simple, but the challenge is to do it efficiently ⚡ 🧠 Brute Force Approach Count frequency using loops Sort elements based on frequency Pick top k ⛔ Time Complexity: O(n² log n) (inefficient for large inputs) ⚡ Optimized Approach (HashMap + Sorting) Here’s what I did: ✅ Step 1: Use a HashMap to store frequency of each element ✅ Step 2: Convert map into array of (frequency, element) pairs ✅ Step 3: Sort array in descending order of frequency ✅ Step 4: Pick first k elements 📌 Example Walkthrough Input: nums = [1,1,1,2,2,3], k = 2 Frequency Map: 1 → 3 times 2 → 2 times 3 → 1 time Sorted: (3,1), (2,2), (1,3) Output: [1,2] ⏱ Complexity Analysis Time: O(n log n) (due to sorting) Space: O(n) 🔥 Key Learning HashMap is super powerful for frequency problems Converting data into sortable structure simplifies logic Always think: Can I reduce nested loops? 🙏 Thanks to my mentor and consistency mindset — improving every single day 💪Day by day, problem by problem — becoming better than yesterday 🚀 #Day15 #DSAJourney #LeetCode #Java #Coding #ProblemSolving #HashMap #Sorting #TopKFrequent #Consistency #LearningInPublic
To view or add a comment, sign in
-
-
Day 81 - LeetCode Journey 🚀 Solved LeetCode 2: Add Two Numbers (Medium) — a classic linked list problem that beautifully combines arithmetic with pointer manipulation. At first, it looks like simple addition. But the twist is that numbers are stored in reverse order as linked lists, and we must simulate digit-by-digit addition. 💡 Core Idea (Simulation + Carry Handling): Traverse both linked lists simultaneously Add corresponding digits along with carry Create a new node for each digit of the result Move forward until both lists and carry are exhausted A dummy node helps in building the result list smoothly. 🤯 Why it works? Because we mimic the exact process of manual addition, handling carry at each step, ensuring correctness even when lengths differ. ⚡ Key Learning Points: • Converting real-world logic into code (digit addition) • Handling carry efficiently • Traversing two linked lists together • Using dummy node for clean construction • Managing different list lengths gracefully • Achieving O(max(n, m)) time and O(1) extra space This problem strengthens both logical thinking and linked list handling. Also, this pattern connects with: Add Binary Multiply Strings Linked List arithmetic problems Big integer calculations ✅ Better understanding of simulation problems ✅ Stronger pointer + arithmetic combination ✅ Improved handling of edge cases (carry, unequal lengths) From simple addition to linked list manipulation — this is where logic meets implementation 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
Day 38 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Print Bracket Number We were given a string str. It contains brackets. Task was to assign a number to each bracket. Each pair gets the same number. Based on order of opening. Let’s understand it simply. ◾️Imagine you are assigning IDs to tasks. ◾️Every time a new task starts, you give it a new ID. ◾️When that task ends, it keeps the same ID. ◾️Multiple tasks can be nested. ◾️But each one has its own number. That’s exactly how brackets behave. 💻 Approach (Using Stack) 🔹️Create an empty stack. 🔹️Initialize a counter = 0. 🔹️Traverse the string. 🔹️If opening bracket: ▪️Increase counter ▪️Push it into stack ▪️Print the counter 🔹️If closing bracket: ▪️Take top value from stack ▪️Print it ▪️Pop from stack Each pair gets same number. 📊 Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) 📚 What I learned today: ▫️Stack helps in tracking nested structures. ▫️Assigning IDs during traversal simplifies pairing logic. ▫️LIFO nature perfectly matches bracket problems. ▫️Nested patterns are easier with stack-based thinking. Day 38 completed. Stack understanding getting stronger 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
To view or add a comment, sign in
-
Why 3Sum Is Really a 2Sum Problem in Disguise 🔍⚡ Solved LeetCode 15 (3Sum) today. Problem 🔍 Find all unique triplets that sum to 0. Initial thought 🧠 Try all triplets → O(n³). Clearly not scalable. Better approach 🚀 Sort the array, then: • Fix one element • Use two pointers on the remaining array • Skip duplicates to avoid repeated triplets Mental model 🧩 Fix one number → reduce problem to 2Sum (target = -nums[i]). Sorting helps with: • Two-pointer movement • Easy duplicate handling Interview takeaway 🎯 When dealing with triplets or combinations, try: Fix one + reduce to a smaller known problem. Practical insight 💡 Duplicate handling is critical. Always skip repeated values while iterating and moving pointers. Time: O(n²) Space: O(1) (excluding output) #DSA #LeetCode #Algorithms #TwoPointers #Sorting #CodingInterview #InterviewPrep #ArrayProblems
To view or add a comment, sign in
-
Day 92/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 347 – Top K Frequent Elements(Medium) 🧠 Approach: Count the frequency of each element using a hashmap, then sort the elements based on frequency in descending order and pick the top k. 💻 Solution: class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: freq = {} for num in nums: freq[num] = freq.get(num, 0) + 1 sorted_items = sorted(freq.items(), key=lambda x: x[1], reverse=True) return [item[0] for item in sorted_items[:k]] ⏱ Time | Space: O(n log n) | O(n) 📌 Key Takeaway: Hashmaps combined with sorting provide a simple way to solve frequency-based problems, though heaps or bucket sort can optimize performance further. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
Day 28 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Convert Numbers to Words We were given a number. Task was to convert it into words. Example: 123 → One Hundred Twenty Three This problem was more about mapping. And understanding place values. 💻 Approach 🔹️Create mappings for digits 0–9. 🔹️Create mappings for 10–19 (special cases). 🔹️Create mappings for tens like 20, 30, 40... 🔹️Also store place values like hundred and thousand. Then process the number step by step. 🔹️Traverse the number from left to right. 🔹️If more than two digits remain, handle place values. 🔹️If two digits remain and first digit is 1, use teen mapping. 🔹️Otherwise print tens and units separately. Continue until all digits are processed. 📊 Complexity Analysis Time Complexity: O(n) Each digit is processed once. Space Complexity: O(1) Only fixed mapping arrays are used. 📚 What I learned today: ▫️This problem is essentially a lookup + formatting problem using constant mapping tables. ▫️Handling special ranges (10–19) separately avoids incorrect word formation. ▫️Breaking the number into place-value segments (hundreds, tens, units) simplifies logic. ▫️Designing clean mapping structures is important for problems involving symbolic representation. Day 28 completed. Learning different problem patterns every day 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
To view or add a comment, sign in
-
Day 78/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 141 – Linked List Cycle (Easy) 🧠 Approach: Use Floyd’s Cycle Detection (Tortoise & Hare). Move one pointer one step and another two steps. If they meet, a cycle exists. 💻 Solution: # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False ⏱ Time | Space: O(n) | O(1) 📌 Key Takeaway: Using two pointers at different speeds is an efficient way to detect cycles without extra space. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 84 of LeetCode Problem Solving Journey-#100DaysOfLeetCode Challenge: Today, I tackled a classic math and string manipulation problem in C++: "Excel Sheet Column Title". The Problem: Given an integer columnNumber, the goal is to return its corresponding column title as it appears in an Excel sheet (for example, 1 -> A, 28 -> AB, 701 -> ZY). My Approach: I used a mathematical base-conversion approach. It's very similar to converting a decimal number to a base-26 system, but with a slight twist because Excel columns are 1-indexed rather than 0-indexed. The Logic: Initialization: Create an empty string ans to store the final column title. While Loop: Continue iterating as long as columnNumber is greater than 0. The 0-Index Twist: The crucial step is doing columnNumber-- right at the start of the loop. This converts the 1-based Excel index to a 0-based index, allowing the modulo operator to work perfectly with 'A' to 'Z' (where A=0, B=1, ... Z=25). Character Extraction: Calculate the remainder (columnNumber % 26), add it to the ASCII value of 'A', and append the resulting character to ans. Update: Divide columnNumber by 26 to move on to the next place value. Final Step: Since we extract the characters from right to left (least significant to most significant), we reverse() the ans string before returning it. Time Complexity: O(log N) where base is 26, since we are dividing the number by 26 in each step. Space Complexity: O(1) auxiliary space (excluding the output string). Huge thanks to NEKAL SINGH SALARIA sir for the continuous guidance and helping us build a strong logical foundation step-by-step! 💡 Just 16 days to go to hit the ultimate 100-day milestone! The grind continues! 💻 #100DaysLeetCode #Day84 #CPP #Math #StringManipulation #DataStructures #Algorithms #DSA #ProblemSolving #CodingChallenge #LeetCode #Mentorship #REGexSoftwareServices #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