There are n gas stations along a circular tour, where the amount of gas at the ith gas station is gas[i]. You have a car with a gas tank of unlimited capacity and it costs cost[i] of gas to travel from the ith station to its next station. You begin the journey with an empty tank at one of the gas station.
Given two integer arrays gas[] and cost[], the task is to return the starting gas station's index if you want to travel around the circular tour once in the clockwise direction, otherwise return -1.
Note: If a solution exists, it is guaranteed to be unique.
Examples:
Input: gas[] = [4, 5, 7, 4], cost[] = [6, 6, 3, 5]
Output: 2
Explanation: Start at gas station at index 2 and fill up with 7 units of gas. Your tank = 0 + 7 = 7
- Travel to station 3. Available gas = (7 - 3 + 4) = 8.
- Travel to station 0. Available gas = (8 - 5 + 4) = 7.
- Travel to station 1. Available gas = (7 - 6 + 5) = 6.
- Return to station 2. Available gas = (6 - 6) = 0.
Therefore, return 2 as the starting index.
Input: gas[] = [1, 2 ,3 ,4, 5], cost[] = [3, 4, 5, 1, 2]
Output: 3
Explanation: Start at gas station 3 (index 3) and fill up with 4 units of gas. Your tank = 0 + 4 = 4
- Travel to station 4. Available gas = 4 - 1 + 5 = 8
- Travel to station 0. Available gas = 8 - 2 + 1 = 7
- Travel to station 1. Available gas= 7 - 3 + 2 = 6
- Travel to station 2. Available gas = 6 - 4 + 3 = 5
- Travel to station 3. The cost is 5. The gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
Input: arr[] = [3, 9], cost[] = [7, 6]
Output: -1
Explanation: There is no gas station to start with such that you can complete the tour.
[Naive Approach] Considering Every Index as Starting Point - O(n^2) Time and O(1) Space
The simplest approach is to consider each index as a starting point and check if a car can complete the circular tour starting from that index. If we find a valid starting point, we will return it.
C++ // C++ program to find starting index of circular Tour // by considering each index as starting point. #include <iostream> #include <vector> using namespace std; int startStation(vector<int> &gas, vector<int> &cost) { int n = gas.size(); int startIdx = -1; for(int i = 0; i < n; i++) { // Initially car tank is empty int currGas = 0; bool flag = true; for (int j = 0; j < n; j++){ // Circular Index int idx = (i + j) % n; currGas = currGas + gas[idx] - cost[idx]; // If currGas is less than zero, then it isn't // possible to proceed further with this starting point if(currGas < 0) { flag = false; break; } } // If flag is true, then we have found // the valid starting point if(flag) { startIdx = i; break; } } return startIdx; } int main() { vector<int> gas = {1, 2, 3, 4, 5}; vector<int> cost = {3, 4, 5, 1, 2}; cout << startStation(gas, cost) << endl; return 0; }
C // C program to find starting index of circular Tour // by considering each index as starting point. #include <stdio.h> int startStation(int gas[], int cost[], int n) { int startIdx = -1; for (int i = 0; i < n; i++) { // Current Available gas int currGas = 0; int flag = 1; for (int j = 0; j < n; j++) { // Circular Index int idx = (i + j) % n; currGas = currGas + gas[idx] - cost[idx]; // If Available gas is less than zero, then it isn't // possible to proceed further with this starting point if (currGas < 0) { flag = 0; break; } } // If flag is true, then we have found // the valid starting point if (flag) { startIdx = i; break; } } return startIdx; } int main() { int gas[] = {1, 2, 3, 4, 5}; int cost[] = {3, 4, 5, 1, 2}; int n = sizeof(gas) / sizeof(gas[0]); printf("%d\n", startStation(gas, cost, n)); return 0; }
Java // Java program to find starting index of circular Tour // by considering each index as starting point. import java.util.*; class GfG { static int startStation(int[] gas, int[] cost) { int n = gas.length; int startIdx = -1; for (int i = 0; i < n; i++) { // Current Available gas int currGas = 0; boolean flag = true; for (int j = 0; j < n; j++) { // Circular Index int idx = (i + j) % n; currGas = currGas + gas[idx] - cost[idx]; // If Available gas is less than zero, then it isn't // possible to proceed further with this starting point if (currGas < 0) { flag = false; break; } } // If flag is true, then we have found // the valid starting point if (flag) { startIdx = i; break; } } return startIdx; } public static void main(String[] args) { int[] gas = {1, 2, 3, 4, 5}; int[] cost = {3, 4, 5, 1, 2}; System.out.println(startStation(gas, cost)); } }
Python # Python program to find starting index of circular Tour # by considering each index as starting point. def startStation(gas, cost): n = len(gas) startIdx = -1 for i in range(n): # Current Available gas currGas = 0 flag = True for j in range(n): # Circular Index idx = (i + j) % n currGas += gas[idx] - cost[idx] # If Available gas is less than zero, then it isn't # possible to proceed further with this starting point if currGas < 0: flag = False break # If flag is true, then we have found # the valid starting point if flag: startIdx = i break return startIdx if __name__ == "__main__": gas = [1, 2, 3, 4, 5] cost = [3, 4, 5, 1, 2] print(startStation(gas, cost))
C# // C# program to find starting index of circular Tour // by considering each index as starting point. using System; class GfG { static int startStation(int[] gas, int[] cost) { int n = gas.Length; int startIdx = -1; for (int i = 0; i < n; i++) { // Current Available gas int currGas = 0; bool flag = true; for (int j = 0; j < n; j++) { // Circular Index int idx = (i + j) % n; currGas = currGas + gas[idx] - cost[idx]; // If Available gas is less than zero, then it isn't // possible to proceed further with this starting point if (currGas < 0) { flag = false; break; } } // If flag is true, then we have found // the valid starting point if (flag) { startIdx = i; break; } } return startIdx; } static void Main() { int[] gas = { 1, 2, 3, 4, 5 }; int[] cost = { 3, 4, 5, 1, 2 }; Console.WriteLine(startStation(gas, cost)); } }
JavaScript // JavaScript program to find starting index of circular Tour // by considering each index as starting point. function startStation(gas, cost) { let n = gas.length; let startIdx = -1; for (let i = 0; i < n; i++) { // Current Available gas let currGas = 0; let flag = true; for (let j = 0; j < n; j++) { // Circular Index let idx = (i + j) % n; currGas += gas[idx] - cost[idx]; // If Available gas is less than zero, then it isn't // possible to proceed further with this starting point if (currGas < 0) { flag = false; break; } } // If flag is true, then we have found // the valid starting point if (flag) { startIdx = i; break; } } return startIdx; } // Driver Code let gas = [1, 2, 3, 4, 5]; let cost = [3, 4, 5, 1, 2]; console.log(startStation(gas, cost));
[Expected Approach 1] Greedy Approach - O(n) Time and O(1) Space
We start by assuming the 0th index as the starting point for the circular tour. As we traverse the array, we calculate the available gas at each gas station, which is the previously available gas + gas[i] - cost[i]. If, at any station i
, the available gas drops below zero, it indicates that a car cannot proceed to the next station (i + 1) from the current starting point. In such a case, we update the starting point to i + 1 and continue the process. After completing the traversal of the array, we check whether the starting point is valid for the circular tour.
If a car starts at gas station A and cannot reach gas station B, then any gas station located between A and B cannot help us reach B either. But why?
If we start at A and are unable to reach B, but we can reach all the stations up to B-1. Let's assume a gas station C (C<=B-1) located between station A and B. When we arrive at C from A, we must have had a positive amount of gas in our tank. Therefore, if we can't reach B starting with positive amount of gas at C, it would be impossible to reach B from C with a zero amount of gas.
C++ // C++ program to find starting index of circular Tour // using greedy approach #include <iostream> #include <vector> using namespace std; int startStation(vector<int> &gas, vector<int> &cost) { int n = gas.size(); int startIdx = 0; // Initially car tank is empty int currGas = 0; for(int i = 0; i < n; i++) { currGas = currGas + gas[i] - cost[i]; // If currGas becomes less than zero, then // It's not possible to proceed with this startIdx if(currGas < 0) { startIdx = i + 1; currGas = 0; } } // Checking if startIdx can be a valid // starting point for the Circular tour currGas = 0; for(int i = 0; i < n; i++) { // Circular Index int idx = (i + startIdx) % n; currGas = currGas + gas[idx] - cost[idx]; if(currGas < 0) return -1; } return startIdx; } int main() { vector<int> gas = {1, 2, 3, 4, 5}; vector<int> cost = {3, 4, 5, 1, 2}; cout << startStation(gas, cost) << endl; return 0; }
C // C program to find starting index of circular Tour // using greedy approach #include <stdio.h> int startStation(int gas[], int cost[], int n) { int startIdx = 0; // Initially car tank is empty int currGas = 0; for (int i = 0; i < n; i++) { currGas = currGas + gas[i] - cost[i]; // If currGas becomes less than zero, then // It's not possible to proceed with this startIdx if (currGas < 0) { startIdx = i + 1; currGas = 0; } } // Checking if startIdx can be a valid // starting point for the Circular tour. currGas = 0; for (int i = 0; i < n; i++) { // Circular Index int idx = (i + startIdx) % n; currGas = currGas + gas[idx] - cost[idx]; if (currGas < 0) return -1; } return startIdx; } int main() { int gas[] = {1, 2, 3, 4, 5}; int cost[] = {3, 4, 5, 1, 2}; int n = sizeof(gas) / sizeof(gas[0]); printf("%d\n", startStation(gas, cost, n)); return 0; }
Java // Java program to find starting index of circular Tour // using greedy approach import java.util.*; class GfG { static int startStation(int[] gas, int[] cost) { int n = gas.length; int startIdx = 0; // Initially car tank is empty int currGas = 0; for (int i = 0; i < n; i++) { currGas = currGas + gas[i] - cost[i]; // If currGas becomes less than zero, then // It's not possible to proceed with this startIdx if (currGas < 0) { startIdx = i + 1; currGas = 0; } } // Checking if startIdx can be a valid // starting point for the Circular tour currGas = 0; for (int i = 0; i < n; i++) { // Circular Index int idx = (i + startIdx) % n; currGas = currGas + gas[idx] - cost[idx]; if (currGas < 0) return -1; } return startIdx; } public static void main(String[] args) { int[] gas = {1, 2, 3, 4, 5}; int[] cost = {3, 4, 5, 1, 2}; System.out.println(startStation(gas, cost)); } }
Python # Python program to find starting index of circular Tour # using greedy approach def startStation(gas, cost): n = len(gas) startIdx = 0 # Initially car tank is empty currGas = 0 for i in range(n): currGas = currGas + gas[i] - cost[i] # If currGas becomes less than zero, then # It's not possible to proceed with this startIdx if currGas < 0: startIdx = i + 1 currGas = 0 # Checking if startIdx can be a valid # starting point for the Circular tour currGas = 0 for i in range(n): # Circular Index idx = (i + startIdx) % n currGas = currGas + gas[idx] - cost[idx] if currGas < 0: return -1 return startIdx if __name__ == "__main__": gas = [1, 2, 3, 4, 5] cost = [3, 4, 5, 1, 2] print(startStation(gas, cost))
C# // C# program to find starting index of a circular Tour // using greedy approach using System; class GfG { static int startStation(int[] gas, int[] cost) { int n = gas.Length; int startIdx = 0; // Initially car tank is empty int currGas = 0; for (int i = 0; i < n; i++) { currGas = currGas + gas[i] - cost[i]; // If currGas becomes less than zero, then // It's not possible to proceed with this startIdx if (currGas < 0) { startIdx = i + 1; currGas = 0; } } // Check if startIdx can be a valid // starting point for the Circular tour currGas = 0; for (int i = 0; i < n; i++) { // Circular Index int idx = (i + startIdx) % n; currGas = currGas + gas[idx] - cost[idx]; if (currGas < 0) return -1; } return startIdx; } static void Main() { int[] gas = { 1, 2, 3, 4, 5 }; int[] cost = { 3, 4, 5, 1, 2 }; Console.WriteLine(startStation(gas, cost)); } }
JavaScript // JavaScript program to find starting index of circular Tour // using greedy approach function startStation(gas, cost) { let n = gas.length; let startIdx = 0; // Initially car tank is empty let currGas = 0; for (let i = 0; i < n; i++) { currGas = currGas + gas[i] - cost[i]; // If currGas becomes less than zero, then // It's not possible to proceed with this startIdx if (currGas < 0) { startIdx = i + 1; currGas = 0; } } // Checking if startIdx can be a valid // starting point for the Circular tour currGas = 0; for (let i = 0; i < n; i++) { // Circular Index let idx = (i + startIdx) % n; currGas = currGas + gas[idx] - cost[idx]; if (currGas < 0) return -1; } return startIdx; } // driver code let gas = [1, 2, 3, 4, 5]; let cost = [3, 4, 5, 1, 2]; console.log(startStation(gas, cost));
[Expected Approach 2] Greedy Approach in One Pass - O(n) Time and O(1) Space
This approach is optimization for the previous one. After completing the entire traversal of the array, instead of checking the validity by circularly traversing from the starting index, we calculate the total gas remaining (net gas and the cost difference). If the difference is greater than or equal to zero, then it's obvious that the starting point is valid; otherwise, it is not possible to complete a circular loop.
C++ // C++ program to find starting index of circular Tour // using greedy approach in one pass #include <iostream> #include <vector> using namespace std; int startStation(vector<int> &gas, vector<int> &cost) { int n = gas.size(); // Variables to track total and current remaining gas int totalGas = 0; int currGas = 0; int startIdx = 0; // Traverse through each station to calculate remaining // gas in the tank, and total gas for(int i = 0; i < n; i++) { currGas += gas[i] - cost[i]; totalGas += gas[i] - cost[i]; // If currGas is negative, circular tour can't // start with this index, so update it to next one if(currGas < 0) { currGas = 0; startIdx = i + 1; } } // No solution exist if(totalGas < 0) return -1; return startIdx; } int main() { vector<int> gas = {1, 2, 3, 4, 5}; vector<int> cost = {3, 4, 5, 1, 2}; cout << startStation(gas, cost); return 0; }
C // C program to find starting index of circular Tour // using greedy approach in one pass #include <stdio.h> int startStation(int gas[], int cost[], int n) { // Variables to track total and current remaining gas int totalGas = 0; int currGas = 0; int startIdx = 0; // Traverse through each station to calculate remaining // gas in the tank, and total gas for (int i = 0; i < n; i++) { currGas += gas[i] - cost[i]; totalGas += gas[i] - cost[i]; // If currGas is negative, circular tour can't // start with this index, so update it to next one if (currGas < 0) { currGas = 0; startIdx = i + 1; } } // No solution exists if (totalGas < 0) return -1; return startIdx; } int main() { int gas[] = {1, 2, 3, 4, 5}; int cost[] = {3, 4, 5, 1, 2}; int n = sizeof(gas) / sizeof(gas[0]); printf("%d\n", startStation(gas, cost, n)); return 0; }
Java // Java program to find starting index of circular Tour // using greedy approach in one pass class GfG { static int startStation(int[] gas, int[] cost) { int n = gas.length; // Variables to track total and current remaining gas int totalGas = 0; int currGas = 0; int startIdx = 0; // Traverse through each station to calculate remaining // gas in the tank, and total gas for (int i = 0; i < n; i++) { currGas += gas[i] - cost[i]; totalGas += gas[i] - cost[i]; // If currGas is negative, circular tour can't // start with this index, so update it to next one if (currGas < 0) { currGas = 0; startIdx = i + 1; } } // No solution exists if (totalGas < 0) return -1; return startIdx; } public static void main(String[] args) { int[] gas = { 1, 2, 3, 4, 5 }; int[] cost = { 3, 4, 5, 1, 2 }; System.out.println(startStation(gas, cost)); } }
Python # Python program to find starting index of circular Tour # using greedy approach in one pass def startStation(gas, cost): n = len(gas) # Variables to track total and current remaining gas totalGas = 0 currGas = 0 startIdx = 0 # Traverse through each station to calculate remaining # gas in the tank, and total gas for i in range(n): currGas += gas[i] - cost[i] totalGas += gas[i] - cost[i] # If currGas is negative, circular tour can't # start with this index, so update it to next one if currGas < 0: currGas = 0 startIdx = i + 1 # No solution exists if totalGas < 0: return -1 return startIdx if __name__ == "__main__": gas = [1, 2, 3, 4, 5] cost = [3, 4, 5, 1, 2] print(startStation(gas, cost))
C# // C# program to find starting index of circular Tour // using greedy approach in one pass using System; class GfG { static int startStation(int[] gas, int[] cost) { int n = gas.Length; // Variables to track total and current remaining gas int totalGas = 0; int currGas = 0; int startIdx = 0; // Traverse through each station to calculate remaining // gas in the tank, and total gas for (int i = 0; i < n; i++) { currGas += gas[i] - cost[i]; totalGas += gas[i] - cost[i]; // If currGas is negative, circular tour can't // start with this index, so update it to next one if (currGas < 0) { currGas = 0; startIdx = i + 1; } } // No solution exists if (totalGas < 0) return -1; return startIdx; } static void Main() { int[] gas = { 1, 2, 3, 4, 5 }; int[] cost = { 3, 4, 5, 1, 2 }; Console.WriteLine(startStation(gas, cost)); } }
JavaScript // JavaScript program to find starting index of circular Tour // using greedy approach in one pass function startStation(gas, cost) { const n = gas.length; // Variables to track total and current remaining gas let totalGas = 0; let currGas = 0; let startIdx = 0; // Traverse through each station to calculate remaining // gas in the tank, and total gas for (let i = 0; i < n; i++) { currGas += gas[i] - cost[i]; totalGas += gas[i] - cost[i]; // If currGas is negative, circular tour can't // start with this index, so update it to next one if (currGas < 0) { currGas = 0; startIdx = i + 1; } } // No solution exists if (totalGas < 0) return -1; return startIdx; } // Driver Code const gas = [1, 2, 3, 4, 5]; const cost = [3, 4, 5, 1, 2]; console.log(startStation(gas, cost));
Similar Reads
Queue Data Structure A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Introduction to Queue Data Structure Queue is a linear data structure that follows FIFO (First In First Out) Principle, so the first element inserted is the first to be popped out. FIFO Principle in Queue:FIFO Principle states that the first element added to the Queue will be the first one to be removed or processed. So, Queue is like
5 min read
Introduction and Array Implementation of Queue Similar to Stack, Queue is a linear data structure that follows a particular order in which the operations are performed for storing data. The order is First In First Out (FIFO). One can imagine a queue as a line of people waiting to receive something in sequential order which starts from the beginn
2 min read
Queue - Linked List Implementation In this article, the Linked List implementation of the queue data structure is discussed and implemented. Print '-1' if the queue is empty.Approach: To solve the problem follow the below idea:we maintain two pointers, front and rear. The front points to the first item of the queue and rear points to
8 min read
Applications, Advantages and Disadvantages of Queue A Queue is a linear data structure. This data structure follows a particular order in which the operations are performed. The order is First In First Out (FIFO). It means that the element that is inserted first in the queue will come out first and the element that is inserted last will come out last
5 min read
Different Types of Queues and its Applications Introduction : A Queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. In this article, the diff
8 min read
Queue implementation in different languages
Queue in C++ STLIn C++, queue container follows the FIFO (First In First Out) order of insertion and deletion. According to it, the elements that are inserted first should be removed first. This is possible by inserting elements at one end (called back) and deleting them from the other end (called front) of the dat
4 min read
Queue Interface In JavaThe Queue Interface is a part of java.util package and extends the Collection interface. It stores and processes the data in order means elements are inserted at the end and removed from the front. Key Features:Most implementations, like PriorityQueue, do not allow null elements.Implementation Class
12 min read
Queue in PythonLike a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. Operations
6 min read
C# Queue with ExamplesA Queue in C# is a collection that follows the First-In-First-Out (FIFO) principle which means elements are processed in the same order they are added. It is a part of the System.Collections namespace for non-generic queues and System.Collections.Generic namespace for generic queues.Key Features:FIF
6 min read
Implementation of Queue in JavascriptA Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Elements are inserted at the rear and removed from the front.Queue Operationsenqueue(item) - Adds an element to the end of the queue.dequeue() - Removes and returns the first element from the queue.peek() - Ret
7 min read
Queue in Go LanguageA queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). Now if you are familiar with other programming languages like C++, Java, and Python then there are inbuilt queue libraries that can be used for the implementat
4 min read
Queue in ScalaA queue is a first-in, first-out (FIFO) data structure. Scala offers both an immutable queue and a mutable queue. A mutable queue can be updated or extended in place. It means one can change, add, or remove elements of a queue as a side effect. Immutable queue, by contrast, never change. In Scala, Q
3 min read
Some question related to Queue implementation
Easy problems on Queue
Detect cycle in an undirected graph using BFSGiven an undirected graph, the task is to determine if cycle is present in it or not.Examples:Input: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]]Undirected Graph with 5 NodeOutput: trueExplanation: The diagram clearly shows a cycle 0 â 2 â 1 â 0.Input: V = 4, edges[][] = [[0, 1], [1,
6 min read
Breadth First Search or BFS for a GraphGiven a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Traversing directory in Java using BFSGiven a directory, print all files and folders present in directory tree rooted with given directory. We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from qu
2 min read
Vertical Traversal of a Binary TreeGiven a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. If multiple nodes pass through a vertical line, they should be printed as they appear in the level order traversal of the tree.Examples: Input:Output: [[4], [2], [1, 5, 6], [3, 8]
10 min read
Print Right View of a Binary TreeGiven a Binary Tree, the task is to print the Right view of it. The right view of a Binary Tree is a set of rightmost nodes for every level.Examples: Example 1: The Green colored nodes (1, 3, 5) represents the Right view in the below Binary tree. Example 2: The Green colored nodes (1, 3, 4, 5) repre
15+ min read
Find Minimum Depth of a Binary TreeGiven a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi
15 min read
Check whether a given graph is Bipartite or notGiven a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not.Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex i
8 min read
Intermediate problems on Queue
Flatten a multilevel linked list using level order traversalGiven a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own to produce a multilevel linked list. Given the head of the first level of the list. The task is to fla
9 min read
Level with maximum number of nodesGiven a binary tree, the task is to find the level in a binary tree that has the maximum number of nodes. Note: The root is at level 0.Examples: Input: Binary Tree Output : 2Explanation: Input: Binary tree Output:1Explanation Using Breadth First Search - O(n) time and O(n) spaceThe idea is to traver
12 min read
Find if there is a path between two vertices in a directed graphGiven a Directed Graph and two vertices src and dest, check whether there is a path from src to dest.Example: Consider the following Graph: adj[][] = [ [], [0, 2], [0, 3], [], [2] ]Input : src = 1, dest = 3Output: YesExplanation: There is a path from 1 to 3, 1 -> 2 -> 3Input : src = 0, dest =
11 min read
All nodes between two given levels in Binary TreeGiven a binary tree, the task is to print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. Note: The levels are 1-indexed, i.e., root node is at level 1.Example: Input: Binary tree, l = 2, h = 3Output
8 min read
Find next right node of a given keyGiven a Binary tree and a key in the binary tree, find the node right to the given key. If there is no node on right side, then return NULL. Expected time complexity is O(n) where n is the number of nodes in the given binary tree.Example:Input: root = [10 2 6 8 4 N 5] and key = 2Output: 6Explanation
15+ min read
Minimum steps to reach target by a Knight | Set 1Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position.Examples: Input: KnightknightPosition: (1, 3) , targetPosition: (5, 0)Output: 3Explanation: In above diagr
9 min read
Islands in a graph using BFSGiven an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in
15+ min read
Level order traversal line by line (Using One Queue)Given a Binary Tree, the task is to print the nodes level-wise, each level on a new line.Example:Input:Output:12 34 5Table of Content[Expected Approach â 1] Using Queue with delimiter â O(n) Time and O(n) Space[Expected Approach â 2] Using Queue without delimiter â O(n) Time and O(n) Space[Expected
12 min read
First non-repeating character in a streamGiven an input stream s consisting solely of lowercase letters, you are required to identify which character has appeared only once in the stream up to each point. If there are multiple characters that have appeared only once, return the one that first appeared. If no character has appeared only onc
15+ min read