Day 21 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Replace all 0’s with 1 in a given integer We were given an integer. Task was simple. Replace every 0 with 1. At first it looked very basic. But there were two ways to approach it. Let’s understand it simply. ◾️Imagine a number written on paper. ◾️Whenever you see a 0, you overwrite it with 1. ◾️All other digits remain the same. That’s the idea. --- 💻 Approach 1 (Using String) 🔹️Convert the integer to a string. 🔹️Traverse each character. 🔹️If character is '0', replace it with '1'. 🔹️Convert the string back to integer. Very simple. Easy to implement. 💻 Approach 2 (Using Arithmetic) This avoids string conversion. 🔹️Extract digits using n % 10. 🔹️If digit is 0, change it to 1. 🔹️Build a new number using multiplication and addition. 🔹️Reverse it again to maintain correct order. More number manipulation involved. 📊 Complexity Analysis Time Complexity: O(D) Where D is number of digits. Space Complexity: O(1) Only few variables used. 📚 What I learned today: ▫️Simple problems can have multiple approaches. ▫️String operations make digit problems easier. ▫️Arithmetic manipulation gives more control over digits. ▫️Understanding both approaches improves problem solving. Day 21 completed. Learning small tricks every day 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
Replacing 0s with 1s in an Integer: 2 Approaches
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 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 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
To view or add a comment, sign in
-
Day 43 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Factorial of a Number We were given an integer n. Task was to find n! Factorial means: n! = n × (n-1) × (n-2) … × 1 Example: 5! = 5 × 4 × 3 × 2 × 1 = 120 💻 Iterative Approach 🔹️Initialize result = 1. 🔹️Run a loop from 1 to n. 🔹️Multiply each number with result. 🔹️Return final result. Simple loop. Easy to understand. Time Complexity: O(n) Space Complexity: O(1) 💻 Recursive Approach 🔹️Base case: ▪️If n == 0 or n == 1 → return 1 🔹️Recursive case: ▪️Return n × factorial(n-1) Breaks problem into smaller parts. Time Complexity: O(n) Space Complexity: O(n) Due to recursion stack. 📚 What I learned today: ▫️Recursion is based on defining smaller subproblems. ▫️Base case is necessary to stop recursion. ▫️Iterative approach is more space efficient. ▫️Same problem can be solved in multiple ways. Day 43 completed. Strengthening recursion vs iteration concepts 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic
To view or add a comment, sign in
-
Solved an interesting algorithm problem today! | Day 2 of 100 Days of LeetCode Problem: Best Time to Buy and Sell Stock The challenge was to determine the maximum profit from a single buy and sell transaction given an array of daily stock prices. Approach: A brute-force solution would compare every pair of days, resulting in O(n²) time complexity. However, the optimized approach involves tracking the minimum stock price encountered so far while traversing the array. At each step, we calculate the potential profit by subtracting the minimum price from the current price, updating the maximum profit whenever a better opportunity appears. This allows the problem to be solved efficiently in O(n) time using a single pass. Key Learnings from Today’s Problem: • The importance of choosing the right approach instead of brute force • How a simple observation can significantly improve algorithm efficiency • Strengthening understanding of arrays and greedy strategies Consistent practice like this helps build stronger problem-solving skills, logical thinking, and coding efficiency. Looking forward to learning something new with every problem solved. #Day2 #100DaysOfLeetCode #LeetCode #DataStructures #Algorithms #ProblemSolving #CodingJourney #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Day 25/50 – LeetCode Challenge 🧩 Problem: Spiral Matrix Today’s problem focused on traversing a matrix in a spiral order, which is a great exercise for understanding matrix boundaries and traversal patterns. 📌 Problem Summary: Given an m × n matrix, return all elements of the matrix in spiral order (clockwise). Example: Input: [ [1,2,3], [4,5,6], [7,8,9] ] Output: [1,2,3,6,9,8,7,4,5] 🔍 Approach Used ✔ Used four boundaries: top bottom left right ✔ Traversed step by step: Left → Right Top → Bottom Right → Left Bottom → Top ✔ After each step, updated the boundaries to avoid repetition ⏱ Time Complexity: O(m × n) 📦 Space Complexity: O(1) 💡 Key Learning ✔ Managing matrix traversal using boundaries ✔ Handling edge cases carefully ✔ Improving logical flow for multi-directional problems This problem helped strengthen my understanding of matrix-based algorithms and traversal techniques. Consistency is the key to mastery 🚀 🔗 Problem Link: https://lnkd.in/gT6-WfXj #50DaysOfLeetCode #LeetCode #DSA #Matrix #ProblemSolving #CodingJourney #FutureAIEngineer #Consistency
To view or add a comment, sign in
-
-
Day 5 of 100 Days of LeetCode – Improving Problem-Solving Skills Problem Solved: Move Zeroes Today’s problem focused on rearranging an array such that all zeroes are moved to the end while maintaining the relative order of the non-zero elements. 🔍 Approach: Instead of creating a new array or performing multiple shifts, the optimized solution uses a two-pointer technique. One pointer tracks the position where the next non-zero element should be placed, while the other pointer traverses the array. Whenever a non-zero element is encountered, it is swapped to the correct position. This ensures all non-zero elements remain in order while pushing zeroes toward the end efficiently. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💡 Key Takeaways: • Learned how the two-pointer technique simplifies array manipulation • Importance of in-place operations to reduce extra space usage • Strengthening understanding of efficient array traversal Each problem solved helps build stronger algorithmic thinking and coding discipline. #Day5 #100DaysOfLeetCode #LeetCode #DataStructures #Algorithms #ProblemSolving #CodingJourney #SoftwareDevelopment
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
-
-
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
-
🔥 Day 163 of My LeetCode Journey Problem 22: Generate Parentheses 💡 Problem Insight: Today’s problem was about generating all valid combinations of n pairs of parentheses. This isn’t about generating all strings it’s about building only valid ones from the start. 🧠 Concept Highlight: The solution uses backtracking with constraints: Add '(' if you still have openings left Add ')' only if it won’t break validity (closing ≤ opening) Explore all valid paths and backtrack cleanly This avoids generating invalid combinations and keeps the search space controlled. 💪 Key Takeaway: Don’t generate everything and filter later. Build only valid states — that’s the difference between brute force and smart recursion. ✨ Daily Reflection: This problem reinforces that recursion is about decision trees and constraints, not just function calls. Once you visualize the tree, the logic becomes clear. #Day163 #LeetCode #Backtracking #GenerateParentheses #ProblemSolving #DSA #CodingJourney #Consistency
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