Showing posts with label Python Programming. Show all posts
Showing posts with label Python Programming. Show all posts

December 17, 2021

Most Frequent Subtree Sum

Problem Statement: Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.

The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).


Example 1:

Input: root = [5,2,-3]
Output: [2,-3,4]

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -105 <= Node.val <= 105


Leetcode Difficulty: Medium

Code:
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution(object):
    
    def __init__(self):
        self.subtree_sums = {}
        self.max_freq=-1
        
    def get_max_subtree_sum(self, root):
        if root==None: 
            return 0
        
        leftsum = self.get_max_subtree_sum(root.left)
        rightsum = self.get_max_subtree_sum(root.right)
        currval = root.val
        
        summation = currval + rightsum + leftsum
        self.subtree_sums[summation] = self.subtree_sums.get(summation, 0)+1
        self.max_freq = max(self.max_freq, self.subtree_sums[summation])
        return summation
        
    def findFrequentTreeSum(self, root):
        self.get_max_subtree_sum(root)
        result=[]
        for k,v in self.subtree_sums.items():
            if v==self.max_freq:
                result.append(k)
        return result

Thought Process / Explanation:
We know that sum of the subtree rooted at a certain node is left sum + right sum + curr val. We need to store the sum with it's count and later return only max frequency sum -- for this keeping a dictionary sounds good and also maintaining global max_freq counter for comparison.



Thank You!

Top K Frequent Words

Problem Statement: Given an array of strings words and an integer k, return the k most frequent stringsReturn the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.


Example 1:

Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.

Constraints:

  • 1 <= words.length <= 500
  • 1 <= words[i] <= 10
  • words[i] consists of lowercase English letters.
  • k is in the range [1, The number of unique words[i]]


Leetcode Difficulty: Medium

Asked in: Facebook Amazon ,Apple  Netflix Google

Code:
    def topKfrequent(self, words, k):
        """
        words: List[str]
        k: int
        return: List[str]
        """
        counter={}
        for i in words:
            if i in counter:
                counter[i]+=1
            else:
                counter[i]=1
    
        heap=[]
        for key,value in counter.items():
            heapq.heappush(heap, (-1*value, key))
    
        return [heapq.heappop(heap)[1] for word in range(k)]

Thought Process / Explanation:
Heapq uses a priority queue to implement heaps. So by default, we will get lexicographically sorted strings. Now the task is to main freq and word pair in a heap where the top is max-freq.



Thank You!

K Closest Points to Origin

Problem Statement: Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).

The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).

You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).


Example 1:

Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].


Constraints:

  • 1 <= k <= points.length <= 104
  • -104 < xi, yi < 104


Leetcode Difficulty: Medium

Code:
    def get_distance(self, point):
        origin=[0,0]
        return ((point[1]-origin[1])**2 + (point[0]-origin[0])**2)**0.5
    
    def kclosest(self, points, k):
        """
        points: List[List[int]]
        k: int
        return: List[List[int]]
        """
        
        heap=[]
        for point in points[:k]:
            distance = self.get_distance(point)
            heapq.heappush(heap, (-1*distance,point))
        
        for point in points[k:]:
            distance = -1*self.get_distance(point)
            
            top = heapq.heappop(heap)
            
            if top[0]<distance:
                heapq.heappush(heap, (distance,point))
            else:
                heapq.heappush(heap, top)
        
        return [heapq.heappop(heap)[1] for _ in range(k)]

Thought Process / Explanation:
The keyword "k closest" hints me to give a shot to heaps. Since heapq implements min-heap by default. We multiply the distance by -1 to make sure the absolute largest is on top every time (acting as max-heap). The rest is just a comparison from the top and updating things.



Thank You!