Skip to main content

Posts

Showing posts from 2020

LeetCode problem #124. Binary tree Maximum path sum.

Problem Statement:     Given a tree, task is to find out the path with maximum sum of the elements along the path.  The path can be anywhere in the tree and need not go along the root and the nodes shouldn't be skipped in the path. Example 1: Input: [1,2,3] 1 / \ 2 3 Output: 6 Example 2: Input: [-10,9,20,null,null,15,7]   -10    / \   9   20     /  \     15   7 Output: 42  Approach to the solution:   Approach here is simple, first traverse the tree in post order manner. Keep track of maximum values of left and right. Keep track of maximum values of left side and right side. Compare and keep track of maximum values between maximum side max and sub tree. Keep track of global maximum sum of the path in one variable Compare global maximum sum with the sum which got from the above process. Return that maximum sum. This maximum sum is the maximum path of the sum ...

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...

LeetCode: Problem #1402. Reducing Dishes

Problem Statement: A chef has collected the data on the review for his dishes. Our Chef will take just 1 unit of time to prepare a dish. Our job is to tell him the dishes he has to make in the order to achieve maximum benefit. The maximum benefit is calculated using the formula time[i] * (review ratings). Example 1: Input: reviews = [-1, -10, -9, 0, 5] Output: 14 Explanation: Considering the dishes in the order of -1, 0 ,5 the calculation will be (-1 * 1 + 0 * 2 + 5 * 3) = 14 Example 2: Input: reviews = [6,5,4] Output: 32 Explanation: Considering the dishes in the order of 4, 5, 6 the calculation will be (4 * 1 + 5 * 2 + 6 * 3) = 32 Approach to the solution: Sort the given reviews so that we can concentrate only on maximum benefited reviews. Make cumulative sums from the end. This will help in deciding till which we have to consider the summation. Now start from the end at add the previous array of cumulative sums until a negative number is encountered. We have to iterate in reverse or...

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 ...

Heap(priority queue) data structure

Heap is a data structure which is constructed based on the complete binary tree. A complete binary tree is a tree with all the nodes except leaf nodes are completely filled and all the nodes are left aligned. There are two types of heaps: 1)Max-Heap 2)Min-Heap 1)Max-Heap: Max heap is a data structure where the node has a value greater than all of its children. 2)Min-Heap Min heap is a data structure where the node has a minimum value compare to all of its children. In C++ STL there is a priority queue in the container which is the implementation of heap. It provides APIs for the heap data structure. Following are the APIs provided by C++ STL priority_queue : empty(): This function returns true if the priority queue is empty and false if the queue is not empty. Ex: priority_queue<int> pq;     pq.empty(); size(): This function returns the size of the priority queue. Here size means number of elements the priority queue is holding. If it is holding 10 elements it retur...

Leet Code: Problem #84 Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.   Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3] .   The largest rectangle is shown in the shaded area, which has area = 10 unit.   Example: Input: [2,1,5,6,2,3] Output: 10 Solution in C++:

Leet Code: Problem #124 Binary Tree Maximum Path Sum

Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Example 1: Input: [1,2,3] 1 / \ 2 3 Output: 6 Example 2: Input: [-10,9,20,null,null,15,7]   -10    / \   9   20     /  \     15   7 Output: 42 Solution in C++:

Leet Code: Problem #1363 Largest Multiple of Three

Given an integer array of digits , return the largest multiple of three that can be formed by concatenating some of the given digits in any order. Since the answer may not fit in an integer data type, return the answer as a string. If there is no answer return an empty string.   Example 1: Input: digits = [8,1,9] Output: "981" Example 2: Input: digits = [8,6,7,1,0] Output: "8760" Example 3: Input: digits = [1] Output: "" Example 4: Input: digits = [0,0,0,0,0,0] Output: "0"   Constraints: 1 <= digits.length <= 10^4 0 <= digits[i] <= 9 The returning answer must not contain unnecessary leading zeros. Solution in C++:

Leet Code: Problem #710 Random Pick with Blacklist

Given a blacklist  B containing unique integers from [0, N) , write a function to return a uniform random integer from [0, N) which is NOT  in B . Optimize it such that it minimizes the call to system’s Math.random() . Note: 1 <= N <= 1000000000 0 <= B.length < min(100000, N) [0, N)  does NOT include N. See interval notation . Example 1: Input: ["Solution","pick","pick","pick"] [[1,[]],[],[],[]] Output: [null,0,0,0] Example 2: Input: ["Solution","pick","pick","pick"] [[2,[]],[],[],[]] Output: [null,1,1,1] Example 3: Input: ["Solution","pick","pick","pick"] [[3,[1]],[],[],[]] Output: [null,0,0,2] Example 4: Input: ["Solution","pick","pick","pick"] [[4,[2]],[],[],[]] Output: [null,1,3,1] Explanation of Input Syntax: The input is two lists: the subroutines called and their argume...

C++ OOPS Concepts & Interview questions:

Is virtual constructor possible:     Virtual constructor is not possible. Virtual has to be used when we don't know the exact type of object and only reference is there to call it. But while creating object we need exact type to create that's why virtual constructor is not possible. #include <iostream> using namespace std; class Base{     virtual Base(){         cout<<"virtual constructor"<<endl;     }    }; class Derived : public Base{     Derived(){         cout<<"Derived constructor"<<endl;     }    }; int main() {     Derived d; } How to Stop from creating Objects of a class: In order to restrict users from creating objects of a class define the constructor as private of the class. As the object cannot call private functions of the class. It restricts the object crea...

Leet Code Problem #41 First missing positive

Given an unsorted integer array, find the smallest missing positive integer. Input: [1,2,4,5] Output: 3 Input: [0,-1,-2,1,5,2]; Output: 3 Input: [0,-1,-2]; Output: 1   Approach to solve the problem: First iterate over the array and identify all the negative elements including zero. Where ever you find zero or negative element replace its value with size of array * 2. Now iterate over the array one more time and mark the value at index. As current iterator as negative of it, If its iterator value is less than size of the  array. Ex: if the array if [1, 4, 6, -1, -3], size of the array is 5. After first iteration it will be [1, 4, 6, 10, 10] (after marking the negative and zero values with double the size of the array). Next follow step 3, arr[0] = 1 (subract -1 as array index starts from zero)which is less than size of array so, => arr[arr[0]] = - arr[arr[0]]. Next arr[2] = 4 which is less than size of array, so index will be 4 - 1 = 3, so arr[3] = - arr[3] Next va...

Simple quotes list App using Flutter

import 'package:flutter/cupertino.dart' ; import 'package:flutter/material.dart' ; import 'quotes.dart' ; void main () => runApp( MaterialApp ( home: QuoteList () )) ; class QuoteList extends StatefulWidget { @override _QuoteListState createState () => _QuoteListState () ; } class _QuoteListState extends State<QuoteList> { List<Quote> quotes = [ Quote ( 'Live your life' , 'CNU' ) , Quote ( 'Do what you love' , 'SREENIVAS' ) , Quote ( 'Never Settle' , 'REDDY' ) ] ; Widget quoteTemplate (quote){ return Card ( margin: EdgeInsets . fromLTRB ( 16 , 16 , 16 , 0 ) , child: Padding ( padding: const EdgeInsets . all ( 12.0 ) , child: Column ( crossAxisAlignment: CrossAxisAlignment. stretch , children: <Widget>[ Text ( quote.text , style: TextStyle ( fontSize: 20 , ...