Skip to main content

Posts

Showing posts from May, 2020

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

Simple ID card building application using flutter

import 'package:flutter/material.dart' ; void main () => runApp( MaterialApp ( home: NinjaCard () , )) ; class NinjaCard extends StatefulWidget { @override _NinjaCardState createState () => _NinjaCardState () ; } class _NinjaCardState extends State<NinjaCard> { int level = 0 ; @override Widget build (BuildContext context) { return Scaffold ( backgroundColor: Colors. grey [ 900 ] , appBar: AppBar ( title: Text ( 'Ninja ID Card' ) , centerTitle: true, backgroundColor: Colors. grey [ 850 ] , elevation: 0.0 , ) , floatingActionButton: FloatingActionButton ( onPressed: (){ setState(() { level += 1 ; }) ; } , child: Icon (Icons. add ) , backgroundColor: Colors. grey [ 500 ] , ) , body: Padding ( padding: EdgeInsets . fromLTRB ( 30.0 , 40 , 40.0 , 0 ) , child: Column ( crossAxisAlignment: Cross...