Skip to main content

Posts

Showing posts with the label STL

LeetCode Problem #230. Kth Smallest element in Binary Search Tree.

  Problem Statement: Given a binary search tree. Program should return Kth Smallest element in the binary search tree. Suppose if the binary tree is represented as: 3,1,4,null, 2 Then 1st smallest element is 1, second smallest element is 2 and 3rd smallest element is 3.   Solution with Explanation: The binary tree consists of elements in sorted order. The easiest way of finding solution is insert the elements in the priority queue and then  pop out k-1 elements, then top element of the priority queue is the kth smallest element of the tree. Optimized solution is doing in-order traversal and keeping track of the count of number of elements visited.  After visiting the left most element of the binary tree, increase the count to 1 and traverse back in in-order manner and increase the count. Whenever the count is reached to k return that element. Complexity Explanation: As the traversal is in-order, each node is visited only once. The traversal continues till the Kth el...

LeetCode Problem: 739. Daily temperatures.

Problem Statement: Given an array which consists of daily temperatures, find out what is the warmth upcoming day in the list. If there is no such day exist return 0. Suppose the array of temperature is: 60, 70, 80, 77, 73, 79, 81, 75 Answer should be 1, 1, 4, 2, 1, 1, 0, 0. Explanation: Immediate warmth day after 60 is 70 which is next day, so 1. Same for 70 as well. But for 80 next warmth day is 81 which is after 4 days, for 77 it is 79 which is the second day, for 73 it is 79 which is next day. But there is no day in the list where temperature is greater than 81 so insert 0 same for 75 as well. Solution with Explanation: The idea is to use stack data structure to keep track of which we didn't find the warmth temperature in next day. First day temperature is pushed into the stack On second day we check the top value of stack is less than the current day temperature. If yes, then we found the immediate warmth day for the day which is on top of the stack. We pop that and check wheth...

Tree Data Structure related must solve programming questions: Part - 2

Problem Statement: Given a tree return inorder traversal of a binary tree. Note: Solve it using both recursion and iterative approach. Approach - 1(Recursive approach): Recursive approach is very simple. Inorder traversal is traversing left sub tree first Then visiting root and finally visiting right sub tree. Break the recursion whenever there is no node available. Code in C++: class Solution {         void traverse(TreeNode* node, vector<int> &res){             if(!node)                 return;             traverse(node->left, res);                        res.push_back(node->val);           ...

Tree Data Structure related must solve programming questions: Part - 1

LeetCode Problem #687 Given a binary tree find the longest possible path with same node values. The length of the path is determined the number of edges between the node. Example 1: Input: 5 / \ 4 5 / \ \ 1 1 5 Output:  2   Example 2: Input: 1 / \ 4 5 / \ \ 4 4 5 Output:  2 Solution in C++: /**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}  * };  */ class Solution ...

LeetCode Problem #794. Valid Tic-Tac-Toe State

Problem Statement: Validate whether given three set of combination leads to valid Tic-Tac-Toe  pattern or not. Given strings consists of 'x', 'o' or ' '. Assume that game starts from 'x'. So, first players1 puts 'x' in the game then player2 takes the turn and inserts 'o'. The game will continue until one of the players win. Our task is to find out whether given pattern is possible at any point of time of play. Return true if the given pattern is possible else return false. Example 1: Input: ['XXX', '   ', 'OOO'] Output:   false Explanation: The given pattern is not possible because once the player 1 put three X in a row which is in the first row game is over, player 2 doesn't get a chance to put thrid O. So, this pattern is not possible. Example 2: Input: ['XOX', 'OOX ', 'XO '] Output:   true Explanation: The given pattern is possible. Example 3: Input: ['OXX', 'XOX', ...

LeetCode Problem: 1028. Recover a Tree From Preorder Traversal

Problem Statement: Recover binary tree from its given preorder traversal string. The string is given in the format: Dashes followed by value. The number of dashes convey its depth and value refers to the node value. Example 1: Input: string = "1-2--3--4-5--6--7"; Output: [1,2,5,3,4,6,7] Example 2: Input: string = "1-2--3---4-5--6---7"; Output: [1,2,5,3,null, 6, null, 4, null, 7] Example 3: Input: string = "1-401--349---90--88"; Output: [1,401,null,349,88,90]. Approach to the solution: Calculate value and its depth Check if right child is present. If yes then move to right child then go to step 2 again until depth of the node is reached. Else move to left and then go to step 2 again until depth of the node is reached. Once the calculated depth is reached. If left child of the node is null, create a new node and assign left child of the node. Else create a new node and assign it to right child. Continue from step 1 again until end of the string is reached. S...

Leet Code: Problem: 355. Design Twitter

Problem Statement: Design basic twitter which lets user follow and unfollow other users and show the latest new feed related to the current user and the user followers. Implement the following APIs void postTweet(int userId, int tweetId):     Stores the tweetId against the user ID. void follow(int followerId, int followeeId):     Marks that follower ID as following followee ID void unfollow(int followerId, int followeeId):     Marks that follower ID as unfollowing followee ID vector<int> getNewsFeed(int userId):     Returns the set of the latest 10 tweetIDs which include the current user tweetIDs and tweetIDs of the user that the follower if following. Approach to the problem: First we need to store the user IDs of the people a particular user is following To store that we can use map. To optimize things instead of storing list of followers, it is better to store them in a set for quicker access. So the followers data str...

Leet Code: Problem #1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows

Problem Statement: Given an matrix of size m * n which is sorted in rows wise in increasing order. Return the Kth smallest sum of the elements by choosing by atmost 1 element from each row. Example 1: Input: mat = [               [1, 2, 3],               [4, 5, 6],               [7, 8, 9]                ] k = 2; Output: 13 (sum of(2,4,7)) Example 2: Input: mat = [               [1, 2, 3],               [4, 5, 6],               [7, 8, 9]                ] k = 3; Output: 14(sum of (3, 4, 7)) Approach to the solution: Take the first row and initialize to an 1D vector From second row on wards add all possible sums of first row and second ...

STL APIs in C++

Here is the most used of the many functions that STL provides:   sort(first_iterator, last_iterator)           - It sorts the elements in ascending order by default. To sort it in descending order we have to pass comparison function as the third parameter. greater<int>() can be used to achieve that purpose. reverse(first_iterator, last_iterator)          - It reverses the vector *max_element(first_iterator, last_iterator)          - It returns the maximum element of the vector *min_element(first_iterator, last_iterator)          - It returns the minimum element of the vector accumulate(first_iterator, last_iterator, initial sum value)          - It returns the sum of the elements plus the initial sum value count(first_iterator, last_iterator, element)         - It returns the number o...