🌟 Day 91 of #100DaysOfLeetCode Challenge! 🚀 Today I solved the problem no. 50 on LeetCode: Pow(x, n) APPROACH : 1. If n == 0: Any number raised to the power of 0 is 1, so return 1. 2. If x == 0: Any non-zero number raised to the power of 0 is 1, so return 0. 3. If n < 0: We need to compute the reciprocal of x raised to the positive value of n (-n). This is handled by setting x = 1/x and making n positive (n = -n). 4. Initialize ans to 1, which will accumulate the result of x raised to the power as we iterate. 5. Use a while loop that continues as long as n is non-zero. 6. Inside the loop: If n is even (n % 2 == 0), square x (x = x * x) and halve n (n = n / 2). If n is odd (n % 2 == 1), multiply ans by x (ans = ans * x) and decrement n by 1 (n = n - 1). 7. Once the while loop completes (i.e., n becomes zero), ans contains x raised to the power of n, considering the adjustments made for negative exponents (if any). 8. Return ans, which is the computed result of x raised to the power n. TIME COMPLEXITY: O(logn) SPACE COMPLEXITY: O(1) Feel free to contribute your approaches as well. #100DaysOfLeetCode #CodingChallenge #Algorithms #Programming #TechSkills #CodingAdventure #GeekModeActivated #leetcodechallenge
Himanshi Verma’s Post
More Relevant Posts
-
🌟 Day 94 of #100DaysOfLeetCode Challenge! 🚀 Today I solved the problem no. 1482 on LeetCode: Minimum Number of Days to Make m Bouquets APPROACH : 1. Initialize left to 0 (the minimum possible days) and right to 1e9 (a large number to act as an upper bound for days). 2. Initialize ans to -1 to track the minimum days found that satisfy the condition. 3. Perform binary search between left and right: a. Calculate mid as the middle point using (left + right) / 2. b. Use a sliding window approach (j variable) to count consecutive flowers that bloom on or before mid: 4. Traverse through the bloomDay array. a. If bloomDay[i] <= mid, increment j. b. If bloomDay[i] > mid, reset j to 0. 5. Whenever j reaches k, it indicates that k consecutive flowers have bloomed within mid days. Increment the count of bouquets and reset j to 0. 6. After processing all flowers for a given mid, check if the count of bouquets formed is >= m. If yes, update ans to mid (potential minimum days found) and adjust right to mid - 1 to search for a smaller number of days. If no, adjust left to mid + 1 to search for more days. 7. After the binary search completes (left > right), ans will hold the minimum number of days required to produce at least m bouquets of k flowers each. TIME COMPLEXITY: O(nlog(max_bloomDay)), where n is the number of elements in bloomDay. SPACE COMPLEXITY: O(1) Feel free to contribute your approaches as well. #100DaysOfLeetCode #CodingChallenge #Algorithms #Programming #TechSkills #CodingAdventure #GeekModeActivated #leetcodechallenge
To view or add a comment, sign in
-
🌟 Day 67 of #100DaysOfLeetCode Challenge! 🚀 Today I solved the problem no. 2597 on LeetCode: The Number of Beautiful Subsets APPROACH : 1. The function beautifulSubsets initializes the count variable to zero. 2. It then calls the helper function makesubsets to start the process of generating subsets and checking if they are beautiful. 3. Finally, it returns the count of beautiful subsets. 4. The makeSubsets is a recursive function that generates all possible subsets of the array nums. 5. It maintains a list subsets to keep track of the current subset being formed. 6. If the current index idx exceeds or equals the size of nums, it means a subset has been formed: a. If this subset is not empty, it increments the count. b. Then, it returns to explore other possible subsets. 7. For each element in the array, the function decides whether to include it in the current subset: a. It checks if including the current element nums[idx] would keep the subset beautiful. This is done by ensuring no element in the current subset has an absolute difference of k with nums[idx]. b. If the subset remains beautiful after including nums[idx], it is added to the current subset. c. The function then recursively calls itself to explore further elements with the updated subset. 8. After the recursive call, it backtracks by removing the last element added to the subset to explore subsets that do not include nums[idx]. 9. Regardless of whether the current element is included or not, the function also explores the path where the current element is excluded. TIME COMPLEXITY: O(2^n.n) SPACE COMPLEXITY: O(n) Feel free to contribute your approaches as well. #100DaysOfLeetCode #CodingChallenge #Algorithms #Programming #TechSkills #CodingAdventure #GeekModeActivated #dsachallenge #codingjourney #problemsolving #leetcodechallenge
To view or add a comment, sign in
-
🌟 Day 42 of #100DaysOfLeetCode Challenge! 🚀 Today I solved the problem no. 3132 on LeetCode: Find the Integer Added to Array II. APPROACH : 1. The check function takes three arguments: an integer x, and two vectors of integers nums1 and nums2. 2. It initializes a counter count to 0 and a variable j to 0. 3. It iterates through both vectors simultaneously using a single loop. 4. For each iteration, it checks if the sum of the current element of nums1 and x is equal to the current element of nums2. If not, it increments the count. If they are equal, it increments j. 5. After the loop, it checks if count is greater than 2. If so, it returns 0; otherwise, it returns 1. 6. The minimumAddedInteger function takes two vector references nums1 and nums2. 7. It initializes variables n and m with the sizes of nums1 and nums2 respectively. 8. It sorts both vectors in non-decreasing order. 9. It initializes a variable minele with the maximum possible integer value. It iterates over first 3 elements of nums1. 10. For each element, it calculates the difference x between the first element of nums2 and the current element of nums1. 11. It then calls the check function with x, nums1, and nums2 as arguments. 12. If check returns true, it updates minele with the minimum value between minele and x. 13. Finally, it returns minele. TIME COMPLEXITY: O(n*logn) SPACE COMPLEXITY: O(1) Feel free to contribute your approaches as well. #100DaysOfLeetCode #CodingChallenge #Algorithms #Programming #TechSkills #CodingAdventure #GeekModeActivated #dsachallenge #codingjourney #problemsolving #leetcodechallenge
To view or add a comment, sign in
-
🚀 Day 43 of LeetCode 75 Challenge! 🚀 Today, I tackled the Rotting Oranges 🍊 problem, and successfully optimized my solution to run in 0 ms, beating 100% in runtime performance! 🔥 Problem Overview: We are given an `m x n` grid where: - `0` represents an empty cell, - `1` represents a fresh orange 🍊, and - `2` represents a rotten orange 🍊. Every minute, any fresh orange adjacent to a rotten one rots. The challenge is to determine the minimum number of minutes that must elapse before no fresh oranges remain. If it's impossible to rot all fresh oranges, return `-1`. Solution Approach: I used a Breadth-First Search (BFS) approach, using a queue to track rotten oranges and spread the rot minute by minute. If all fresh oranges rot, the time is recorded; otherwise, we return `-1`. Another challenging but fun problem, keeping the momentum going! ⚡ #leetcode #codingchallenge #algorithm #codenewbie #BFS #100percent #datastructures #competitiveprogramming #learningeveryday #keepcoding #programminglife 💻
To view or add a comment, sign in
-
🌟 Day 36 of #100DaysOfLeetCode Challenge! 🚀 Today I solved the problem no. 752 on LeetCode: Open the lock. APPROACH: 1. Initialize an unordered set deadendSet to store the deadend combinations for easy checking. 2. Initialize another unordered set visited to keep track of visited combinations. 3. Check if the initial combination "0000" is a deadend. If it is, return -1 immediately as the lock cannot be opened. 4. Start a BFS by initializing a queue q. Each element of the queue is a pair containing the current combination and the number of moves required to reach it. 5. Push the starting combination "0000" with 0 moves into the queue and mark it as visited. 6. While the queue is not empty, dequeue a combination and its corresponding number of moves. 7. Check if the current combination matches the target combination. If it does, return the number of moves required to reach it. 8. If the current combination does not match the target: a. Iterate over each digit of the combination. b. For each digit, try both turning it clockwise and counterclockwise by adding and subtracting 1 modulo 10 (to wrap around from 9 to 0 and vice versa). c. Generate the new combination by updating the digit. d, Check if the new combination is not in the visited set and is not a deadend. 9. If it satisfies these conditions, mark it as visited, enqueue it into the queue with the incremented number of moves. 10. If the target combination is not found after exploring all possible combinations, return -1 indicating that the lock cannot be opened. TIME COMPLEXITY: O(n), n = no. of possible combinations reached from "0000" SPACE COMPLEXITY: O(n) + O(deadends) Feel free to contribute your approaches as well. #100DaysOfLeetCode #CodingChallenge #Algorithms #Programming #TechSkills #CodingAdventure #GeekModeActivated #dsachallenge #codingjourney #problemsolving #leetcodechallenge
To view or add a comment, sign in
-
🌟 Day 72 of #100DaysOfLeetCode Challenge! 🚀 Today I solved the problem no. 1208 on LeetCode: Get Equal Substrings Within Budget. APPROACH : 1.Determine the length of the strings s and t (since they are of equal length, using s.length() is sufficient). 2. Initialize variables - maxlength to store the maximum length of the valid substring found so far, two pointers i and j for the sliding window, both starting at 0, cost to keep track of the current cost of transforming the substring s[i...j] to t[i...j]. 3. Use a while loop to iterate over the characters of the strings as long as j (the end pointer of the window) is less than n (the length of the strings). 4. For each character at position j, calculate the transformation cost (abs(s[j] - t[j])) and add it to the current cost. 5. If the updated cost is within the allowed maxCost, update maxlength if the current window size (j - i + 1) is greater than the previously recorded maximum length. 6. Move the end pointer j one step to the right to expand the window. 7. If the cost exceeds maxCost, shrink the window from the left: a. Use another while loop to reduce the cost by subtracting the transformation cost of the character at the start pointer i and move the start pointer i one step to the right until the cost is within maxCost again. b. After adjusting, move the end pointer j one step to the right. 8. Once the loop completes, the maxlength will hold the maximum length of the valid substring found, which is then returned as the result. TIME COMPLEXITY: O(n) SPACE COMPLEXITY: O(1) Feel free to contribute your approaches as well. #100DaysOfLeetCode #CodingChallenge #Algorithms #Programming #TechSkills #CodingAdventure #GeekModeActivated #dsachallenge #codingjourney #problemsolving #leetcodechallenge
To view or add a comment, sign in
-
🚀 Just solved LeetCode Problem 2583: Kth Largest Sum in a Binary Tree with an efficient and clean approach! 🎉 📊 My solution leverages DFS traversal to accumulate sums for each level, storing them in an array. After that, I apply a descending sort to quickly access the Kth largest sum! 🧠 The approach optimizes both time and space complexity, ensuring that it works efficiently even for large trees. 🌳⏱️ This blend of recursion and sorting keeps the code simple while ensuring high performance! 💡💻 Check out the C code below! 🧑💻 Git: https://lnkd.in/g4unsh7q Leetcode: https://lnkd.in/gJgptwW8 #CodeOptimization #CodingJourney #CProgramming #LeetCodeChallenge #ProblemSolving #BinaryTree #Algorithms #DataStructures #CodingLife #Tech #CodeMastery #ProgrammersLife #LinkedInTech #LeetCodeDaily #CodeMaster #DeveloperLife #TechCommunity
To view or add a comment, sign in
-
🌟 Day 73 of My 100 Days of LeetCode Challenge 🌟 Today, I tackled and conquered the "Magnetic Force Between Two Balls" problem on LeetCode! 🎉 This problem was a great exercise in binary search and required a keen understanding of optimizing placement to maximize minimum distance. It's always satisfying to see how theoretical concepts can be applied to solve such intriguing problems. 🔍 Key Learnings: 1. Binary Search: Leveraged binary search to efficiently find the optimal solution. 2. Optimization Techniques: Applied techniques to maximize the minimum distance, ensuring the most balanced solution. 3. Problem-Solving Skills: Enhanced my problem-solving toolkit by working through edge cases and constraints. 💡 Problem Overview: Given n positions on a straight line and a number of balls, the goal is to place the balls in these positions such that the minimum magnetic force between any two balls is maximized. It's challenges like these that make me appreciate the beauty of algorithmic problem-solving. Onward to the next challenge! 🚀 #100DaysOfCode #LeetCode #CodingChallenge #ProblemSolving #BinarySearch #Algorithms #Programming #TechJourney
To view or add a comment, sign in
-
Day 57 of the #100DaysOfCode Challenge! 🚀 Problem Solved: LeetCode 153 - Find Minimum in Rotated Sorted Array Approach: Initialize pointers and the result variable. Check if the array is sorted: If the first element is less than the last, return the first element. Binary search: - Calculate the midpoint. - Update the result with the minimum of the current result and the midpoint. - Adjust pointers based on the sorted halves. Return the minimum value found. Excited to tackle this problem and keep pushing forward in my coding journey! Every challenge is a step closer to mastery. Let’s continue this journey together! 💻✨ #100DaysOfCode #LeetCode #ProblemSolving #LearningJourney #CodeHelp #DSA #TechJourney #Algorithms #DataStructures #CodingChallenge #Consistent
To view or add a comment, sign in
-
🚀 🚀 DAY 19 of #28daysofcode :- Hey linkedIn people!!!👋 🌟 Today, I have tackled a problem of leetcode which says:- problem statement:- You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. you may not slant the container. problem link:- https://lnkd.in/g3_89QnY I would love to connect with you people at any hour here on the LinkedIn or on the twitter maybe-(https://lnkd.in/gsTgZzd7) You can even drop your suggestions in the following comment box.. #28daysofcode #codingchallenge #DSA #algorithms #problemsolving #dailylearning #Arrays #codingskill #techlearning #coding #programmingjourney #techskills #codelife #leetcode #codeforces #learningtogether #dailychallenge #strings #characterarrays #complexities #2DArrays #dataStructures #binarysearch #sorting
To view or add a comment, sign in