Skip to main content

Day 7: Top K Frequent Elements - leetcode - Python3

 Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.


Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

SOLUTION:

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        count: dict[int, int] = {}
        freq: List[List[int]] = [[] for i in range(len(nums) + 1)]
        result: List[int] = []

        for n in nums:
            count[n] = count.get(n,0) + 1
            # using hashmap to find the frequency
            #of each occurance
        for val, key in count.items():
            freq[key].append(val)
        for i in range(len(freq) -1,0,-1):
            for n in freq[i]:
                result.append(n)
                if len(result)==k:
                    return result

  • Time complexity:
  • O(n), where n is the number of elements in the nums list.

Let's go through the code step by step:

  1. The count dictionary is created to store the frequencies of each element in the nums list.

  2. The freq list is initialized as an empty list with a length of len(nums) + 1. This list will be used to store the elements grouped by their frequencies.

  3. A loop is used to iterate over each element n in the nums list.

  4. Inside the loop, the frequency of each element is calculated and stored in the count dictionary. The count.get(n, 0) retrieves the current frequency of the element n and increments it by 1. If the element is not present in the dictionary, it defaults to 0 and adds 1 to it.

  5. Another loop iterates over the key-value pairs in the count dictionary.

  6. Inside this loop, the element val and its frequency key are retrieved.

  7. The element val is appended to the freq list at the index corresponding to its frequency key. This means that elements with the same frequency will be grouped together in the freq list.

  8. After populating the freq list, another loop is used to iterate over the elements in reverse order, starting from the last index.

  9. Inside this loop, another nested loop iterates over the elements n in the freq[i] list, where i represents the frequency.

  10. Each element n is appended to the result list, which stores the k most frequent elements.

  11. After appending an element to the result list, the length of the result list is checked. If it equals k, the desired number of elements has been added, and the result list is returned as the final output.

  12. If the loop completes without returning the result, it means that there are fewer than k distinct elements in the input list, and the function will return the result list containing the available distinct elements.


Comments

Popular posts from this blog

Bug Boundy Methodology, Tools & Resources

Start by defining a clear objective, such as exploiting a remote code execution (RCE) vulnerability or bypassing authentication on your target. Then, consider how you can achieve this goal using various attack vectors like XSS, SSRF, or others - these are simply tools to help you reach your objective. Use the target as how a normal user would, while browsing keep these questions in mind: 1)How does the app pass data? 2)How/where does the app talk about users? 3)Does the app have multi-tenancy or user levels? 4)Does the app have a unique threat model? 5)Has there been past security research & vulnerabilities? 6)How does the app handle XSS, CSRF, and code injection?

Install & set up mitmweb or mitmproxy in Linux

Step 1: Go to the mitmproxy page and download the binaries. Step 2: Install the downloaded tar file with the command " tar -xzf <filename>.tar.gz " Step 3: In the FoxyProxy add the proxy 127.0.0.1:8080  and turn it on. Step 4 : In the terminal run command " ./mitmweb " Step 5: Go to the page  http://mitm.it/   and download the mitmproxy's Certificate. Step 6: If you downloaded the certificate for Firefox, then go to " settings -> Privacy & Security -> Click View Certificates -> Click  Import ", then import the certificate.  Step 7: Now you are ready to capture the web traffic. Step 8 : In terminal run " ./mitmweb"

pip error in Kali Linux: error: externally-managed-environment : SOLVED

 error: externally-managed-environment × This environment is externally managed ╰─> To install Python packages system-wide, try apt install     python3-xyz, where xyz is the package you are trying to     install.     If you wish to install a non-Kali-packaged Python package,     create a virtual environment using python3 -m venv path/to/venv.     Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make     sure you have pypy3-venv installed.     If you wish to install a non-Kali-packaged Python application,     it may be easiest to use pipx install xyz, which will manage a     virtual environment for you. Make sure you have pipx installed.     For more information, refer to the following:     * https://www.kali.org/docs/general-use/python3-external-packages/     * /usr/share/doc/python3.12/README.venv note: If you believe this is a mistake, please contac...