Day 12 of Solving LeetCode 75 [ q- 14 ] Maximum Average Subarray I You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10^-5 will be accepted. Example 1: Input: nums = [1,12,-5,-6,50,3], k = 4 Output: 12.75000 Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 Example 2: Input: nums = [5], k = 1 Output: 5.00000 Constraints: n == nums.length 1 <= k <= n <= 105 -104 <= nums[i] <= 104 In a java class 1. Create a method which accepts an array of numbers and a integer variable k. 2. Initialize a long variable to store the sum of k integers. 3. Use a for loop to find the sum of first k elements. 4. Initialize a variable to store the maximum sum. 5. Iterate through the array starting from index k. 6. Update the sum by adding the current element and subtracting the element at position (i - k). 7. Update the maximum sum. 8. Calculate and return the maximum average by dividing the maximum sum by k. Time Complexity: The code iterates through the array nums only once, both iterations have a time complexity of O(n), where n is the length of the array nums, therefore, the overall time complexity is O(n). Space Complexity: The code uses a constant amount of extra space regardless of the input size, therefore, the space complexity is O(1), constant space complexity. #java #leetcode
Vikasa M R’s Post
More Relevant Posts
-
Day 28 of Solving LeetCode 75 [ q- 31 ] Reverse Linked List Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is the range [0, 5000]. -5000 <= Node.val <= 5000 Solution ( iterative solution ): In a java class 1. Create a method which accepts a singly linked list. 2. Initialize a new node to null. 3. Use a while loop to iterate over each node in the original list. 4. After the loop ends , return newHead, which is now the head of the reversed list. Logic - * save the next node in the original list in a variable next. * set the next pointer of the current node to point to newHead, effectively reversing the next pointer direction. * update newHead to point to the current node, effectively moving the newHead pointer one step forward. * move the head pointer to the next node in the original list. * when head becomes null, indicating the end of the original list. #timecomplexity : The time complexity of this algorithm is O(N). The algorithm traverses the original list once to reverse it. #spacecomplexity : The space complexity of this algorithm is O(1) since it uses only a constant amount of extra space regardless of the size of the input linked list. #javaprogramming #javadevelopers #java #codingcommunity #leetcode
To view or add a comment, sign in
-
Day 15 of Solving LeetCode 75 [ q- 17 ] Longest Subarray of 1's After Deleting One Element Hint Given a binary array nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray. Example 1: Input: nums = [1,1,0,1] Output: 3 Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's. Example 2: Input: nums = [0,1,1,1,0,1,1,0,1] Output: 5 Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1]. Example 3: Input: nums = [1,1,1] Output: 2 Explanation: You must delete one element. Constraints: 1 <= nums.length <= 105 nums[i] is either 0 or 1. In a java class 1. Create a method which accepts an array of numbers[nums] 2. Declare 4 integer variables [i,j,k=1,l] 3. Use a for loop to iterate the array with a var [j] 4. with a nested if condition check nums[j] is 0 if so reduce the value of k by 1. 5. Use a nested while loop (k < 0), if nums[i] is 0, then increment k by 1, initialize l with the maximum value between (l and j-i) 6. return l Time Complexity: The code iterates through the array nums only once, both iterations have a time complexity of O(n), where n is the length of the array nums, therefore, the overall time complexity is O(n). Space Complexity: The code uses a constant amount of extra space, regardless of the size of the input array nums, therefore, the space complexity is O(1), constant space complexity. #javaprogramming #javafullstack #java #leetcode #problemsolving
To view or add a comment, sign in
-
𝗗𝗶𝘃𝗶𝗻𝗴 𝗶𝗻𝘁𝗼 𝘁𝗵𝗲 𝗛𝗲𝗮𝗿𝘁 𝗼𝗳 𝗝𝗮𝘃𝗮: 𝗝𝗩𝗠 𝗔𝗿𝗰𝗵𝗶𝘁𝗲𝗰𝘁𝘂𝗿𝗲 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱 🖥️ 🛠️ 𝙒𝙝𝙖𝙩 𝙞𝙨 𝙩𝙝𝙚 𝙅𝙑𝙈? The JVM is the engine that runs Java applications. It converts your compiled Java code (bytecode) into machine code that your computer can understand. Think of it as the middleman between your Java program and your hardware. 🧩 𝙆𝙚𝙮 𝘾𝙤𝙢𝙥𝙤𝙣𝙚𝙣𝙩𝙨 𝙤𝙛 𝙅𝙑𝙈 𝘼𝙧𝙘𝙝𝙞𝙩𝙚𝙘𝙩𝙪𝙧𝙚 : 1️⃣ 𝘾𝙡𝙖𝙨𝙨 𝙇𝙤𝙖𝙙𝙚𝙧 𝙎𝙪𝙗𝙨𝙮𝙨𝙩𝙚𝙢 - Loads .class files (bytecode) into memory. - Verifies and prepares the code for execution. - Dynamically links dependencies during runtime. 2️⃣ 𝙈𝙚𝙢𝙤𝙧𝙮 𝘼𝙧𝙚𝙖𝙨 - Method Area: Stores class structures like methods, fields, and runtime constants. - Heap: The space where objects are stored. This is managed by garbage collection. - Stack: Holds method calls and local variables for each thread. Each thread gets its own stack. - PC Register: Keeps track of the address of the currently executing instruction for each thread. - Native Method Stack: Handles native (non-Java) methods. 3️⃣ 𝙀𝙭𝙚𝙘𝙪𝙩𝙞𝙤𝙣 𝙀𝙣𝙜𝙞𝙣𝙚 - Interpreter: Executes bytecode line by line. - JIT Compiler (Just-In-Time Compiler): Converts frequently used bytecode into machine code for better performance. - Garbage Collector: Automatically frees memory by removing unused objects. 4️⃣ 𝙅𝙖𝙫𝙖 𝙉𝙖𝙩𝙞𝙫𝙚 𝙄𝙣𝙩𝙚𝙧𝙛𝙖𝙘𝙚 (𝙅𝙉𝙄) - Allows Java to interact with native code written in languages like C and C++. 📚 Here are some great resources to deepen your understanding of JVM Architecture: -https://lnkd.in/deKtseTF -https://lnkd.in/dhA4bbEy #Java #JVM #BackendDevelopment #Software #Development #Programming #LearningJourney #Coding #SystemDesign
To view or add a comment, sign in
-
🚀 Just tackled another exciting problem from LeetCode 75! 🌟 Check out my latest blog on solving the "Max Number of K-Sum Pairs" problem. This medium-level challenge dives deep into array manipulation and the two-pointer technique. 🧩💡 Discover the approach, solution, and insights into maximizing operations with efficient pair sums. Perfect for anyone looking to enhance their problem-solving skills! 💻✨ Read more and let's connect over some code! 🔗 #LeetCode75 #CodingChallenges #ProblemSolving #TechBlogs #Java
To view or add a comment, sign in
-
Leetcode problem of the day : Time Needed to Buy Tickets The problem that we are tackling for today is calculating the time required to purchase a specific number of tickets, as depicted in the provided Java code. Approach used : 1. Initialization: We initialize the variable `neededTime` to 0 to keep track of the total time required for ticket purchase. We also retrieve the length of the `tickets` array, denoted as `n`. 2. Iterating through Tickets: We iterate through each element of the `tickets` array using the index `i`. For each ticket: - If `i` is less than or equal to `k`, we add the minimum value between the number of tickets at index `k` and the current ticket count at index `i` to the `neededTime`. - If `i` is greater than `k`, we add the minimum value between one less than the number of tickets at index `k` (indicating that one ticket has been purchased) and the current ticket count at index `i`. 3. Calculating Total Time: After iterating through all tickets, we obtain the total time required for the purchase, stored in the variable `neededTime`. 4. Returning Result: Finally, we return the calculated `neededTime`. Time Complexity : O(N) Space Complexity : O(1) Link : https://lnkd.in/gSWCg8ek Feel free to reach out if you have any questions or suggestions! Happy coding! 🎟️🕒 #Algorithm #Java #TicketPurchase #Optimization #ArrayManipulation #DSA #CodingJourney #CodingChallenge #DataStructuresAndAlgorithms #LeetcodeDailyChallenge #CompetativeProgramming #Consistency❤💪🏻
To view or add a comment, sign in
-
🔐 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐨𝐟 𝐭𝐡𝐞 𝐃𝐚𝐲: 𝐃𝐞𝐟𝐮𝐬𝐞 𝐭𝐡𝐞 𝐁𝐨𝐦𝐛(#1652) - LeetCode (Java Solution) 💥 Today, I solved the "𝐃𝐞𝐟𝐮𝐬𝐞 𝐭𝐡𝐞 𝐁𝐨𝐦𝐛" problem on LeetCode, an excellent exercise in array manipulation and understanding modular arithmetic. 💡 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐮𝐦𝐦𝐚𝐫𝐲: Given an integer array code and an integer k, the goal is to return an array where each element is the sum of all elements of code except for the current one, with the caveat that the array is rotated by k positions. 🧠 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: 1. 𝐑𝐨𝐭𝐚𝐭𝐢𝐨𝐧 𝐋𝐨𝐠𝐢𝐜: 𝐢. If k is positive, rotate the array right. 𝐢𝐢. If k is negative, rotate left. 𝐢𝐢𝐢. Instead of actually rotating the array, we can use modular arithmetic to calculate the "virtual" rotation for each element. 2. 𝐄𝐟𝐟𝐢𝐜𝐢𝐞𝐧𝐭 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧: 𝐢. First, we calculate the sum of the elements we need (the next k elements). 𝐢𝐢. Then, using modular arithmetic, we adjust the sum as we slide through the array, without needing to rotate it physically. 🧩 𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧: 𝐢. 𝐈𝐧𝐢𝐭𝐢𝐚𝐥𝐢𝐳𝐚𝐭𝐢𝐨𝐧: 𝐢. We start by calculating the sum of the next k elements based on the direction of the rotation (k > 0 for right, k < 0 for left). 𝐢𝐢. 𝐒𝐥𝐢𝐝𝐢𝐧𝐠 𝐖𝐢𝐧𝐝𝐨𝐰 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡: 𝐢. As we move through the array, we adjust the sum by subtracting the element leaving the window and adding the new element entering the window. This allows us to compute the result efficiently. 3. 𝐄𝐝𝐠𝐞 𝐂𝐚𝐬𝐞: 𝐢. If k == 0, we immediately return an array of zeroes since no rotation or summing happens. 🔑 𝐊𝐞𝐲 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲𝐬: 𝐢. 𝐒𝐥𝐢𝐝𝐢𝐧𝐠 𝐖𝐢𝐧𝐝𝐨𝐰: This approach efficiently computes the sum of the next k elements without rotating the array. 𝐢𝐢. 𝐌𝐨𝐝𝐮𝐥𝐚𝐫 𝐀𝐫𝐢𝐭𝐡𝐦𝐞𝐭𝐢𝐜: Using modulo to wrap around the array indices allows us to avoid index out-of-bound errors. 💻 #Java #LeetCode #ProblemSolving #AlgorithmDesign #SlidingWindow #TechChallenges #SoftwareDevelopment #CodingJourney
To view or add a comment, sign in
-
Hello Connections, 100 days of Leetcode challenge: Day 32: Find the first occurence of the string. Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Example 1: Input: haystack = "sadbutsad", needle = "sad" Output: 0 Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0. Example 2: Input: haystack = "leetcode", needle = "leeto" Output: -1 Explanation: "leeto" did not occur in "leetcode", so we return -1. Approach:A code approach involves systematically planning and executing a solution to a programming problem. Start by thoroughly understanding the requirements and constraints. Break the problem into smaller, manageable tasks. Design a clear algorithm or flowchart to outline the steps. Write clean, modular code, ensuring each function has a single responsibility. Use meaningful variable names and add comments for clarity. Test each module independently and then as an integrated whole. Debug by identifying and fixing errors iteratively. Optimize for performance and readability. Finally, review the code for improvements and document it for future maintenance. Method to Solve: There are tooo many approach is available but this code sloved by using "equals function in java" #100DaysofLeetcodeChallenge
To view or add a comment, sign in
-
📚 Day 32 of my LeetCode Journey! 🌟 Today, I tackled the "Reverse Words in a String" problem on LeetCode. The task was to reverse the order of characters in each word within a sentence while maintaining the word order. This problem tested my string manipulation skills and understanding of array operations. Here's the Java solution I implemented to solve this problem: class Solution { public String reverseWords(String s) { String[] words = s.trim().split("\\s+"); // Create a StringBuilder to construct the reversed string StringBuilder reversed = new StringBuilder(); // Iterate over the words in reverse order and append them to the StringBuilder for (int i = words.length - 1; i >= 0; i--) { reversed.append(words[i]); if (i > 0) { reversed.append(" "); // Append a space between words } } return reversed.toString(); } } In this solution, I utilized the split method to split the input string s into individual words, and then I used a StringBuilder to construct the reversed string by iterating over the words in reverse order. By appending each word to the StringBuilder and adding a space between words, I was able to achieve the desired output. This problem was a great exercise in practicing string manipulation techniques and understanding how to iterate over arrays in reverse order. It also reinforced the importance of handling edge cases, such as extra spaces and leading/trailing whitespace, to ensure a correct solution. Stay tuned for more updates as I continue my 100-day LeetCode journey! 🚀📊 #LeetCode #100DaysOfCode #StringManipulation #CodingChallenges
To view or add a comment, sign in
-
Search in Rotated Sorted Array LeetCode Question: How would you search for a target value in a rotated sorted array? For example, given the array [4,5,6,7,0,1,2], how would you find the index of the value 0? Explanation: A rotated sorted array is an array that has been sorted and then rotated. For instance, [0,1,2,4,5,6,7] becomes [4,5,6,7,0,1,2] after a rotation. The challenge is to search for a target value efficiently, taking advantage of the properties of both sorting and rotation. Approach: 1. Initialize Pointers: Start with two pointers, low and high, pointing to the start and end of the array. 2. Binary Search Loop: While low is less than or equal to high: - Compute the middle index mid. - If the element at mid is the target, return mid. - Determine which half of the array is sorted: - If the left half is sorted, check if the target lies within this range and adjust pointers accordingly. - If the right half is sorted, check if the target lies within this range and adjust pointers accordingly. 3. Return -1: If the loop completes without finding the target, return -1. Time Complexity: The time complexity of this approach is O(logn), where n is the number of elements in the array. This is due to the binary search methodology which halves the search space with each iteration. Space Complexity: The space complexity is O(1) since only a constant amount of extra space is used for the pointers and variables. Question Link - https://lnkd.in/d9sXYysE Solution Link - https://lnkd.in/dpZgfWsh #DSA #ProblemSolving #RotatedArray #LeetCode #JAVA #LinkedInLearning
To view or add a comment, sign in
-
Day 26 of #31DaysOfCode (Target for this month) Updating after a long time. (due to my inconsistency) 1)Solved problems on LeetCode today, got to know about ArrayList in Java, its syntax and its use, its similarities and differences with arrays. Problems based on counting frequencies of elements in an array using ArrayList and iterating through the ArrayList. 2)Revised Classes and Objects in Java, how classes and objects work with respect to each other. Read about Data Abstraction and Encapsulation examples. Learned more about access modifiers in Java i.e. private, public, protected, and default. 3)Completed the first two videos of HTML playlist by Hitesh Choudhary Sir on "Chai Aur Code" channel. Came to learn about: - History of HTML. - Why HTML is used and its importance. - Why HTML is more a structured language than a markup language? - Head tag and Body Tag, Emmet abbreviation, Extensions, and keyboard shortcuts. The best thing about Hitesh Choudhary Sir is that "He highly inspires others to read the official docs for self-learning and proper understanding". Link:- https://lnkd.in/gyB57y2B #LearningInPublic #LearnInPublic #BuildInPublic #BuildingInPublic #HTML #ChaiAurCode #HiteshChoudhary #Java #DSA #ArrayList #Arrays #LeetCode #ProblemSolving
To view or add a comment, sign in