Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/k-closest-values/1
K closest Values
Difficulty: Medium Accuracy: 85.45%
Given the root of a Binary Search Tree, a target value, and an integer k. Your task is to find the k values in the BST that are closest to the target.
The closest value is taken by choosing the one that gives minimum absolute difference from target.
Note: In case two values have same absolute difference from target, choose the smaller one. The target may or may not be present in BST.
You can return the values in any order the driver code will print them in sorted order only.
Examples:
Input: root = [20, 8, 22, 4, 12, N, N, N, N, 10, 14], target = 17, k = 3
Output: [14, 20, 12]
Explanation: Absolute difference of 17 wrt 14 and 20 is 3 and 3, but we choose the smaller value in case of same absolute difference. So, 14 coes first and then 20. Then, 12 and 22 have same absolute difference, i.e., 5 from 17. But we choose the smaller value, i.e., 12.
Input: root = [5, 4, 8, 1], target = 5, k = 2
Explanation: The absolute difference of 5 wrt 5 is 0, and for 4, the absolute difference is 1.
Constraints:
1 β€ number of nodes, k β€ 104
1 β€ node->data, target β€ 104
Solution:
class Solution:
def getKClosest(self, root, target, k):
arr = []
def inorder(node):
if not node: return
inorder(node.left)
arr.append(node.data)
inorder(node.right)
inorder(root)
arr.sort(key=lambda x: (abs(x - target), x))
return arr[:k]
Top comments (0)