✨ 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴: 𝗙𝗶𝗻𝗱𝗶𝗻𝗴 𝘁𝗵𝗲 𝗞𝘁𝗵 𝗟𝗮𝗿𝗴𝗲𝘀𝘁 𝗘𝗹𝗲𝗺𝗲𝗻𝘁 𝗘𝗳𝗳𝗶𝗰𝗶𝗲𝗻𝘁𝗹𝘆 ✨ Today, I tackled a LeetCode problem that initially seemed simple: finding the kth largest element in an array. Initially, the straightforward solution was to sort the array and pick the kth largest from the end. But sorting takes O(nlogn) time—what if we could do better? After some thought, I considered heaps! With a heap, we can reduce the time complexity to O(nlogk) by maintaining only the k largest elements. But that’s not where the magic ends... 𝗘𝗻𝘁𝗲𝗿 𝗖𝗼𝘂𝗻𝘁𝗶𝗻𝗴 𝗦𝗼𝗿𝘁! 🚀 I implemented counting sort, which gave me an elegant O(n) solution. Here's how it works: 1. 𝗙𝗶𝗻𝗱 𝘁𝗵𝗲 𝗠𝗶𝗻𝗶𝗺𝘂𝗺 𝗮𝗻𝗱 𝗠𝗮𝘅𝗶𝗺𝘂𝗺 𝗩𝗮𝗹𝘂𝗲𝘀: First, I identified the smallest and largest elements in the array to determine the range. 2. 𝗖𝗿𝗲𝗮𝘁𝗲 𝗮 𝗙𝗿𝗲𝗾𝘂𝗲𝗻𝗰𝘆 𝗔𝗿𝗿𝗮𝘆: When creating the frequency array, I considered an important detail: the array can have negative values. So, instead of just creating an array based on the maximum value, I also had to account for the minimum value. This means the array size is max - min + 1. For example, if the array is [-3, -1, 2, 4, -2], the minimum value is -3 and the maximum value is 4. To place the numbers in their correct positions in the frequency array, I use the formula num - minv. This means: • -3 becomes 0 (because -3 - (-3) = 0) • -1 becomes 2 (because -1 - (-3) = 2) • 2 becomes 5 (because 2 - (-3) = 5) • 4 becomes 7, and so on. This way, all negative numbers get valid positions in the array. 3. 𝗧𝗿𝗮𝘃𝗲𝗿𝘀𝗲 𝘁𝗵𝗲 𝗙𝗿𝗲𝗾𝘂𝗲𝗻𝗰𝘆 𝗔𝗿𝗿𝗮𝘆: Starting from the largest value, I decrement k by the count at each index. When k reaches zero or less, I've found the kth largest element. 𝗖𝗼𝗻𝘀𝗶𝗱𝗲𝗿𝗮𝘁𝗶𝗼𝗻𝘀 𝗮𝗻𝗱 𝗗𝗶𝘀𝗮𝗱𝘃𝗮𝗻𝘁𝗮𝗴𝗲𝘀: While counting sort is a powerful technique, it cannot be used everywhere. Here are some disadvantages to keep in mind: • Space Complexity: The frequency array size is max - min + 1, which can lead to high memory usage if the range of numbers is large. • Inefficiency with Sparse Data: In cases where numbers are limited but widely spread apart, the frequency array can waste space. • Limited Applicability: It works primarily for integers within a defined range and may not suit other data types. • Potential for Integer Overflow: When calculating max and min in large arrays, there's a risk of overflow in some languages (though not in Java). • Less Generalized: Unlike other algorithms like Quickselect, counting sort is specifically for integers, limiting its versatility. This approach avoids sorting, making the solution much more efficient. I am excited to keep learning and applying these techniques as I go! 🙌 Here is the link to the problem - https://lnkd.in/g29Dcttm #LeetCode #CodingTips #Algorithms #ProblemSolving #LearningJourney
Neha Bhatia’s Post
More Relevant Posts
-
🌳 **Day 137: Find the Kth Smallest Element in a Binary Search Tree (BST)** **Understanding the Problem:** We are given a binary search tree (BST) and an integer K. We need to find the Kth smallest element in the BST. Since the BST is structured in a way that an inorder traversal yields the nodes in sorted order, we can leverage this property. **Approach:** To solve this problem, we use an inorder traversal to visit the nodes in sorted order. We keep a counter to track the number of nodes visited and stop once we reach the Kth node. **Implementation:** 1. **Helper Function for Inorder Traversal:** - Define a helper function `solve` that performs an inorder traversal of the BST. - Use a counter to track the number of nodes visited. - If the counter matches K, set the answer to the current node's value. 2. **Main Function to Find Kth Smallest Element:** - Initialize the answer and counter variables. - Call the helper function to start the inorder traversal. - Return the answer once the traversal is complete. **Steps:** 1. Traverse the BST in inorder fashion. 2. Increment the counter each time a node is visited. 3. Once the counter matches K, capture the node's value as the answer. 4. Continue traversal until the Kth node is found. **Complexity Analysis:** - Time Complexity: O(N), where N is the number of nodes in the BST. In the worst case, we might need to visit all nodes. - Space Complexity: O(H), where H is the height of the BST. This space is used for the recursive call stack. This approach efficiently finds the Kth smallest element in a binary search tree. 🌟 #BinarySearchTree #KthSmallestElement #DSADay137 #AlgorithmInsights
To view or add a comment, sign in
-
The first step towards an understanding of why the study and knowledge of algorithms are so important is to define exactly what we mean by an algorithm. According to the popular algorithms textbook Introduction to Algorithms (Second Edition by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein), "an algorithm is any well- defined computational procedure that takes some value, or set of values, as input and produces some value, or set of values as output." In other words, algorithms are like road maps for accomplishing a given, well-defined task. So, a chunk of code that calculates the terms of the Fibonacci sequence is an implementation of a particular algorithm. Even a simple function for adding two numbers is an algorithm in a sense, albeit a simple one.
To view or add a comment, sign in
-
Day 41 of #100DaysOfCode Problem : Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n]. Example 1: Input: n = 13, k = 2 Output: 10 Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. Example 2: Input: n = 1, k = 1 Output: 1 Constraints: 1 <= k <= n <= 109
To view or add a comment, sign in
-
🌟 Day 2 of the GeeksforGeeks 160 Days Challenge Today's task: Implement KMP Algorithm for Pattern Searching 🔍 This problem emphasizes how efficient string matching can be achieved using the Knuth-Morris-Pratt (KMP) algorithm. Optimizing search operations for large texts is a key area for improvement in computational efficiency.🚀 🔍 Problem Statement: Given a pattern and a text, the task is to find all occurrences of the pattern in the text using the KMP algorithm. Return a list of indices where the pattern starts in the text. 🛠️ Solution Approach: Here's a breakdown of the KMP algorithm that I implemented: 1️⃣ Preprocessing with LPS (Longest Prefix Suffix) Array: Constructed an LPS array for the given pattern. This array helps avoid unnecessary re-checking of characters in the pattern, improving the time complexity of the search phase. For each character in the pattern, the LPS array tracks the length of the longest prefix that is also a suffix for the substring ending at that character. 2️⃣ Pattern Searching with KMP: I iterated through the text using two pointers, one for the pattern and one for the text. Whenever a mismatch occurred, the KMP algorithm efficiently shifts the pattern based on the LPS array, reducing the number of comparisons needed. Once a full match is found, I added the starting index of the match to the result list and continued searching with the help of the LPS values.
To view or add a comment, sign in
-
Our new article "On Improvements of Multi-Objective Branch and Bound" co-authored by Dr. Julius Bauß and Sophie Parragh is published in the EURO Journal on Computational Optimization. We improve the performance of multi-objective branch and bound by using objective space information to guide the search in promising directions and to obtain good approximations of the Pareto front in early stages of the algorithm. In particular, we use an indicator-based scheduling of subproblems and the solution of adaptively chosen scalarizations to integer optimality. EURO Journal on Computational Optimization (Open access) https://lnkd.in/e_HvgEYN
On improvements of multi-objective branch and bound
sciencedirect.com
To view or add a comment, sign in
-
🚀🌳 Day 25 of #100DaysOfCode 🔍 Today, I focused on finding the kth smallest element in a Binary Search Tree (BST), which utilizes the in-order traversal approach to efficiently retrieve sorted elements. Problem: Retrieve the kth smallest element from a BST. Key Insight: Since an in-order traversal of a BST produces nodes in ascending order, the kth element in this traversal is the desired result Approach: Perform an in-order traversal (left-root-right) to visit nodes in ascending order. Keep track of nodes visited and stop at the kth node, which provides the kth smallest element. Iterative Approach: Alternatively, using an iterative stack-based traversal can be memory-efficient and avoids recursion stack limits in large trees. Edge Cases: k is out of range (greater than the number of nodes or less than 1). The BST has only one node. k equals the number of nodes (returns the largest element). Complexity Analysis Time Complexity: O(h + k), where h is the tree height and k is the number of nodes traversed. In a balanced BST, this averages to O(log n + k). Space Complexity: O(h), for the stack in the iterative approach or recursion depth in recursive traversal. Learning In-order traversal's natural sorting property is particularly powerful when solving for the kth smallest or largest elements. #BinarySearchTree #KthSmallestElement #InOrderTraversal #BSTTraversal
To view or add a comment, sign in
-
I am very happy to share that our new article "On improvements of multi-objective branch and bound" co-authored by Michael Stiglmayr and Sophie Parragh has been published in the EURO Journal on Computational Optimization. Branch and bound methods which are based on the principle “divide and conquer” are a well established solution approach in single-objective integer programming. In multi-objective optimization, branch and bound algorithms are increasingly attracting interest. However, the larger number of objectives raises additional difficulties for implicit enumeration approaches like branch and bound. Since bounding and pruning is considerably weaker in multiple objectives, many branches have to be (partially) searched and may not be pruned directly. The adaptive use of objective space information can guide the search in promising directions to determine a good approximation of the Pareto front already in early stages of the algorithm. In particular, we focus in this article on improving the branching and queuing of subproblems and the handling of lower bound sets. In our numerical tests, we evaluate the impact of the proposed methods in comparison to a standard implementation of multi-objective branch and bound on knapsack problems, generalized assignment problems and (un)capacitated facility location problems.
Our new article "On Improvements of Multi-Objective Branch and Bound" co-authored by Dr. Julius Bauß and Sophie Parragh is published in the EURO Journal on Computational Optimization. We improve the performance of multi-objective branch and bound by using objective space information to guide the search in promising directions and to obtain good approximations of the Pareto front in early stages of the algorithm. In particular, we use an indicator-based scheduling of subproblems and the solution of adaptively chosen scalarizations to integer optimality. EURO Journal on Computational Optimization (Open access) https://lnkd.in/e_HvgEYN
On improvements of multi-objective branch and bound
sciencedirect.com
To view or add a comment, sign in
-
Insertion sort is a simple and intuitive sorting algorithm that builds the final sorted array one element at a time Let's take a look at how it works: Start with the Second Element: Assume the first element is already sorted. Take the second element and find its correct position in the sorted part of the array, then insert it there. Repeat for All Elements: Move to the next element and repeat the process until the entire array is sorted. Time Complexity: O(n^2) Space Complexity: O(1) because it sorts the list in place. #DSA #SDE #ALGORITHIMS
To view or add a comment, sign in
-
Human matting is a foundation task in image and video processing where human foreground pixels are extracted from the input. Prior works either improve the accuracy by additional guidance or improve the temporal consistency of a single instance across frames. This Paper proposes a new framework MaGGIe, Masked Guided Gradual Human Instance Matting, which predicts alpha mattes progressively for each human instance while maintaining the computational cost, precision, and consistency. The method leverages modern architectures, including transformer attention and sparse convolution, to output all instance mattes simultaneously without exploding memory and latency. Code and datasets are available at 👉 https://lnkd.in/g5NGetUY. Paper 👉 https://lnkd.in/gRakdity
To view or add a comment, sign in
-
Geek For Geeks Question https://lnkd.in/gZyUqVjP Problem Statement: Given an array arr of size n and an integer X. Find if there's a triplet in the array which sums up to the given integer X. My Solution: Using Hashing: This approach uses extra space. Here we will have 2 loops one outer loop and another inner loop from i + 1. Check if the given remainder is in the dictionary if it is we have our result else we will push the inner loop value into dictionary. class Solution: def find3Numbers(self, A, n, X): numbers = {A[0]: 1} for i in range(1, n): j = i + 1 while j < n: remainder = X - (A[i] + A[j]) if(remainder in numbers and (A[i] != remainder and A[j] != remainder)): return True else: numbers[A[j]] = 1 j += 1 else: return False Time Complexity: O(N2), Space Complexity: O(N) Other Solution: Using the Two Pointers: Initially Sorting the array. Then run 2 loops the outer loop on the list and inner loop will with 2 pointers. Moving the left pointer if sum is less that X and right pointer if sum is greater than X. class Solution: def find3Numbers(self, A, n, X): A.sort() for i in range(0, n): left = i + 1 right = n - 1 while left < right: sum = A[i] + A[left] + A[right] if sum == X: return True else: if sum > X: right -= 1 else: left += 1 else: return False Time Complexity: O(N2), Space Complexity: O(1) #gfgcodechallenge #dsachallenge #algorithms #binarysearch #hashing
Find a triplet that sum to a given value
geeksforgeeks.org
To view or add a comment, sign in
Software Developer Intern at BlockFrame, Inc.
1moInsightful!