Posts

Sliding Window Technique - Part 13

Image
Solution here is a simple sliding window approach, the caveat is to cache the mapping number -> list of unique factors which you can use across test cases. Reasonably fast prime factorization is important too, mine isn't the most optimal but fast enough to pass all test cases. Code is down below, cheers, ACC. Longest Subarray With at Most K Distinct Prime Factors - LeetCode You are given an integer array nums consisting of positive integers and an integer k . The prime factor set of a subarray is the union of the distinct prime factors of all its elements. Return the length of the longest subarray whose prime factor set contains at most k distinct prime factors. If no such subarray exists, return 0.   Example 1: Input: nums = [7,6,10,12,11], k = 3 Output: 3 Explanation: Consider the subarray [6, 10, 12] : The distinct prime factors of 6 are {2, 3} . The distinct prime factors of 10 are {2, 5} . The distinct prime factors of 12 are {2, 3} . The union of these sets is {2...

Depth-First Search (DFS) II

Image
Another problem whose a solution can be accomplished via Depth-First Search (DFS). Map the tree to a hash table. Calculate the height of the tree separately (also a DFS). Then perform a DFS to calculate the weighted sum. Code is down below, cheers, ACC. Weighted Sum of a Tree - LeetCode You are given an integer array parent of length n representing a rooted tree with nodes labeled from 0 to n - 1 . The tree is rooted at node 0, so parent[0] = -1 . For each node i where 1 <= i <= n - 1 , parent[i] denotes the parent of node i . You are also given an integer array nums of length n , where nums[i] denotes the value of node i . The weight of a node i at depth d is nums[i] * (h - d + 1) , where h is the height of the tree. Return the sum of the weights of all nodes in the tree. The depth of a node is the number of nodes on the path from the root to that node, inclusive, with the root having depth 1. The height of the tree is the maximum depth among all nodes in the tree. ...