Recursion
Recursion
Recursion
3 All possible binary numbers of length n with equal sum in both halves 22
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4 Backtracking | Introduction 25
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
14 Combinational Sum 73
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
16 Convert a Binary Tree such that every node stores the sum of all nodes
in its right subtree 81
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
17 Count all possible paths from top left to bottom right of a mXn matrix 85
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
2
Contents
31 Find all even length binary sequences with same sum of first and second
half bits 173
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
45 Generate all possible sorted arrays from alternate elements of two given
sorted arrays 247
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
3
Contents
48 Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’ 259
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
50 Given an array A[] and a number x, check for pair in A[] with sum as x 274
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
53 How to print maximum number of A’s using given four keys 307
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
54 How will you print numbers from 1 to 100 without using loop? 317
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
55 How will you print numbers from 1 to 100 without using loop? | Set-2 321
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
61 Leaf nodes from Preorder of a Binary Search Tree (Using Recursion) 355
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
4
Contents
63 Level order traversal with direction change after every two levels | Re-
cursive Approach 369
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
78 Number of handshakes such that a person shakes hands only once 477
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
5
Contents
81 Partition given string in such manner that i’th substring is sum of (i-
1)’th and (i-2)’th substring 494
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
93 Print N-bit binary numbers having more 1’s than 0’s in all prefixes 529
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
6
Contents
97 Print all increasing sequences of length k from first n natural numbers 552
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
98 Print all leaf nodes of a Binary Tree from left to right 562
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
101 Print all non-increasing sequences of sum equal to a given number x 574
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
102 Print all possible combinations of r elements in a given array of size n 584
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
104 Print all possible strings of length k that can be formed from a set of
n characters 603
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
105 Print all possible strings that can be made by placing spaces 608
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
107 Print all sequences starting with n and consecutive difference limited
to k 618
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
7
Contents
117 Program to find the minimum (or maximum) element of an array 683
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689
123 Recursive Approach to find nth node from the end in the linked list 721
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
8
Contents
133 Recursive function to delete k-th node from linked list 764
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
138 Recursive solution to count substrings with same first and last characters783
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
142 Remove duplicates from a sorted linked list using recursion 803
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
146 Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ……, an, bn}
without using extra space 828
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834
9
Contents
10
Contents
11
Chapter 1
Input : n = 4
Output : 1 2 4 5 8 9 10
These are numbers with 1 to 4
bits and no consecutive ones in
binary representation.
Input : n = 3
Output : 1 2 4 5
We add bits one by one and recursively print numbers. For every last bit, we have two
choices.
12
Chapter 1. 1 to n bit numbers with no consecutive 1s in binary representation.
1. We make a solution vector sol and insert first bit 1 in it which will be the first number.
2. Now we check whether length of solution vector is less than or equal to n or not.
3. If it is so then we calculate the decimal number and store it into a map as it store
numbers in sorted order.
4. Now we will have two conditions-
• if last digit in sol is 0 the we can insert 0 or 1 and recur.
• else if last digit is 1 then we can insert 0 only and recur.
numberWithNoConsecutiveOnes(n, sol)
{
if sol.size() <= n
13
Chapter 1. 1 to n bit numbers with no consecutive 1s in binary representation.
Output:
1 2 4 5 8 9 10
Related Post :
Count number of binary strings without consecutive 1’s
Improved By : Kishore Srinivas
14
Chapter 1. 1 to n bit numbers with no consecutive 1s in binary representation.
Source
https://www.geeksforgeeks.org/1-to-n-bit-numbers-with-no-consecutive-1s-in-binary-representation/
15
Chapter 2
Alexander Bogomolny’s
UnOrdered Permutation
Algorithm
Input : 2
Output : 1 2
2 1
Input : 3
Output : 1 2 3
1 3 2
2 1 3
3 1 2
2 3 1
3 2 1
The idea is to maintain an array to store the current permutation. A static integer level
variable is used to define these permutations.
1. It initializes the value of current level and permutes the remaining values to the higher
levels.
2. As the assigning action of the values reaches to the highest level, it prints the permu-
tation obtained.
16
Chapter 2. Alexander Bogomolny’s UnOrdered Permutation Algorithm
C++
17
Chapter 2. Alexander Bogomolny’s UnOrdered Permutation Algorithm
int perm[N] = { 0 };
AlexanderBogomolyn(perm, N, 0);
return 0;
}
Java
18
Chapter 2. Alexander Bogomolny’s UnOrdered Permutation Algorithm
C#
// C# program to implement
// Alexander Bogomolny UnOrdered
// Permutation Algorithm
using System;
class GFG
{
static int level = -1;
// A function to print
// the permutation.
static void print(int []perm,
int N)
{
for (int i = 0; i < N; i++)
Console.Write(" " + perm[i]);
Console.WriteLine();
}
// A function implementing
// Alexander Bogomolyn algorithm.
static void AlexanderBogomolyn(int []perm,
int N, int k)
{
// Assign level to
// zero at start.
19
Chapter 2. Alexander Bogomolny’s UnOrdered Permutation Algorithm
level = level + 1;
perm[k] = level;
if (level == N)
print(perm, N);
else
for (int i = 0; i < N; i++)
// Assign values
// to the array
// if it is zero.
if (perm[i] == 0)
AlexanderBogomolyn(perm, N, i);
// Decrement the level
// after all possible
// permutation after
// that level.
level = level - 1;
perm[k] = 0;
}
// Driver Code
public static void Main ()
{
int N = 3;
int []perm = new int[N];
AlexanderBogomolyn(perm, N, 0);
}
}
// This code is contributed
// by anuj_67.
Output:
1 2 3
1 3 2
2 1 3
3 1 2
2 3 1
3 2 1
Improved By : vt_m
20
Chapter 2. Alexander Bogomolny’s UnOrdered Permutation Algorithm
Source
https://www.geeksforgeeks.org/alexander-bogomolnys-unordered-permutation-algorithm/
21
Chapter 3
All possible binary numbers of length n with equal sum in both halves - GeeksforGeeks
Given a number n, we need to print all n-digit binary numbers with equal sum in left and
right halves. If n is odd, then mid element can be either 0 or 1.
Examples:
Input : n = 4
Output : 1001 1010 1111
Input : n = 5
Output : 10001 10101 10010 10110 11011 11111
The idea is to recursively build left and right halves and keep track of difference between
counts of 1s in them. We print a string when difference becomes 0 and there are no more
characters to add.
22
Chapter 3. All possible binary numbers of length n with equal sum in both halves
23
Chapter 3. All possible binary numbers of length n with equal sum in both halves
/* add 1 in end in left half and 0 to the
right half. Add 1 to di as left sum is
increased by 1*/
equal(n-2, left+"1", right+"0", di+1);
/* add 1 in end to both left and right
half the sum will not change*/
equal(n-2, left+"1", right+"1", di);
}
}
/* driver function */
int main()
{
int n = 5; // n-bits
equal(n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/all-possible-binary-numbers-of-length-n-with-equal-sum-in-both-halves/
24
Chapter 4
Backtracking | Introduction
• Recursion
• Complexity Analysis
25
Chapter 4. Backtracking | Introduction
coin. This is what backtracking is, that is solving all sub-problems one by one in order to
reach the best possible solution.
Consider the below example to understand the Backtracking approach more formally,
The Algorithm begins to build up a solution, starting with an empty solution set . S=
{}
1. Add to the first move that is still left (All possible moves are added to one by
one). This now creates a new sub-tree in the search tree of the algorithm.
using argument .
4. If the check for returns that it is a solution for the entire data . Output
and terminate the program.
If not, then return that no solution is possible with the current and hence discard
it.
26
Chapter 4. Backtracking | Introduction
The expected output is a binary matrix which has 1s for the blocks where queens are placed.
For example, following is the output matrix for the above 4 queen solution.
{ 0, 1, 0, 0}
{ 0, 0, 0, 1}
{ 1, 0, 0, 0}
{ 0, 0, 1, 0}
Backtracking Algorithm: The idea is to place queens one by one in different columns,
starting from the leftmost column. When we place a queen in a column, we check for clashes
27
Chapter 4. Backtracking | Introduction
with already placed queens. In the current column, if we find a row for which there is no
clash, we mark this row and column as part of the solution. If we do not find such a row
due to clashes then we backtrack and return false.
You may refer to the article on Backtracking | Set 3 (N Queen Problem) for complete
implementation of the above approach.
More Backtracking Problems:
Source
https://www.geeksforgeeks.org/backtracking-introduction/
28
Chapter 5
Balanced expressions such that given positions have opening brackets | Set 2 - GeeksforGeeks
Given an integer n and an array of positions ‘position[]’ (1 <= length(position[]) <= 2n),
find the number of ways of proper bracket expressions that can be formed of length 2n such
that given positions have the opening bracket.
Note: position[] array is given in the form of (1-based indexing) [0, 1, 1, 0]. Here 1
denotes the positions at which open bracket should be placed. At positions with value 0,
either of opening and closing bracket can be placed.
Examples:
Dynamic Programming approach of this problem has been already discussed here. In this
post, recursive and recursion using memoization approach will be discussed.
Algorithm–
29
Chapter 5. Balanced expressions such that given positions have opening brackets | Set 2
1. Mark all the positions with open brackets in the given array adj as 1.
2. Run a recursive loop, such that –
• If count of total brackets(opening brackets subracted from closing brackets is less
than zero), return 0.
• If the index reaches till n and if the total brackets=0, then a solution is obtained
and return 1, otherwise return 0.
• If the index has 1 pre-assigned to it, return the function recursively with index+1
and increment the total brackets.
• Otherwise Return the function recursively by inserting open brackets at that
index and incrementing total brackets by 1 + inserting closed brackets at that
index and decrementing total brackets by 1 and move on to the next index till n.
30
Chapter 5. Balanced expressions such that given positions have opening brackets | Set 2
Output:
Memoized Approach: Time complexity of the above algorithm can be optimized by using
Memorization. The only thing to be done is to use an array to store the results of previous
iterations so that there is no need to recursively call the same function more than once, if
the value is already calculated.
Below is the required implementation:
31
Chapter 5. Balanced expressions such that given positions have opening brackets | Set 2
// If index reaches the end of expression
if (index == n) {
// If brackets are balanced
if (openbrk == 0)
return 1;
else
return 0;
}
// If already stored in dp
if (dp[index][openbrk] != -1)
return dp[index][openbrk];
// If the current index has assigned open bracket
if (adj[index] == 1) {
// Move forward increasing the
// length of open brackets
dp[index][openbrk] = find(index + 1,
openbrk + 1, n, dp, adj);
}
else {
// Move forward by inserting open as
// well as closed brackets on that index
dp[index][openbrk] = find(index + 1, openbrk + 1, n, dp, adj)
+ find(index + 1, openbrk - 1, n, dp, adj);
}
// return the answer
return dp[index][openbrk];
}
// Driver Code
int main()
{
// DP array to precompute the answer
int dp[N][N];
int n = 2;
memset(dp, -1, sizeof(dp));
// Open brackets at postion 1
int adj[4] = { 1, 0, 0, 0 };
// Calling the find function to calculate the answer
cout << find(0, 0, 2 * n, dp, adj) << endl;
32
Chapter 5. Balanced expressions such that given positions have opening brackets | Set 2
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/balanced-expressions-such-that-given-positions-have-opening-brackets-set-2/
33
Chapter 6
Bank Of America (BA Continuum India Pvt. Ltd.) Campus Recruitment - GeeksforGeeks
Approved Offer.
Bank Of America has visited our college for on campus recruitment . The recruitment
consisted of 4 Rounds in total.
The recruitment was for BA Continuum India Pvt Ltd. the technical field of BOA
Round 1:
This round was a general aptitude test, English proficiency, quantitative analysis and the
logical questions. This was time specific f0r each and every section. Try practicing from
GFG, indiabix and careerride youtube videos.
Round 2: TECHNICAL 1
This was a face to face technical interview. I was asked to submit my resume and then was
asked to wait until my name was called out. The interview went around 30-40 minutes.
The interviewer started with a very basic aptitude problem( dices probability) and then he
asked me a puzzle of water jug problem. Then he asked me to explain my projects in the
resume and about the experience I had in the previous organization.
After that he went forward with the technical questions consisting of CODING problems .
34
Chapter 6. Bank Of America (BA Continuum India Pvt. Ltd.) Campus Recruitment
Round 3: TECHNICAL 2
It was another technical round. This round was based on advanced coding.
The interviewers above solely focused on the approach or the pseudo code and helped if we
got stuck somewhere.
Round 4: HR ROUND
Here the HR was very friendly and asked about whether you are able to relocate if asked?
At last I was given a feedback by the interviewers as strong logical and coding skills . I
received the offer letter on that day itself at night.
Position: Senior Tech Associate, Bank Of America
Source
https://www.geeksforgeeks.org/bank-of-america-ba-continuum-india-pvt-ltd-campus-recruitment/
35
Chapter 7
Input : 1001
Output : 1101
Input : 11
Output : 10
binary_to_grey(n)
if n == 0
grey = 0;
else if last two bits are opposite to each other
grey = 1 + 10 * binary_to_gray(n/10))
else if last tow bits are same
grey = 10 * binary_to_gray(n/10))
CPP
36
Chapter 7. Binary to Gray code using recursion
Java
37
Chapter 7. Binary to Gray code using recursion
int a, b;
int result = 0;
if (n != 0)
{
// Taking last digit
a = n % 10;
n = n / 10;
// Taking second last digit
b = n % 10;
if ((a & ~ b) == 1 || (~ a & b) == 1)
{
result = (int) (result + pow(10,i));
}
return binary_to_gray(n, ++i) + result;
}
return 0;
}
// Driver Function
public static void main(String[] args)
{
int binary_number;
int result = 0;
binary_number = 1011101;
bin_gray obj = new bin_gray();
result = obj.binary_to_gray(binary_number,0);
System.out.print(result);
}
}
// This article is contributed by Anshika Goyal.
Python3
38
Chapter 7. Binary to Gray code using recursion
C#
// C# program to convert
// Binary code to Gray code
using System;
class GFG {
// Function to change Binary to
// Gray using recursion
static int binary_to_gray(int n, int i)
{
int a, b;
int result = 0;
if (n != 0)
{
// Taking last digit
a = n % 10;
n = n / 10;
// Taking second last digit
b = n % 10;
if ((a & ~ b) == 1 || (~ a & b) == 1)
{
result = (int) (result + Math.Pow(10,i));
}
39
Chapter 7. Binary to Gray code using recursion
return binary_to_gray(n, ++i) + result;
}
return 0;
}
// Driver Function
public static void Main()
{
int binary_number;
binary_number = 1011101;
Console.WriteLine(binary_to_gray(binary_number,0));
}
}
// This article is contributed by vt_m.
PHP
<?php
// PHP program to convert Binary to
// Gray code using recursion
// Function to change Binary to
// Gray using recursion
function binary_to_gray($n)
{
if (!$n)
return 0;
// Taking last digit
$a = $n % 10;
// Taking second
// last digit
$b = ($n / 10) % 10;
// If last digit are
// opposite bits
if (($a && !$b) || (!$a && $b))
return (1 + 10 * binary_to_gray($n / 10));
// If last two
// bits are same
return (10 * binary_to_gray($n / 10));
}
40
Chapter 7. Binary to Gray code using recursion
// Driver Code
$binary_number = 1011101;
echo binary_to_gray($binary_number);
// This code is contributed by Ajit
?>
Output :
1110011
Assume that the binary number is in the range of integer. For larger value we can take
binary number as string.
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-convert-binary-code-equivalent-gray-code-using-recursion/
41
Chapter 8
Input : int x = 4, y = 78
Output : 82
Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be
obtained by performing AND (&) of two bits.
Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this
logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^)
of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&)
is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it
to x ^ y to get the required result.
One important observation is, if (x & y) becomes 0, then result is x ^ y.
C
42
Chapter 8. Bitwise recursive addition of two integers
Java
43
Chapter 8. Bitwise recursive addition of two integers
C#
// C# program to do recursive
// addition of two integers
using System;
class GFG {
static int add(int x, int y)
{
int keep = (x & y) << 1;
int res = x^y;
// If bitwise & is 0, then there
// is not going to be any carry.
// Hence result of XOR is addition.
if (keep == 0)
return res;
return add(keep, res);
}
// Driver code
public static void Main ()
{
Console.Write(add(15, 38));
}
}
// This code is contributed by Smitha.
PHP
<?php
// php program to do recursive addition
// of two integers
function add($x, $y) {
$keep = ($x & $y) << 1;
$res = $x^$y;
// If bitwise & is 0, then there
// is not going to be any carry.
// Hence result of XOR is addition.
if ($keep == 0)
44
Chapter 8. Bitwise recursive addition of two integers
{
echo $res;
exit(0);
}
add($keep, $res);
}
// Driver code
$k= add(15, 38);
// This code is contributed by mits.
?>
Output:
53
Source
https://www.geeksforgeeks.org/bitwise-recursive-addition-two-integers/
45
Chapter 9
We have discussed a stack based solution. Here we are not allowed to use stack. Looks like
this problem cannot be solved without extra space (please see comments at the end). We
use recursion to solve the problem.
Below is the implementation of above algorithm:
46
Chapter 9. Check for balanced parenthesis without using stack
return '}';
if (c == '[')
return ']';
return -1;
}
// function to check if parenthesis are
// balanced.
bool check(char expr[], int n)
{
// Base cases
if (n == 0)
return true;
if (n == 1)
return false;
if (expr[0] == ')' || expr[0] == '}' || expr[0] == ']')
return false;
// Search for closing bracket for first
// opening bracket.
char closing = findClosing(expr[0]);
// count is used to handle cases like
// "((()))". We basically need to
// consider matching closing bracket.
int i, count = 0;
for (i = 1; i < n; i++) {
if (expr[i] == expr[0])
count++;
if (expr[i] == closing) {
if (count == 0)
break;
count--;
}
}
// If we did not find a closing
// bracket
if (i == n)
return false;
// If closing bracket was next
// to open
if (i == 1)
return check(expr + 2, n - 2);
// If closing bracket was somewhere
// in middle.
47
Chapter 9. Check for balanced parenthesis without using stack
Output:
Not Balanced
The above solution is very inefficient compared to stack based solution. This seems to only
useful for recursion practice problems.
Source
https://www.geeksforgeeks.org/check-for-balanced-parenthesis-without-using-stack/
48
Chapter 10
Check if a destination is
reachable from source with two
movements allowed
Check if a destination is reachable from source with two movements allowed - GeeksforGeeks
Given coordinates of a source point (x1, y1) determine if it is possible to reach the destination
point (x2, y2). From any point (x, y) there only two types of valid movements:
(x, x + y) and (x + y, y). Return a boolean true if it is possible else return false.
Note: All coordinates are positive.
Asked in: Expedia, Telstra
Examples:
The problem can be solved using simple recursion. Base case would be to check if current
x or y coordinate is greater than that of destination, in which case we return false. If it is
not the destination point yet we make two calls for both valid movements from that point.
If any of them yields a path we return true else return false.
C++
49
Chapter 10. Check if a destination is reachable from source with two movements allowed
Java
50
Chapter 10. Check if a destination is reachable from source with two movements allowed
Python3
# Python3 program to check if
# a destination is reachable
# from source with two movements allowed
def isReachable(sx, sy, dx, dy):
# base case
if (sx > dx or sy > dy):
return False
# current point is equal to destination
if (sx == dx and sy == dy):
return True
# check for other 2 possibilities
return (isReachable(sx + sy, sy, dx, dy) or
isReachable(sx, sy + sx, dx, dy))
# Driver code
source_x, source_y = 2, 10
dest_x, dest_y = 26, 12
51
Chapter 10. Check if a destination is reachable from source with two movements allowed
C#
52
Chapter 10. Check if a destination is reachable from source with two movements allowed
PHP
<?php
// PHP program to check if a
// destination is reachable
// from source with two movements
// allowed
function isReachable($sx, $sy, $dx, $dy)
{
// base case
if ($sx > $dx || $sy > $dy)
return false;
// current point is equal
// to destination
if ($sx == $dx && $sy == $dy)
return true;
// check for other 2 possibilities
return (isReachable($sx + $sy, $sy, $dx, $dy) ||
isReachable($sx, $sy + $sx, $dx, $dy));
}
// Driver code
$source_x = 2;
$source_y = 10;
$dest_x = 26;
$dest_y = 12;
if (isReachable($source_x, $source_y,
$dest_x, $dest_y))
echo "True\n";
else
echo "False\n";
// This code is contributed by Sam007
?>
Output:
True
Improved By : Sam007
53
Chapter 10. Check if a destination is reachable from source with two movements allowed
Source
https://www.geeksforgeeks.org/check-destination-reachable-source-two-movements-allowed/
54
Chapter 11
sub-string(i, x) + sub-string(x+1, j)
= sub-string(j+1, l)
and
sub-string(x+1, j)+sub-string(j+1, l)
= sub-string(l+1, m)
and so on till end.
From the examples, we can see that our decision depends on first two chosen numbers.
So we choose all possible first two number for given string. Then for every chosen two
55
Chapter 11. Check if a given string is sum-string
56
Chapter 11. Check if a given string is sum-string
}
// Returns true of two substrings of ginven
// lengths of str[beg..] can cause a positive
// result.
bool checkSumStrUtil(string str, int beg,
int len1, int len2)
{
// Finding two substrings of given lengths
// and their sum
string s1 = str.substr(beg, len1);
string s2 = str.substr(beg + len1, len2);
string s3 = string_sum(s1, s2);
int s3_len = s3.size();
// if number of digits s3 is greater then
// the available string size
if (s3_len > str.size() - len1 - len2 - beg)
return false;
// we got s3 as next number in main string
if (s3 == str.substr(beg + len1 + len2, s3_len)) {
// if we reach at the end of the string
if (beg + len1 + len2 + s3_len == str.size())
return true;
// otherwise call recursively for n2, s3
return checkSumStrUtil(str, beg + len1, len2,
s3_len);
}
// we do not get s3 in main string
return false;
}
// Returns true if str is sum string, else false.
bool isSumStr(string str)
{
int n = str.size();
// choosing first two numbers and checking
// whether it is sum-string or not.
for (int i = 1; i < n; i++)
for (int j = 1; i + j < n; j++)
if (checkSumStrUtil(str, 0, i, j))
57
Chapter 11. Check if a given string is sum-string
return true;
return false;
}
// Driver code
int main()
{
cout << isSumStr("1212243660") << endl;
cout << isSumStr("123456787");
return 0;
}
Output:
1
0
Source
https://www.geeksforgeeks.org/check-given-string-sum-string/
58
Chapter 12
Check if a number is
Palindrome
Let the given number be num. A simple method for this problem is to first reverse digits of
num, then compare the reverse of num with num. If both are same, then return true, else
false.
Following is an interesting method inspired from method#2 of thispost. The idea is to
create a copy of num and recursively pass the copy by reference, and pass num by value. In
the recursive calls, divide num by 10 while moving down the recursion tree. While moving
up the recursion tree, divide the copy by 10. When they meet in a function for which all
child calls are over, the last digit of num will be ith digit from the beginning and the last
digit of copy will be ith digit from the end.
C++
59
Chapter 12. Check if a number is Palindrome
60
Chapter 12. Check if a number is Palindrome
n = 12;
isPal(n)? printf("Yesn"): printf("Non");
n = 88;
isPal(n)? printf("Yesn"): printf("Non");
n = 8999;
isPal(n)? printf("Yesn"): printf("Non");
return 0;
}
Java
61
Chapter 12. Check if a number is Palindrome
62
Chapter 12. Check if a number is Palindrome
C#
63
Chapter 12. Check if a number is Palindrome
64
Chapter 12. Check if a number is Palindrome
65
Chapter 12. Check if a number is Palindrome
else
Console.WriteLine("No");
n = 8999;
if(isPal(n) == 0)
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by mits
PHP
<?php
// A recursive PHP program to
// check whether a given number
// is palindrome or not
// A function that reurns true
// only if num contains one digit
function oneDigit($num)
{
// comparison operation is faster
// than division operation. So
// using following instead of
// "return num / 10 == 0;"
return (($num >= 0) &&
($num < 10));
}
// A recursive function to find
// out whether num is palindrome
// or not. Initially, dupNum
// contains address of a copy of num.
function isPalUtil($num, $dupNum)
{
// Base case (needed for recursion
// termination): This statement
// mainly compares the first digit
// with the last digit
if (oneDigit($num))
return ($num == ($dupNum) % 10);
// This is the key line in this
// method. Note that all recursive
// calls have a separate copy of
66
Chapter 12. Check if a number is Palindrome
67
Chapter 12. Check if a number is Palindrome
echo "Yes\n";
else
echo "No\n";
$n = 88;
if(isPal($n) == 1)
echo "Yes\n";
else
echo "No\n";
$n = 8999;
if(isPal($n) == 0)
echo "Yes\n";
else
echo "No\n";
// This code is contributed by m_kit
?>
Output:
Yes
No
Yes
No
Source
https://www.geeksforgeeks.org/check-if-a-number-is-palindrome/
68
Chapter 13
Iterative Approach : Traverse the linked list from head to end. For every newly encoun-
tered element, check node -> data > node -> next -> data. If True, do same for each
node else return 0 and Print “No”.
69
Chapter 13. Check if linked list is sorted (Iterative and Recursive)
int data;
struct Node* next;
};
// function to Check Linked List is
// sorted in descending order or not
bool isSortedDesc(struct Node *head)
{
if (head == NULL)
return true;
// Traverse the list till last node and return
// false if a node is smaller than or equal
// its next.
for (Node *t=head; t->next != NULL; t=t->next)
if (t->data <= t->next->data)
return false;
return true;
}
Node *newNode(int data)
{
Node *temp = new Node;
temp->next = NULL;
temp->data = data;
}
// Driver program to test above
int main()
{
struct Node *head = newNode(7);
head->next = newNode(5);
head->next->next = newNode(4);
head->next->next->next = newNode(3);
isSortedDesc(head) ? cout << "Yes" :
cout << "No";
return 0;
}
Output:
Yes
70
Chapter 13. Check if linked list is sorted (Iterative and Recursive)
Recursive Approach :
Check Recursively that node -> data > node -> next -> data, If not, return 0 that
is our terminated condition to come out from recursion else Call Check_List Function
Recursively for next node.
71
Chapter 13. Check if linked list is sorted (Iterative and Recursive)
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-linked-list-sorting-order/
72
Chapter 14
Combinational Sum
Input : arr[] = 2, 4, 6, 8
x = 8
Output : [2, 2, 2, 2]
[2, 2, 4]
[2, 6]
[4, 4]
[8]
Since the problem is to get all the possible results, not the best or the number of result, thus
we don’t need to consider DP(dynamic programming), recursion is needed to handle it.
We should use the following algorithm.
73
Chapter 14. Combinational Sum
vectors).
(B) Else if sum if negative then ignore that
sub-problem.
(C) Else insert the present array in that
index to the current vector and call
the function with sum = sum-ar[index] and
index = index, then pop that element from
current index (backtrack) and call the
function with sum = sum and index = index+1
74
Chapter 14. Combinational Sum
}
}
// Returns all combinations of ar[] that have given
// sum.
vector<vector<int> > combinationSum(vector<int>& ar,
int sum)
{
// sort input array
sort(ar.begin(), ar.end());
// remove duplicates
ar.erase(unique(ar.begin(), ar.end()), ar.end());
vector<int> r;
vector<vector<int> > res;
findNumbers(ar, sum, res, r, 0);
return res;
}
// Driver code
int main()
{
vector<int> ar;
ar.push_back(2);
ar.push_back(4);
ar.push_back(6);
ar.push_back(8);
int n = ar.size();
int sum = 8; // set value of sum
vector<vector<int> > res = combinationSum(ar, sum);
// If result is empty, then
if (res.size() == 0)
{
cout << "Emptyn";
return 0;
}
// Print all combinations stored in res.
for (int i = 0; i < res.size(); i++)
{
if (res[i].size() > 0)
{
cout << " ( ";
for (int j = 0; j < res[i].size(); j++)
75
Chapter 14. Combinational Sum
Output:
( 2 2 2 2 ) ( 2 2 4 ) ( 2 6 ) ( 4 4 ) ( 8 )
Source
https://www.geeksforgeeks.org/combinational-sum/
76
Chapter 15
Combinations in a String of
Digits
Input : 123
Output :1 2 3
1 23
12 3
123
Input : 1234
Output : 1 2 3 4
1 2 34
1 23 4
1 234
12 3 4
12 34
123 4
1234
The problem can be solved using recursion. We keep track of current index in given input
string and length of output string so far. In each call to the function, if there are no digits
remaining in the input string print the current output string and return. Otherwise, copy
current digit to output. From here make two calls, one considering next digit as part of next
number(including a space in output string) and one considering next digit as part of current
number( no space included). If there are no digits remaining after current digit the second
call to the function is omitted because a trailing space doesn’t count as a new combination.
77
Chapter 15. Combinations in a String of Digits
78
Chapter 15. Combinations in a String of Digits
Output:
1 2 1 4
1 2 14
1 21 4
1 214
12 1 4
12 14
121 4
1214
Alternative Solution:
79
Chapter 15. Combinations in a String of Digits
Output:
1214
1 214
12 14
1 2 14
121 4
1 21 4
12 1 4
1 2 1 4
Source
https://www.geeksforgeeks.org/combinations-string-digits/
80
Chapter 16
Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- GeeksforGeeks
Given a binary tree, change the value in each node to sum of all the values in the nodes in
the right subtree including its own.
Examples:
Input :
1
/ \
2 3
Output :
4
/ \
2 3
Input :
1
/ \
2 3
/ \ \
4 5 6
Output :
10
/ \
7 9
81
Chapter 16. Convert a Binary Tree such that every node stores the sum of all nodes in its
right subtree
/ \ \
4 5 6
Approach : The idea is to traverse the given binary tree in bottom up manner. Recur-
sively compute the sum of nodes in right and left subtrees. Accumulate sum of nodes in the
right subtree to the current node and return sum of nodes under current subtree.
Below is the implementation of above approach.
82
Chapter 16. Convert a Binary Tree such that every node stores the sum of all nodes in its
right subtree
// Return sum of values under root
return root->data + leftsum;
}
// Function to traverse tree in inorder way
void inorder(struct Node* node)
{
if (node == NULL)
return;
inorder(node->left);
cout << node->data << " ";
inorder(node->right);
}
// Driver code
int main()
{
/* Let us construct a binary tree
1
/ \
2 3
/ \ \
4 5 6 */
struct Node* root = NULL;
root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->right = createNode(6);
// new tree construction
updateBTree(root);
cout << "Inorder traversal of the modified tree is \n";
inorder(root);
return 0;
}
Output:
83
Chapter 16. Convert a Binary Tree such that every node stores the sum of all nodes in its
right subtree
Source
https://www.geeksforgeeks.org/convert-a-binary-tree-such-that-every-node-stores-the-sum-of-all-nodes-in-its-right-
84
Chapter 17
Count all possible paths from top left to bottom right of a mXn matrix - GeeksforGeeks
The problem is to count all the possible paths from top left to bottom right of a mXn matrix
with the constraints that from each cell you can either move only to right or down
Examples :
Input : m = 2, n = 2;
Output : 2
There are two paths
(0, 0) -> (0, 1) -> (1, 1)
(0, 0) -> (1, 0) -> (1, 1)
Input : m = 2, n = 3;
Output : 3
There are three paths
(0, 0) -> (0, 1) -> (0, 2) -> (1, 2)
(0, 0) -> (0, 1) -> (1, 1) -> (1, 2)
(0, 0) -> (1, 0) -> (1, 1) -> (1, 2)
We have discussed a solution to print all possible paths, counting all paths is easier. Let
NumberOfPaths(m, n) be the count of paths to reach row number m and column number n
in the matrix, NumberOfPaths(m, n) can be recursively written as following.
C++
#include <iostream>
85
Chapter 17. Count all possible paths from top left to bottom right of a mXn matrix
Java
86
Chapter 17. Count all possible paths from top left to bottom right of a mXn matrix
Python
Output:
The time complexity of above recursive solution is exponential. There are many overlap-
ping subproblems. We can draw a recursion tree for numberOfPaths(3, 3) and see many
overlapping subproblems. The recursion tree would be similar to Recursion tree for Longest
Common Subsequence problem.
So this problem has both properties (see this and this) of a dynamic programming problem.
87
Chapter 17. Count all possible paths from top left to bottom right of a mXn matrix
#include <iostream>
using namespace std;
// Returns count of possible paths to reach cell at
// row number m and column number n from the topmost
// leftmost cell (cell at 1, 1)
int numberOfPaths(int m, int n)
{
// Create a 2D table to store results of subproblems
int count[m][n];
// Count of paths to reach any cell in first column is 1
for (int i = 0; i < m; i++)
count[i][0] = 1;
// Count of paths to reach any cell in first column is 1
for (int j = 0; j < n; j++)
count[0][j] = 1;
// Calculate count of paths for other cells in
// bottom-up manner using the recursive solution
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
// By uncommenting the last part the code calculatest he total
// possible paths if the diagonal Movements are allowed
count[i][j] = count[i-1][j] + count[i][j-1]; //+ count[i-1][j-1];
}
return count[m-1][n-1];
}
// Driver program to test above functions
int main()
{
cout << numberOfPaths(3, 3);
return 0;
}
Java
88
Chapter 17. Count all possible paths from top left to bottom right of a mXn matrix
Python
89
Chapter 17. Count all possible paths from top left to bottom right of a mXn matrix
Output:
90
Chapter 17. Count all possible paths from top left to bottom right of a mXn matrix
class GFG
{
// Returns count of possible paths to reach
// cell at row number m and column number n from
// the topmost leftmost cell (cell at 1, 1)
static int numberOfPaths(int m, int n)
{
// Create a 1D array to store results of subproblems
int[] dp = new int[n];
dp[0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] += dp[j - 1];
}
}
return dp[n - 1];
}
// Driver program to test above function
public static void main(String args[])
{
System.out.println(numberOfPaths(3, 3));
}
}
Output:
Source
https://www.geeksforgeeks.org/count-possible-paths-top-left-bottom-right-nxm-matrix/
91
Chapter 18
Input : abc de
Output : 3
There are three consonants b, c and d.
1. Iterative Method
C++
92
Chapter 18. Count consonants in a string (Iterative and recursive methods)
Java
93
Chapter 18. Count consonants in a string (Iterative and recursive methods)
Python3
94
Chapter 18. Count consonants in a string (Iterative and recursive methods)
# Driver code
string = "abc de"
print(totalConsonants(string))
# This code id contributed by Ansu Kumari.
C#
Output:
95
Chapter 18. Count consonants in a string (Iterative and recursive methods)
2. Recursive Method
C++
Python3
96
Chapter 18. Count consonants in a string (Iterative and recursive methods)
def isConsonant(ch):
# To handle lower case
ch = ch.upper()
return not (ch == 'A' or ch == 'E' or
ch == 'I' or ch == 'O' or
ch == 'U') and ord(ch) >= 65 and ord(ch) <= 90
# To count total number of
# consonants from 0 to n-1
def totalConsonants(string, n):
if n == 1:
return isConsonant(string[0])
return totalConsonants(string, n - 1) + isConsonant(string[n-1])
# Driver code
string = "abc de"
print(totalConsonants(string, len(string)))
# This code is contributed by Ansu Kuamri.
Output :
97
Chapter 18. Count consonants in a string (Iterative and recursive methods)
98
Chapter 18. Count consonants in a string (Iterative and recursive methods)
Source
https://www.geeksforgeeks.org/count-consonants-string-iterative-recursive-methods/
99
Chapter 19
Input: n = 3, k = 2
Output: 3
Explanation: Let the set be {1, 2, 3}, we can partition
it into 2 subsets in following ways
{{1,2}, {3}}, {{1}, {2,3}}, {{1,3}, {2}}
Input: n = 3, k = 1
Output: 1
Explanation: There is only one way {{1, 2, 3}}
We strongly recommend you to minimize your browser and try this yourself
first.
Let S(n, k) be total number of partitions of n elements into k sets. Value of S(n, k) can be
defined recursively as,
100
Chapter 19. Count number of ways to partition a set into k subsets
C++
Java
101
Chapter 19. Count number of ways to partition a set into k subsets
// k subsets
public static int countP(int n, int k)
{
// Base cases
if (n == 0 || k == 0 || k > n)
return 0;
if (k == 1 || k == n)
return 1;
// S(n+1, k) = k*S(n, k) + S(n, k-1)
return (k * countP(n - 1, k)
+ countP(n - 1, k - 1));
}
// Driver program
public static void main(String args[])
{
System.out.println(countP(3, 2));
}
}
//This code is contributed by Anshika Goyal.
C#
102
Chapter 19. Count number of ways to partition a set into k subsets
}
// Driver program
public static void Main()
{
Console.WriteLine(countP(3, 2));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// A PHP program to count
// number of partitions of
// a set with n elements
// into k subsets
// Returns count of different
// partitions of n elements
// in k subsets
function countP($n, $k)
{
// Base cases
if ($n == 0 || $k == 0 || $k > $n)
return 0;
if ($k == 1 || $k == $n)
return 1;
// S(n+1, k) = k*S(n, k)
// + S(n, k-1)
return $k * countP($n - 1, $k) +
countP($n - 1, $k - 1);
}
// Driver Code
echo countP(3, 2);
// This code is contributed by aj_36
?>
Output:
The time complexity of above recursive solution is exponential. The solution can be op-
timized as there are overlapping subproblems. For example, below is recursion tree of
countP(10,7). The subproblem countP(8,6) or CP(8,6) is called multiple times.
103
Chapter 19. Count number of ways to partition a set into k subsets
CP(10,7)
/ \
CP(9,7) CP(9,6)
/ \ / \
CP(8,7) CP(8,6) CP(8,6) CP(8,5)
/ \ / \ / \ / \
So this problem has both properties (see this and this) of a dynamic programming problem.
Like other typical Dynamic Programming(DP) problems, recomputations of same subprob-
lems can be avoided by constructing a temporary array dp[][] in bottom up manner using
the above recursive formula.
Below is C++ implementation of Dynamic Programming Solution.
104
Chapter 19. Count number of ways to partition a set into k subsets
return dp[n][k];
}
// Driver program
int main()
{
cout << countP(5, 2);
return 0;
}
Output:
15
Source
https://www.geeksforgeeks.org/count-number-of-ways-to-partition-a-set-into-k-subsets/
105
Chapter 20
Count occurrences of a
substring recursively
Input: kanekihiishishi
Output: 3
Suppose the problem has n parts, divide the problem in such a way that considers n-1 parts
already done after which the operation to be performed is limited to only one part. Thereby,
dividing the recursion approach into two cases i.e. base case and the recursive case.
In this particular problem, the base case involves the fact that if the length of str1 is less
than that of str2.
Now, talking about the recursive case, compare first substring of str1 with str2 and recur
for remaining str1.
C++
106
Chapter 20. Count occurrences of a substring recursively
Java
107
Chapter 20. Count occurrences of a substring recursively
C#
108
Chapter 20. Count occurrences of a substring recursively
String str2)
{
int n1 = str1.Length;
int n2 = str2.Length;
// Base Case
if (n1 == 0 || n1 < n2)
return 0;
// Recursive Case
// Checking if the first
// substring matches
if (str1.Substring(0, n2).Equals(str2))
return countSubstrig(str1.Substring(n2 - 1),
str2) + 1;
// Otherwise, return the
// count from the remaining
// index
return countSubstrig(str1.Substring(n2 - 1),
str2);
}
// Driver Code
public static void Main()
{
string str1 = "geeksforgeeks",
str2 = "geeks";
Console.Write(countSubstrig(str1,
str2));
Console.Write("\n");
str1 = "hikakashi";
str2 = "hi";
Console.Write(countSubstrig(str1,
str2));
}
}
// This code is contributed
// by Smita
Output:
2
2
109
Chapter 20. Count occurrences of a substring recursively
Source
https://www.geeksforgeeks.org/count-occurrences-of-a-substring-recursively/
110
Chapter 21
Input :
5
/ \
-10 3
/ \ / \
9 8 -4 7
x = 7
Output : 2
There are 2 subtrees with sum 7.
-10
/ \
9 8
111
Chapter 21. Count subtrees that sum up to a given value x
countSubtreesWithSumX(root, count, x)
if !root then
return 0
ls = countSubtreesWithSumX(root->left, count, x)
rs = countSubtreesWithSumX(root->right, count, x)
sum = ls + rs + root->data
if sum == x then
count++
return sum
countSubtreesWithSumXUtil(root, x)
if !root then
return 0
Initialize count = 0
ls = countSubtreesWithSumX(root->left, count, x)
rs = countSubtreesWithSumX(root->right, count, x)
if (ls + rs + root->data) == x
count++
return count
C++
112
Chapter 21. Count subtrees that sum up to a given value x
// put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// function to count subtress that
// sum up to a given value x
int countSubtreesWithSumX(Node* root,
int& count, int x)
{
// if tree is empty
if (!root)
return 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root->left, count, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumX(root->right, count, x);
// sum of nodes in the subtree rooted
// with 'root->data'
int sum = ls + rs + root->data;
// if true
if (sum == x)
count++;
// return subtree's nodes sum
return sum;
}
// utility function to count subtress that
// sum up to a given value x
int countSubtreesWithSumXUtil(Node* root, int x)
{
// if tree is empty
if (!root)
return 0;
int count = 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root->left, count, x);
// sum of nodes in the right subtree
113
Chapter 21. Count subtrees that sum up to a given value x
Java
// Java program to find if
// there is a subtree with
// given sum
import java.util.*;
class GFG
{
// structure of a node
// of binary tree
static class Node
{
114
Chapter 21. Count subtrees that sum up to a given value x
int data;
Node left, right;
}
static class INT
{
int v;
INT(int a)
{
v = a;
}
}
// function to get a new node
static Node getNode(int data)
{
// allocate space
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.left = newNode.right = null;
return newNode;
}
// function to count subtress that
// sum up to a given value x
static int countSubtreesWithSumX(Node root,
INT count, int x)
{
// if tree is empty
if (root == null)
return 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root.left,
count, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumX(root.right,
count, x);
// sum of nodes in the subtree
// rooted with ‘root.data’
int sum = ls + rs + root.data;
// if true
if (sum == x)
count.v++;
// return subtree’s nodes sum
return sum;
}
115
Chapter 21. Count subtrees that sum up to a given value x
// utility function to
// count subtress that
// sum up to a given value x
static int countSubtreesWithSumXUtil(Node root,
int x)
{
// if tree is empty
if (root == null)
return 0;
INT count = new INT(0);
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root.left,
count, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumX(root.right,
count, x);
// if tree’s nodes sum == x
if ((ls + rs + root.data) == x)
count.v++;
// required count of subtrees
return count.v;
}
// Driver Code
public static void main(String args[])
{
/* binary tree creation
5
/\
-10 3
/\/\
9 8 -4 7
*/
Node root = getNode(5);
root.left = getNode(-10);
root.right = getNode(3);
root.left.left = getNode(9);
root.left.right = getNode(8);
root.right.left = getNode(-4);
root.right.right = getNode(7);
int x = 7;
System.out.println(“Count = ” +
countSubtreesWithSumXUtil(root, x));
}
}
116
Chapter 21. Count subtrees that sum up to a given value x
Count = 2
Source
https://www.geeksforgeeks.org/count-subtress-sum-given-value-x/
117
Chapter 22
Input : x = 100
n = 2
Output : 3
Explanation: There are three ways to
express 100 as sum of natural numbers
raised to power 2.
100 = 10^2 = 8^2+6^2 = 1^2+3^2+4^2+5^2+7^2
Input : x = 100
n = 3
Output : 1
Explanation : The only combination is,
1^3 + 2^3 + 3^3 + 4^3
We use recursion to solve the problem. We first check one by one that the number is
included in summation or not.
C++
118
Chapter 22. Count ways to express a number as sum of powers
Java
119
Chapter 22. Count ways to express a number as sum of powers
return 1;
if (val < 0)
return 0;
// Consider two possibilities, num is
// included and num is not included.
return countWaysUtil(val, n, num + 1) +
countWaysUtil(x, n, num + 1);
}
// Returns number of ways to express
// x as sum of n-th power of two.
static int countWays(int x, int n)
{
return countWaysUtil(x, n, 1);
}
// Driver code
public static void main(String args[])
{
int x = 100, n = 2;
System.out.println(countWays(x, n));
}
}
// This code is contributed by Sumit Ghosh
Python3
120
Chapter 22. Count ways to express a number as sum of powers
C#
121
Chapter 22. Count ways to express a number as sum of powers
}
// Driver code
public static void Main()
{
int x = 100, n = 2;
Console.WriteLine(countWays(x, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to count number of ways
// to express x as sum of n-th power
// of unique natural numbers.
// num is current num.
function countWaysUtil($x, $n, $num)
{
// Base cases
$val = ($x - pow($num, $n));
if ($val == 0)
return 1;
if ($val < 0)
return 0;
// Consider two possibilities, num is
// included and num is not included.
return (countWaysUtil($val, $n, $num + 1) +
countWaysUtil($x, $n, $num + 1));
}
// Returns number of ways to express
// x as sum of n-th power of two.
function countWays($x, $n)
{
return countWaysUtil($x, $n, 1);
}
// Driver code
$x = 100; $n = 2;
echo(countWays($x, $n));
122
Chapter 22. Count ways to express a number as sum of powers
Output:
Source
https://www.geeksforgeeks.org/count-ways-express-number-sum-powers/
123
Chapter 23
Examples :
Input : 7
Output :111
Input :10
Output :1010
findBinary(decimal)
if (decimal == 0)
binary = 0
else
binary = decimal % 2 + 10 * (findBinary(decimal / 2)
124
Chapter 23. Decimal to binary number using recursion
Step by step process for better understanding of how the algorithm works
Let decimal number be 10.
Step 1-> 10 % 2 which is equal-too 0 + 10 * ( 10/2 ) % 2
Step 2-> 5 % 2 which is equal-too 1 + 10 * ( 5 / 2) % 2
Step 3-> 2 % 2 which is equal-too 0 + 10 * ( 2 / 2 ) % 2
Step 4-> 1 % 2 which is equal-too 1 + 10 * ( 1 / 2 ) % 2
C
125
Chapter 23. Decimal to binary number using recursion
Java
Python3
126
Chapter 23. Decimal to binary number using recursion
# Driver Code
decimal_number = 10
print(find(decimal_number))
# This code is contributed
# by "Sharad_Bhardwaj"
C#
PHP
<?php
// PHP program for decimal to binary
// conversion using recursion
127
Chapter 23. Decimal to binary number using recursion
// Decimal to binary
// conversion using recursion
function find($decimal_number)
{
if ($decimal_number == 0)
return 0;
else
return ($decimal_number % 2 + 10 *
find($decimal_number / 2));
}
// Driver Code
$decimal_number = 10;
echo(find($decimal_number));
// This code is contributed by Ajit.
?>
Output :
1010
Improved By : jit_t
Source
https://www.geeksforgeeks.org/decimal-binary-number-using-recursion/
128
Chapter 24
Examples:
The idea is to use two stacks, one for integers and another for characters.
Now, traverse the string,
129
Chapter 24. Decode a string recursively encoded as count followed by substring
1. Whenever we encounter any number, push it into the integer stack and in case of any
alphabet (a to z) or open bracket (‘[‘), push it onto the character stack.
2. Whenever any close bracket (‘]’) is encounter pop the character from the character
stack until open bracket (‘[‘) is not found in the character stack. Also, pop the top
element from the integer stack, say n. Now make a string repeating the popped
character n number of time. Now, push all character of the string in the stack.
C++
130
Chapter 24. Decode a string recursively encoded as count followed by substring
stack<char> stringstack;
string temp = "", result = "";
// Traversing the string
for (int i = 0; i < str.length(); i++)
{
int count = 0;
// If number, convert it into number
// and push it into integerstack.
if (str[i] >= '0' && str[i] <='9')
{
while (str[i] >= '0' && str[i] <= '9')
{
count = count * 10 + str[i] - '0';
i++;
}
i--;
integerstack.push(count);
}
// If closing bracket ']', pop elemment until
// '[' opening bracket is not found in the
// character stack.
else if (str[i] == ']')
{
temp = "";
count = 0;
if (! integerstack.empty())
{
count = integerstack.top();
integerstack.pop();
}
while (! stringstack.empty() && stringstack.top()!='[' )
{
temp = stringstack.top() + temp;
stringstack.pop();
}
if (! stringstack.empty() && stringstack.top() == '[')
stringstack.pop();
// Repeating the popped string 'temo' count
// number of times.
for (int j = 0; j < count; j++)
131
Chapter 24. Decode a string recursively encoded as count followed by substring
Java
132
Chapter 24. Decode a string recursively encoded as count followed by substring
import java.util.Stack;
class Test
{
// Returns decoded string for 'str'
static String decode(String str)
{
Stack<Integer> integerstack = new Stack<>();
Stack<Character> stringstack = new Stack<>();
String temp = "", result = "";
// Traversing the string
for (int i = 0; i < str.length(); i++)
{
int count = 0;
// If number, convert it into number
// and push it into integerstack.
if (Character.isDigit(str.charAt(i)))
{
while (Character.isDigit(str.charAt(i)))
{
count = count * 10 + str.charAt(i) - '0';
i++;
}
i--;
integerstack.push(count);
}
// If closing bracket ']', pop elemment until
// '[' opening bracket is not found in the
// character stack.
else if (str.charAt(i) == ']')
{
temp = "";
count = 0;
if (!integerstack.isEmpty())
{
count = integerstack.peek();
integerstack.pop();
}
while (!stringstack.isEmpty() && stringstack.peek()!='[' )
{
temp = stringstack.peek() + temp;
133
Chapter 24. Decode a string recursively encoded as count followed by substring
stringstack.pop();
}
if (!stringstack.empty() && stringstack.peek() == '[')
stringstack.pop();
// Repeating the popped string 'temo' count
// number of times.
for (int j = 0; j < count; j++)
result = result + temp;
// Push it in the character stack.
for (int j = 0; j < result.length(); j++)
stringstack.push(result.charAt(j));
result = "";
}
// If '[' opening bracket, push it into character stack.
else if (str.charAt(i) == '[')
{
if (Character.isDigit(str.charAt(i-1)))
stringstack.push(str.charAt(i));
else
{
stringstack.push(str.charAt(i));
integerstack.push(1);
}
}
else
stringstack.push(str.charAt(i));
}
// Pop all the elmenet, make a string and return.
while (!stringstack.isEmpty())
{
result = stringstack.peek() + result;
stringstack.pop();
}
return result;
}
// Driver method
public static void main(String args[])
{
134
Chapter 24. Decode a string recursively encoded as count followed by substring
Output:
bcacabcacabcaca
Source
https://www.geeksforgeeks.org/decode-string-recursively-encoded-count-followed-substring/
135
Chapter 25
136
Chapter 25. Delete a linked list using recursion
Output:
Source
https://www.geeksforgeeks.org/delete-linked-list-using-recursion/
137
Chapter 26
The idea is to use recursive calls. We first remove all items one by one, then we recur.
After recursive calls, we push all items back except the middle item.
C++
138
Chapter 26. Delete middle element of a stack
// Remove current item
int x = st.top();
st.pop();
// Remove other items
deleteMid(st, n, curr+1);
// Put all items back except middle
if (curr != n/2)
st.push(x);
}
//Driver function to test above functions
int main()
{
stack<char> st;
//push elements into the stack
st.push('1');
st.push('2');
st.push('3');
st.push('4');
st.push('5');
st.push('6');
st.push('7');
deleteMid(st, st.size());
// Printing stack after deletion
// of middle.
while (!st.empty())
{
char p=st.top();
st.pop();
cout << p << " ";
}
return 0;
}
Java
139
Chapter 26. Delete middle element of a stack
// Deletes middle of stack of size
// n. Curr is current item number
static void deleteMid(Stack<Character> st,
int n, int curr)
{
// If stack is empty or all items
// are traversed
if (st.empty() || curr == n)
return;
// Remove current item
char x = st.pop();
// Remove other items
deleteMid(st, n, curr+1);
// Put all items back except middle
if (curr != n/2)
st.push(x);
}
// Driver function to test above functions
public static void main(String args[])
{
Stack<Character> st =
new Stack<Character>();
// push elements into the stack
st.push('1');
st.push('2');
st.push('3');
st.push('4');
st.push('5');
st.push('6');
st.push('7');
deleteMid(st, st.size(), 0);
// Printing stack after deletion
// of middle.
while (!st.empty())
{
char p=st.pop();
System.out.print(p + " ");
}
}
140
Chapter 26. Delete middle element of a stack
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
141
Chapter 26. Delete middle element of a stack
# Driver function to test above functions
st = Stack()
# push elements into the stack
st.push('1')
st.push('2')
st.push('3')
st.push('4')
st.push('5')
st.push('6')
st.push('7')
deleteMid(st, st.size(), 0)
# Printing stack after deletion
# of middle.
while (st.isEmpty() == False) :
p = st.peek()
st.pop()
print (str(p) + " ", end="")
# This code is contributed by
# Manish Shaw (manishshaw1)
C#
142
Chapter 26. Delete middle element of a stack
st.Pop();
// Remove other items
deleteMid(st, n, curr+1);
// Put all items
// back except middle
if (curr != n / 2)
st.Push(x);
}
// Driver Code
public static void Main()
{
Stack<char> st = new Stack<char>();
// push elements into the stack
st.Push('1');
st.Push('2');
st.Push('3');
st.Push('4');
st.Push('5');
st.Push('6');
st.Push('7');
deleteMid(st, st.Count);
// Printing stack after
// deletion of middle.
while (st.Count != 0)
{
char p=st.Peek();
st.Pop();
Console.Write(p + " ");
}
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Output:
7 6 5 3 2 1
Improved By : manishshaw1
143
Chapter 26. Delete middle element of a stack
Source
https://www.geeksforgeeks.org/delete-middle-element-stack/
144
Chapter 27
Algorithm:
The idea is to keep track of vertical distance from top diagonal passing through root. We
increment the vertical distance we go down to next diagonal.
1. Add root with vertical distance as 0 to the queue.
2. Process the sum of all right child and right of right child and so on.
3. Add left child current node into the queue for later processing. The vertical distance of
145
Chapter 27. Diagonal Sum of a Binary Tree
146
Chapter 27. Diagonal Sum of a Binary Tree
}
// Function to calculate diagonal
// sum of given binary tree
void diagonalSum(struct Node* root)
{
// create a map to store Diagonal Sum
map<int, int> diagonalSum;
diagonalSumUtil(root, 0, diagonalSum);
map<int, int>::iterator it;
cout << "Diagonal sum in a binary tree is - ";
for(it = diagonalSum.begin();
it != diagonalSum.end(); ++it)
{
cout << it->second << " ";
}
}
// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(9);
root->left->right = newNode(6);
root->right->left = newNode(4);
root->right->right = newNode(5);
root->right->left->right = newNode(7);
root->right->left->left = newNode(12);
root->left->right->left = newNode(11);
root->left->left->right = newNode(10);
diagonalSum(root);
return 0;
}
// This code is contributed by Aditya Goel
Java
147
Chapter 27. Diagonal Sum of a Binary Tree
import java.util.Map.Entry;
//Tree node
class TreeNode
{
int data; //node data
int vd; //vertical distance diagonally
TreeNode left, right; //left and right child's reference
// Tree node constructor
public TreeNode(int data)
{
this.data = data;
vd = Integer.MAX_VALUE;
left = right = null;
}
}
// Tree class
class Tree
{
TreeNode root;//Tree root
// Tree constructor
public Tree(TreeNode root) { this.root = root; }
// Diagonal sum method
public void diagonalSum()
{
// Queue which stores tree nodes
Queue<TreeNode> queue = new LinkedList<TreeNode>();
// Map to store sum of node's data lying diagonally
Map<Integer, Integer> map = new TreeMap<>();
// Assign the root's vertical distance as 0.
root.vd = 0;
// Add root node to the queue
queue.add(root);
// Loop while the queue is not empty
while (!queue.isEmpty())
{
// Remove the front tree node from queue.
TreeNode curr = queue.remove();
// Get the vertical distance of the dequeued node.
148
Chapter 27. Diagonal Sum of a Binary Tree
int vd = curr.vd;
// Sum over this node's right-child, right-of-right-child
// and so on
while (curr != null)
{
int prevSum = (map.get(vd) == null)? 0: map.get(vd);
map.put(vd, prevSum + curr.data);
// If for any node the left child is not null add
// it to the queue for future processing.
if (curr.left != null)
{
curr.left.vd = vd+1;
queue.add(curr.left);
}
// Move to the current node's right child.
curr = curr.right;
}
}
// Make an entry set from map.
Set<Entry<Integer, Integer>> set = map.entrySet();
// Make an iterator
Iterator<Entry<Integer, Integer>> iterator = set.iterator();
// Traverse the map elements using the iterator.
System.out.print("Diagonal sum in a binary tree is - ");
while (iterator.hasNext())
{
Map.Entry<Integer, Integer> me = iterator.next();
System.out.print(me.getValue()+" ");
}
}
}
//Driver class
public class DiagonalSum
{
public static void main(String[] args)
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(9);
149
Chapter 27. Diagonal Sum of a Binary Tree
Output:
Exercise:
This problem was for diagonals from top to bottom and slope -1. Try the same problem for
slope +1.
This article is contributed by Kumar Gautam. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/diagonal-sum-binary-tree/
150
Chapter 28
151
Chapter 28. Equal sum array partition excluding a given element
It can be determined recursively that whether set1Sum is equal to set2Sum. Start from
position 0 and traverse the array recursively. At every array position, there are two choices:
either include current array element in set 1 or in set 2. Recursively call for both the
conditions, by including current element in set 1 first then in set 2. If current position is
the index to be excluded then recursively call for next position without updating any sum.
When entire array is traversed then check for equality of both sets sum. If the sums are
equal then result is found otherwise backtrack and check for other possibilities.
Implementation:
C++
152
Chapter 28. Equal sum array partition excluding a given element
Java
153
Chapter 28. Equal sum array partition excluding a given element
154
Chapter 28. Equal sum array partition excluding a given element
Python3
155
Chapter 28. Equal sum array partition excluding a given element
index, pos + 1)
# Each element can be included either in
# set 1 or in set 2. Call function for
# both the cases.
return (isSubsetSumPoss(arr, n, set1Sum + arr[pos],
set2Sum, index, pos + 1)
or isSubsetSumPoss(arr, n, set1Sum,
set2Sum + arr[pos], index, pos + 1))
# Function that calls the main utility
# function and returns whether array can
# be partitioned into two sets or not.
def canPartition(arr, n, index) :
# Calculate sum of entire array
# excluding position index.
sum = 0
for i in range (0, n) :
if (i == index) :
continue
sum += arr[i]
# If sum is not even then array
# cannot be partitioned into two
# equal sum sets.
if (sum % 2 != 0) :
return false
# If sum is even call utility function.
return isSubsetSumPoss(arr, n, 0, 0, index, 0)
# Driver Code
arr = [ 2, 5, 1, 4, 0 ]
index = 4
n = len(arr)
if (canPartition(arr, n, index)) :
print ("Yes")
else :
print ("No")
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
156
Chapter 28. Equal sum array partition excluding a given element
157
Chapter 28. Equal sum array partition excluding a given element
// Calculate sum of entire array
// excluding position index.
int sum = 0;
for (int i = 0; i < n; i++) {
if (i == index)
continue;
sum += arr[i];
}
// If sum is not even then array
// cannot be partitioned into two
// equal sum sets.
if (sum % 2 != 0)
return false;
// If sum is even call utility function.
return isSubsetSumPoss(arr, n, 0, 0,
index, 0);
}
// Driver code
public static void Main()
{
int []arr = { 2, 5, 1, 4, 0 };
int index = 4;
int n = arr.Length;
if (canPartition(arr, n, index))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP program to determine whether
// an array can be partitioned into
// two equal sum sets when an index
// is always excluded from both sets.
// Utility function to partition array
158
Chapter 28. Equal sum array partition excluding a given element
159
Chapter 28. Equal sum array partition excluding a given element
// If sum is not even then array
// cannot be partitioned into two
// equal sum sets.
if ($sum % 2 != 0)
return false;
// If sum is even call
// utility function.
return isSubsetSumPoss($arr, $n, 0,
0, $index, 0);
}
// Driver Code
$arr = array( 2, 5, 1, 4, 0 );
$index = 4;
$n = count($arr);
if (canPartition($arr, $n, $index))
echo ("Yes");
else
echo ("No");
// This code is contributed by
// Manish Shaw (manishshaw1)
?>
Output :
Yes
Source
https://www.geeksforgeeks.org/equal-sum-array-partition-excluding-given-element/
160
Chapter 29
161
Chapter 29. Euler Tour | Subtree Sum using Segment Tree
Queries :
1. Sum of all the subtrees of node 1.
2. Update the value of node 6 to 10.
3. Sum of all the subtrees of node 2.
Answers :
1. 6 + 5 + 4 + 3 + 2 + 1 = 21
2.
3. 10 + 5 + 2 = 17
Time Complexity Analysis :
Such queries can be performed using depth for search(dfs) in O(n) time complexity.
Efficient Approach :
The time complexity for such queries can be reduced to O(log(n)) time by converting the
rooted tree into segment tree using Euler tour technique. So, When the number of queries
are q, the total complexity becomes O(q*5log(n)).
Euler Tour :
In Euler tour Technique, each vertex is added to the vector twice, while descending into it
and while leaving it.
Let us understand with the help of previous example :
162
Chapter 29. Euler Tour | Subtree Sum using Segment Tree
On performing depth for search(DFS) using euler tour technique on the given rooted tree,
the vector so formed is :
s[]={1, 2, 6, 6, 5, 5, 2, 3, 4, 4, 3, 1}
163
Chapter 29. Euler Tour | Subtree Sum using Segment Tree
For the output and update query, store the entry time and exit time(which serve as index
range) for each node of the rooted tree.
s[]={1, 2, 6, 6, 5, 5, 2, 3, 4, 4, 3, 1}
Query of type 1 :
Find the range sum on segment tree for output query where range is exit time and entry
time of the rooted tree node. Deduce that the answer is always twice the expected answer
because each node is added twice in segment tree. So reduce the answer by half.
Query of type 2 :
For update query, update the leaf node of segment tree at the entry time and exit time of
the rooted tree node.
Below is the implementation of above approach :
164
Chapter 29. Euler Tour | Subtree Sum using Segment Tree
165
Chapter 29. Euler Tour | Subtree Sum using Segment Tree
}
/* A recursive function to update the
nodes which have the given index in
their range. The following are
parameters pos --> index of current
node in segment tree seg[]. idx -->
index of the element to be updated.
This index is in input array.
val --> Value to be change at node idx
*/
int update(int pos, int low, int high,
int idx, int val)
{
if (low == high) {
seg[pos] = val;
}
else {
int mid = (low + high) / 2;
if (low <= idx && idx <= mid) {
update(2 * pos, low, mid,
idx, val);
}
else {
update(2 * pos + 1, mid + 1,
high, idx, val);
}
seg[pos] = seg[2 * pos] + seg[2 * pos + 1];
}
}
/* A recursive function to form array
ar[] from a directed tree .
*/
int dfs(int root)
{
// pushing each node in vector s
s.push_back(root);
if (v[root].size() == 0)
return root;
for (int i = 0; i < v[root].size(); i++) {
int temp = dfs(v[root][i]);
s.push_back(temp);
}
return root;
166
Chapter 29. Euler Tour | Subtree Sum using Segment Tree
}
// Driver program to test above functions
int main()
{
// Edges between the nodes
v[1].push_back(2);
v[1].push_back(3);
v[2].push_back(6);
v[2].push_back(5);
v[3].push_back(4);
// Calling dfs function.
int temp = dfs(1);
s.push_back(temp);
// Storing entry time and exit
// time of each node
vector<pair<int, int> > p;
for (int i = 0; i <= vertices; i++)
p.push_back(make_pair(0, 0));
for (int i = 0; i < s.size(); i++) {
if (p[s[i]].first == 0)
p[s[i]].first = i + 1;
else
p[s[i]].second = i + 1;
}
// Build segment tree from array ar[].
segment(0, s.size() - 1, 1);
// query of type 1 return the
// sum of subtree at node 1.
int node = 1;
int e = p[node].first;
int f = p[node].second;
int ans = query(1, 1, s.size(), e, f);
// print the sum of subtree
cout << "Subtree sum of node " << node << " is : " << (ans / 2) << endl;
// query of type 2 return update
// the subtree at node 6.
int val = 10;
node = 6;
167
Chapter 29. Euler Tour | Subtree Sum using Segment Tree
e = p[node].first;
f = p[node].second;
update(1, 1, s.size(), e, val);
update(1, 1, s.size(), f, val);
// query of type 1 return the
// sum of subtree at node 2.
node = 2;
e = p[node].first;
f = p[node].second;
ans = query(1, 1, s.size(), e, f);
// print the sum of subtree
cout << "Subtree sum of node " << node << " is : " << (ans / 2) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/euler-tour-subtree-sum-using-segment-tree/
168
Chapter 30
Now you are given n, and you have to find out nth term using above formula.
Examples:
Input : n = 2
Output : 5
Input : n = 3
Output :13
Prerequisite :
Basic Approach:This problem can be solved by simply just iterating over the n terms.
Every time you find a term, using this term find next one and so on. But time complexity
of this problem is of order O(n).
Optimized Approach
All such problem where a term is a function of other terms in linear fashion. Then these
can be solved using Matrix (Please refer : Matrix Exponentiation). First we make transfor-
mation matrix and then just use matrix exponentiation to find Nth term.
169
Chapter 30. Find Nth term (A matrix exponentiation example)
170
Chapter 30. Find Nth term (A matrix exponentiation example)
{
if (n <= 1)
return 1;
// This power function returns first row of
// {Transformation Matrix}^n-1*Initial Vector
n--;
// This is an identity matrix.
ll res[2][2] = { 1, 0, 0, 1 };
// this is Transformation matrix.
ll tMat[2][2] = { 2, 3, 1, 0 };
// Matrix exponentiation to calculate power of {tMat}^n-1
// store res in "res" matrix.
while (n) {
if (n & 1) {
ll tmp[2][2];
tmp[0][0] = (res[0][0] * tMat[0][0] +
res[0][1] * tMat[1][0]) % MOD;
tmp[0][1] = (res[0][0] * tMat[0][1] +
res[0][1] * tMat[1][1]) % MOD;
tmp[1][0] = (res[1][0] * tMat[0][0] +
res[1][1] * tMat[1][0]) % MOD;
tmp[1][1] = (res[1][0] * tMat[0][1] +
res[1][1] * tMat[1][1]) % MOD;
res[0][0] = tmp[0][0];
res[0][1] = tmp[0][1];
res[1][0] = tmp[1][0];
res[1][1] = tmp[1][1];
}
n = n / 2;
ll tmp[2][2];
tmp[0][0] = (tMat[0][0] * tMat[0][0] +
tMat[0][1] * tMat[1][0]) % MOD;
tmp[0][1] = (tMat[0][0] * tMat[0][1] +
tMat[0][1] * tMat[1][1]) % MOD;
tmp[1][0] = (tMat[1][0] * tMat[0][0] +
tMat[1][1] * tMat[1][0]) % MOD;
tmp[1][1] = (tMat[1][0] * tMat[0][1] +
tMat[1][1] * tMat[1][1]) % MOD;
tMat[0][0] = tmp[0][0];
tMat[0][1] = tmp[0][1];
tMat[1][0] = tmp[1][0];
tMat[1][1] = tmp[1][1];
}
171
Chapter 30. Find Nth term (A matrix exponentiation example)
// res store {Transformation matrix}^n-1
// hence will be first row of res*Initial Vector.
return (res[0][0] * 1 + res[0][1] * 1) % MOD;
}
// Driver code
int main()
{
ll n = 3;
cout << power(n);
return 0;
}
Output:
13
Source
https://www.geeksforgeeks.org/find-nth-term-a-matrix-exponentiation-example/
172
Chapter 31
Find all even length binary sequences with same sum of first and second half bits - Geeks-
forGeeks
Given a number n, find all binary sequences of length 2n such that sum of first n bits is
same as sum of last n bits.
Examples:
Input: N = 2
Output:
0101 1111 1001 0110 0000 1010
Input: N = 3
Output:
011011 001001 011101 010001 101011 111111
110011 101101 100001 110101 001010 011110
010010 001100 000000 010100 101110 100010
110110 100100
The idea is to fix first and last bits and then recur for remaining 2*(n-1) bits. There are
four possibilities when we fix first and last bits –
1. First and last bits are 1, remaining n – 1 bits on both sides should also have the same
sum.
2. First and last bits are 0, remaining n – 1 bits on both sides should also have the same
sum.
173
Chapter 31. Find all even length binary sequences with same sum of first and second half
bits
3. First bit is 1 and last bit is 0, sum of remaining n – 1 bits on left side should be 1 less
than the sum n-1 bits on right side.
4. First bit is 0 and last bit is 1, sum of remaining n – 1 bits on left side should be 1
more than the sum n-1 bits on right side.
174
Chapter 31. Find all even length binary sequences with same sum of first and second half
bits
// fill first bit as 1 and last bit as 0
out[start] = '1', out[end] = '0';
findAllSequences(diff - 1, out, start + 1, end - 1);
}
// Driver program
int main()
{
// input number
int n = 2;
// allocate string contaning 2*n characters
char out[2 * n + 1];
// null terminate output array
out[2 * n] = '\0';
findAllSequences(0, out, 0, 2*n - 1);
return 0;
}
Java
175
Chapter 31. Find all even length binary sequences with same sum of first and second half
bits
// if all bits are filled
if (start > end)
{
// if sum of first n bits and
// last n bits are same
if (diff == 0)
{
System.out.print(out);
System.out.print(" ");
}
return;
}
// fill first bit as 0 and last bit as 1
out[start] = '0';
out[end] = '1';
findAllSequences(diff + 1, out, start + 1, end - 1);
// fill first and last bits as 1
out[start] = out[end] = '1';
findAllSequences(diff, out, start + 1, end - 1);
// fill first and last bits as 0
out[start] = out[end] = '0';
findAllSequences(diff, out, start + 1, end - 1);
// fill first bit as 1 and last bit as 0
out[start] = '1';
out[end] = '0';
findAllSequences(diff - 1, out, start + 1, end - 1);
}
// Driver program
public static void main (String[] args)
{
// input number
int n = 2;
// allocate string contaning 2*n characters
char[] out = new char[2 * n + 1];
// null terminate output array
out[2 * n] = '\0';
findAllSequences(0, out, 0, 2*n - 1);
}
}
176
Chapter 31. Find all even length binary sequences with same sum of first and second half
bits
// This code is contributed by Pramod Kumar
C#
177
Chapter 31. Find all even length binary sequences with same sum of first and second half
bits
outt[start] = '0';
outt[end] = '1';
findAllSequences(diff + 1, outt,
start + 1, end - 1);
// fill first and last bits as 1
outt[start] = outt[end] = '1';
findAllSequences(diff, outt,
start + 1, end - 1);
// fill first and last bits as 0
outt[start] = outt[end] = '0';
findAllSequences(diff, outt,
start + 1, end - 1);
// fill first bit as 1 and last
// bit as 0
outt[start] = '1';
outt[end] = '0';
findAllSequences(diff - 1, outt,
start + 1, end - 1);
}
// Driver program
public static void Main ()
{
// input number
int n = 2;
// allocate string contaning 2*n
// characters
char []outt = new char[2 * n + 1];
// null terminate output array
outt[2 * n] = '\0';
findAllSequences(0, outt, 0, 2*n - 1);
}
}
// This code is contributed by nitin mittal.
Output:
178
Chapter 31. Find all even length binary sequences with same sum of first and second half
bits
Source
https://www.geeksforgeeks.org/find-all-even-length-binary-sequences-with-same-sum-of-first-and-second-half-bits/
179
Chapter 32
If m > 1
SUM(n, m) = SUM(SUM(n, m - 1), 1)
Else
SUM(n, 1) = Sum of first n natural numbers.
Input : n = 4, m = 1
Output : SUM(4, 1) = 10
Explanation : 1 + 2 + 3 + 4 = 10
Input : n = 3, m = 2
Output : SUM(3, 2) = 21
Explanation : SUM(3, 2)
= SUM(SUM(3, 1), 1)
= SUM(6, 1)
= 21
Naive Approach : We can solve this problem using two nested loop, where outer loop
iterate for m and inner loop iterate for n. After completion of a single outer iteration, we
should update n as whole of inner loop got executed and value of n must be changed then.
Time complexity should be O(n*m).
180
Chapter 32. Find m-th summation of first n natural numbers.
Efficient Approach :
We can use direct formula for sum of first n numbers to reduce time.
We can also use recursion. In this approach m = 1 will be our base condition and for any
intermediate step SUM(n, m), we will call SUM (SUM(n, m-1), 1) and for a single step
SUM(n, 1) = n * (n + 1) / 2 will be used. This will reduce our time complexity to O(m).
181
Chapter 32. Find m-th summation of first n natural numbers.
Java
Python3
182
Chapter 32. Find m-th summation of first n natural numbers.
C#
PHP
<?php
183
Chapter 32. Find m-th summation of first n natural numbers.
Output:
Source
https://www.geeksforgeeks.org/find-mth-summation-first-n-natural-numbers/
184
Chapter 33
Input : 4
/ \
2 -5
/ \ /\
-1 3 -2 6
Output: 36
Explanation :
Product of all nodes of 0'th level is 4
Product of all nodes of 1'th level is -10
Product of all nodes of 0'th level is 36
Hence maximum product is 6
Input : 1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Output : 160
Explanation :
Product of all nodes of 0'th level is 1
185
Chapter 33. Find maximum level product in Binary Tree
186
Chapter 33. Find maximum level product in Binary Tree
187
Chapter 33. Find maximum level product in Binary Tree
/ \ \
4 5 8
/ \
6 7 */
cout << "Maximum level product is "
<< maxLevelProduct(root) << endl;
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/find-maximum-level-product-binary-tree/
188
Chapter 34
Input : 1->2->3->4->5
Output : 3
Input : 1->2->3->4->5->6
Output : 4
We have already discussed Iterative Solution. In this post iterative solution is discussed.
Count total number of nodes in the list in recursive manner and do half of this, suppose this
value is n. Then rolling back through recursion decrement n by one for each call. Return
the node where n is zero.
189
Chapter 34. Find middle of singly linked list Recursively
190
Chapter 34. Find middle of singly linked list Recursively
head->next->next->next->next = newLNode(5);
Node* result = midpoint(head);
cout << result->data << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-middle-singly-linked-list-recursively/
191
Chapter 35
We have discussed how to find lexicographically n-th permutation using STL. Time com-
plexity of previous approach is O(n * n!) which is quite high.
Here we use some Mathematical concept for solving this problem.
The idea is based on below facts.
192
Chapter 35. Find n-th lexicographically permutation of a string | Set 2
• The total number of permutation of a string formed by N characters (all distinct) after
fixing the first character is (N-1)!
We first count frequencies of all characters in an array freq[]. Now from the first smallest
character present in the string (smallest index i such that freq[i] > 0), we compute the
number of maximum permutation possible after setting that particular i-th character as the
first character. If this sum value is more than given n, then we set that character as the first
result output character, decrement freq[i], and continue same for remaining n-1 characters.
On the other hand, if the count is less than the required n, iterate for the next character in
the frequency table and update the count over and over again until we find a character that
produces a count greater than the required n.
Time Complexity: O(n) i.e. order of string length
C++
193
Chapter 35. Find n-th lexicographically permutation of a string | Set 2
char out[MAX_CHAR];
// iterate till sum equals n
int sum = 0;
int k = 0;
// We update both n and sum in this
// loop.
while (sum != n) {
sum = 0;
// check for characters present in freq[]
for (int i = 0; i < MAX_CHAR; i++) {
if (freq[i] == 0)
continue;
// Remove character
freq[i]--;
// calculate sum after fixing
// a particuar char
int xsum = fact[len - 1 - k];
for (int j = 0; j < MAX_CHAR; j++)
xsum /= fact[freq[j]];
sum += xsum;
// if sum > n fix that char as
// present char and update sum
// and required nth after fixing
// char at that position
if (sum >= n) {
out[k++] = i + 'a';
n -= (sum - xsum);
break;
}
// if sum < n, add character back
if (sum < n)
freq[i]++;
}
}
// if sum == n means this char will provide its
// greatest permutation as nth permutation
for (int i=MAX_CHAR-1; k < len && i >= 0; i--)
if (freq[i]) {
out[k++] = i + 'a';
freq[i++]--;
194
Chapter 35. Find n-th lexicographically permutation of a string | Set 2
}
// append string termination
// character and print result
out[k] = '\0';
cout << out;
}
// Driver program
int main()
{
int n = 2;
char str[] = "geeksquiz";
nPermute(str, n);
return 0;
}
Java
195
Chapter 35. Find n-th lexicographically permutation of a string | Set 2
// out string for output string
String out = "";
// iterate till sum equals n
int sum = 10;
int k = 0;
// We update both n and sum in this
// loop.
while (sum >= n) {
// check for characters present in freq[]
for (int i = 0; i < MAX_CHAR; i++) {
if (freq[i] == 0)
continue;
// Remove character
freq[i]--;
// calculate sum after fixing
// a particular char
sum = 0;
int xsum = (int) fact[len - 1 - k];
for (int j = 0; j < MAX_CHAR; j++)
xsum /= fact[freq[j]];
sum += xsum;
// if sum > n fix that char as
// present char and update sum
// and required nth after fixing
// char at that position
if (sum >= n) {
out += (char)(i + 'a');
k++;
n -= (sum - xsum);
break;
}
// if sum < n, add character back
if (sum < n)
freq[i]++;
}
}
// if sum == n means this char will provide its
// greatest permutation as nth permutation
for (int i = MAX_CHAR - 1; k < len && i >= 0; i--)
196
Chapter 35. Find n-th lexicographically permutation of a string | Set 2
if (freq[i] != 0) {
out += (char)(i + 'a');
freq[i++]--;
}
// append string termination
// character and print result
System.out.println(out);
}
// Driver program to test above method
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 2;
String str = "geeksquiz";
nPermute(str, n);
}
}
// This code is contributed by Sumit Ghosh
C#
197
Chapter 35. Find n-th lexicographically permutation of a string | Set 2
// Count frequencies of all
// characters
int []freq = new int[MAX_CHAR];
for (int i = 0; i < len; i++)
freq[str[i] - 'a']++;
// out string for output string
string ou = "";
// iterate till sum equals n
int sum = 10;
int k = 0;
// We update both n and sum in this
// loop.
while (sum >= n) {
// check for characters present in freq[]
for (int i = 0; i < MAX_CHAR; i++) {
if (freq[i] == 0)
continue;
// Remove character
freq[i]--;
// calculate sum after fixing
// a particular char
sum = 0;
int xsum = (int) fact[len - 1 - k];
for (int j = 0; j < MAX_CHAR; j++)
xsum /= (int)(fact[freq[j]]);
sum += xsum;
// if sum > n fix that char as
// present char and update sum
// and required nth after fixing
// char at that position
if (sum >= n) {
ou += (char)(i + 'a');
k++;
n -= (sum - xsum);
break;
}
198
Chapter 35. Find n-th lexicographically permutation of a string | Set 2
Output:
eegikqszu
Source
https://www.geeksforgeeks.org/find-n-th-lexicographically-permutation-string-set-2/
199
Chapter 36
Input : N = 4
11
/ \
21 31
/ \
41 51
Output : 31
Explanation: Postorder Traversal of given Binary Tree is 41 51 21 31 11,
so 4th node will be 31.
Input : N = 5
25
/ \
20 30
/ \ / \
18 22 24 32
Output : 32
The idea to solve this problem is to do postorder traversal of the given binary tree and keep
track of the count of nodes visited while traversing the tree and print the current node when
the count becomes equal to N.
200
Chapter 36. Find n-th node in Postorder traversal of a Binary Tree
201
Chapter 36. Find n-th node in Postorder traversal of a Binary Tree
// driver code
int main()
{
struct Node* root = createNode(25);
root->left = createNode(20);
root->right = createNode(30);
root->left->left = createNode(18);
root->left->right = createNode(22);
root->right->left = createNode(24);
root->right->right = createNode(32);
int N = 6;
// prints n-th node found
NthPostordernode(root, N);
return 0;
}
Output:
30
Time Complexity: O(n), where n is the number of nodes in the given binary tree.
Auxiliary Space: O(1)
Source
https://www.geeksforgeeks.org/find-n-th-node-in-postorder-traversal-of-a-binary-tree/
202
Chapter 37
E
/
E D
/ /
E D D E
/ / / /
E D D E D E E D
Given level and position of a person in above ancestor tree, find the profession of the person.
Examples :
203
Chapter 37. Find profession in a special family
Method 1 (Recursive)
The idea is based on the fact that profession of a person depends on following two.
1. Profession of parent.
2. Position of node : If position of a node is odd, then its profession is same as its parent.
Else profession is different from its parent.
We recursively find the profession of parent, then use point 2 above to find the profession
of current node.
Below is implementation of above idea.
C++
204
Chapter 37. Find profession in a special family
Java
205
Chapter 37. Find profession in a special family
pos) == 'e')
System.out.println("Engineer");
else
System.out.println("Doctor");
}
}
// This code is contributed
// by anuj_67.
C#
// C# program to find
// profession of a person
// at given level and position
using System;
class GFG
{
// Returns 'e' if profession
// of node at given level
// and position is engineer.
// Else doctor. The function
// assumes that given position
// and level have valid values.
static char findProffesion(int level,
int pos)
{
// Base case
if (level == 1)
return 'e';
// Recursively find parent's
// profession. If parent
// is a doctar, this node
// will be a doctal if it
// is at odd position and an
// engineer if at even position
if (findProffesion(level - 1,
(pos + 1) / 2) == 'd')
return (pos % 2 > 0) ?
'd' : 'e';
// If parent is an engineer,
// then current node will be
// an enginner if at add
// position and doctor if even
206
Chapter 37. Find profession in a special family
// position.
return (pos % 2 > 0) ?
'e' : 'd';
}
// Driver code
public static void Main ()
{
int level = 4, pos = 2;
if(findProffesion(level,
pos) == 'e')
Console.WriteLine("Engineer");
else
Console.WriteLine("Doctor");
}
}
// This code is contributed
// by anuj_67.
PHP
<?php
// PHP program to find profession
// of a person at given level
// and position.
// Returns 'e' if profession of
// node at given level and position
// is engineer. Else doctor. The
// function assumes that given
// position and level have valid values.
function findProffesion($level, $pos)
{
// Base case
if ($level == 1)
return 'e';
// Recursively find parent's
// profession. If parent is
// a Doctor, this node will
// be a doctor if it is at
// odd position and an engineer
// if at even position
if (findProffesion($level - 1,
($pos + 1) / 2) == 'd')
return ($pos % 2) ? 'd' : 'e';
207
Chapter 37. Find profession in a special family
Output :
Doctor
Level 1: E
Level 2: ED
Level 3: EDDE
Level 4: EDDEDEED
Level 5: EDDEDEEDDEEDEDDE
Level input isn’t necessary (if we ignore max position limit) because first elements are same.
The result is based on count of 1’s in binary representation of position minus one. If count
of 1’s is even then result is Engineer, else then Doctor.
And of course position limit is 2^(Level-1)
C++
208
Chapter 37. Find profession in a special family
PHP
<?php
// PHP program to find profession
// of a person at given level and position.
// Function to get no of set
// bits in binary representation
// of passed binary no.
function countSetBits($n)
{
$count = 0;
while ($n)
{
209
Chapter 37. Find profession in a special family
Output :
Engineer
210
Chapter 37. Find profession in a special family
Source
https://www.geeksforgeeks.org/find-profession-in-a-hypothetical-special-situation/
211
Chapter 38
Find ways an Integer can be expressed as sum of n-th power of unique natural numbers -
GeeksforGeeks
Given two numbers x and n, find number of ways x can be expressed as sum of n-th power
of unique natural numbers.
Examples :
Input : x = 10, n = 2
Output : 1
Explanation: 10 = 12 + 32,
Hence total 1 possibility
Input : x = 100, n = 2
Output : 3
Explanation: 100 = 102
OR 62 + 82
OR 12 + 32 + 42 + 52 + 72
Hence total 3 possibilities
The idea is simple. We iterate through all number starting from 1. For every number, we
recursively try all greater numbers and if we are able to find sum, we increment result.
C++
212
Chapter 38. Find ways an Integer can be expressed as sum of n-th power of unique natural
numbers
213
Chapter 38. Find ways an Integer can be expressed as sum of n-th power of unique natural
numbers
int x = 10, n = 2;
cout << checkRecursive(x, n);
return 0;
}
PHP
<?php
// PHP program to count
// number of ways any
// given integer x can
// be expressed as n-th
// power of unique
// natural numbers.
// Function to calculate and return
// the power of any given number
function power($num, $n)
{
if ($n == 0)
return 1;
else if ($n % 2 == 0)
return power($num, (int)($n / 2)) *
power($num, (int)($n / 2));
else
return $num * power($num, (int)($n / 2)) *
power($num, (int)($n / 2));
}
// Function to check power
// representations recursively
function checkRecursive($x, $n,
$curr_num = 1,
$curr_sum = 0)
{
// Initialize number of
// ways to express
// x as n-th powers
// of different natural
// numbers
$results = 0;
// Calling power of 'i'
// raised to 'n'
$p = power($curr_num, $n);
while ($p + $curr_sum < $x)
214
Chapter 38. Find ways an Integer can be expressed as sum of n-th power of unique natural
numbers
{
// Recursively check all
// greater values of i
$results += checkRecursive($x, $n,
$curr_num + 1,
$p + $curr_sum);
$curr_num++;
$p = power($curr_num, $n);
}
// If sum of powers
// is equal to x
// then increase the
// value of result.
if ($p + $curr_sum == $x)
$results++;
// Return the final result
return $results;
}
// Driver Code.
$x = 10; $n = 2;
echo(checkRecursive($x, $n));
// This code is contributed by Ajit.
?>
Output:
Alternate Solution :
Below is an alternate simpler solution provided by Shivam Kanodia.
Java
215
Chapter 38. Find ways an Integer can be expressed as sum of n-th power of unique natural
numbers
C#
216
Chapter 38. Find ways an Integer can be expressed as sum of n-th power of unique natural
numbers
PHP
<?php
// PHP program to find number
// of ways to express a number
// as sum of n-th powers of numbers.
$res = 0;
function checkRecursive($num, $x,
$k, $n)
{
global $res;
if ($x == 0)
$res++;
$r = (int)floor(pow($num,
1.0 / $n));
for ($i = $k + 1;
$i <= $r; $i++)
{
$a = $x - (int)pow($i, $n);
if ($a >= 0)
checkRecursive($num, $x -
(int)pow($i, $n),
217
Chapter 38. Find ways an Integer can be expressed as sum of n-th power of unique natural
numbers
$i, $n);
}
return $res;
}
// Wrapper over
// checkRecursive()
function check($x, $n)
{
return checkRecursive($x, $x,
0, $n);
}
// Driver Code
echo (check(10, 2));
// This code is contributed by ajit
?>
Output:
Source
https://www.geeksforgeeks.org/find-ways-integer-can-expressed-sum-n-th-power-unique-natural-numbers/
218
Chapter 39
Input : geeksforgeeKs
Output : K
Input : geekS
Output : S
C++
219
Chapter 39. First uppercase letter in a string (Iterative and Recursive)
return str[i];
return 0;
}
// Driver code
int main()
{
string str = "geeksforGeeKS";
char res = first(str);
if (res == 0)
cout << "No uppercase letter";
else
cout << res << "\n";
return 0;
}
Java
220
Chapter 39. First uppercase letter in a string (Iterative and Recursive)
Python3
C#
221
Chapter 39. First uppercase letter in a string (Iterative and Recursive)
return str[i];
return '0';
}
// Driver function
public static void Main()
{
string str = "geeksforGeeKS";
char res = first(str);
if (res == '0')
Console.WriteLine("No uppercase"
+ " letter");
else
Console.WriteLine(res);
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to find the first
// uppercase letter using linear search
// Function to find string which has
// first character of each word.
function first($str)
{
for ($i = 0; $i < strlen($str); $i++)
if (ctype_upper($str[$i]))
{
return $str[$i];
}
return 0;
}
// Driver code
$str = "geeksforGeeKS";
$res = first($str);
if (ord($res) ==ord(0) )
echo "No uppercase letter";
else
echo $res . "\n";
// This code is contributed by Sam007
222
Chapter 39. First uppercase letter in a string (Iterative and Recursive)
?>
Output:
C++
Java
223
Chapter 39. First uppercase letter in a string (Iterative and Recursive)
// Function to find string which has
// first character of each word.
static char first(String str, int i)
{
if (str.charAt(i) == '\0')
return 0;
if (Character.isUpperCase(str.charAt(i)))
return str.charAt(i);
return first(str, i + 1);
}
// Driver code
public static void main(String args[])
{
String str = "geeksforGeeKS";
char res = first(str,0);
if (res == 0)
System.out.println("No uppercase letter");
else
System.out.println (res );
}
}
// This code is contributed
// by Nikita Tiwari.
Python 3
224
Chapter 39. First uppercase letter in a string (Iterative and Recursive)
else:
print(res)
# This code is contributed
# by Smitha
C#
PHP
<?php
//PHP program to find the
// first uppercase letter.
225
Chapter 39. First uppercase letter in a string (Iterative and Recursive)
Output :
Source
https://www.geeksforgeeks.org/first-uppercase-letter-in-a-string-iterative-and-recursive/
226
Chapter 40
Input :
1
/ \
2 5
/ \ \
3 4 6
Output :
1
\
2
\
3
\
4
\
5
\
6
Input :
227
Chapter 40. Flatten a binary tree into linked list
1
/ \
3 4
/
2
\
5
Output :
1
\
3
\
4
\
2
\
5
Simple Approach: A simple solution is to use Level Order Traversal using Queue. In level
order traversal, keep track of previous node. Make current node as right child of previous
and left of previous node as NULL. This solution requires queue, but question asks to solve
without additional data structure.
Efficient Without Additional Data StructureRecursively look for the node with no
grandchildren and both left and right child in the left sub-tree. Then store node->right in
temp and make node->right=node->left. Insert temp in first node NULL on right of node
by node=node->right. Repeat until it is converted to linked list.
For Example,
228
Chapter 40. Flatten a binary tree into linked list
struct Node {
int key;
Node *left, *right;
};
/* utility that allocates a new Node
with the given key */
Node* newNode(int key)
{
Node* node = new Node;
node->key = key;
node->left = node->right = NULL;
return (node);
}
// Function to convert binary tree into
// linked list by altering the right node
// and making left node point to NULL
void flatten(struct Node* root)
{
// base condition- return if root is NULL
// or if it is a leaf node
if (root == NULL || root->left == NULL &&
root->right == NULL) {
return;
}
// if root->left exists then we have
// to make it root->right
if (root->left != NULL) {
// move left recursively
flatten(root->left);
// store the node root->right
struct Node* tmpRight = root->right;
root->right = root->left;
root->left = NULL;
// find the position to insert
// the stored value
struct Node* t = root->right;
while (t->right != NULL) {
t = t->right;
}
// insert the stored value
t->right = tmpRight;
229
Chapter 40. Flatten a binary tree into linked list
}
// now call the same function
// for root->right
flatten(root->right);
}
// To find the inorder traversal
void inorder(struct Node* root)
{
// base condition
if (root == NULL)
return;
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
/* Driver program to test above functions*/
int main()
{
/* 1
/ \
2 5
/ \ \
3 4 6 */
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->right = newNode(6);
flatten(root);
cout << "The Inorder traversal after "
"flattening binary tree ";
inorder(root);
return 0;
}
Output:
230
Chapter 40. Flatten a binary tree into linked list
Source
https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list/
231
Chapter 41
Input:
screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 2, 2, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 2, 2, 0},
{1, 1, 1, 1, 1, 2, 1, 1},
{1, 1, 1, 1, 1, 2, 2, 1},
};
x = 4, y = 4, newColor = 3
The values in the given 2D screen indicate colors of the pixels.
x and y are coordinates of the brush, newColor is the color that
should replace the previous color on screen[x][y] and all surrounding
pixels with same color.
Output:
Screen should be changed to following.
screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1},
232
Chapter 41. Flood fill Algorithm – how to implement fill() in paint?
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 3, 3, 3, 3, 0, 1, 0},
{1, 1, 1, 3, 3, 0, 1, 0},
{1, 1, 1, 3, 3, 3, 3, 0},
{1, 1, 1, 1, 1, 3, 1, 1},
{1, 1, 1, 1, 1, 3, 3, 1},
};
233
Chapter 41. Flood fill Algorithm – how to implement fill() in paint?
// Recur for north, east, south and west
floodFillUtil(screen, x+1, y, prevC, newC);
floodFillUtil(screen, x-1, y, prevC, newC);
floodFillUtil(screen, x, y+1, prevC, newC);
floodFillUtil(screen, x, y-1, prevC, newC);
}
// It mainly finds the previous color on (x, y) and
// calls floodFillUtil()
void floodFill(int screen[][N], int x, int y, int newC)
{
int prevC = screen[x][y];
floodFillUtil(screen, x, y, prevC, newC);
}
// Driver program to test above function
int main()
{
int screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 2, 2, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 2, 2, 0},
{1, 1, 1, 1, 1, 2, 1, 1},
{1, 1, 1, 1, 1, 2, 2, 1},
};
int x = 4, y = 4, newC = 3;
floodFill(screen, x, y, newC);
cout << "Updated screen after call to floodFill: n";
for (int i=0; i<M; i++)
{
for (int j=0; j<N; j++)
cout << screen[i][j] << " ";
cout << endl;
}
}
Output:
234
Chapter 41. Flood fill Algorithm – how to implement fill() in paint?
1 1 1 3 3 3 3 0
1 1 1 1 1 3 1 1
1 1 1 1 1 3 3 1
References:
http://en.wikipedia.org/wiki/Flood_fill
This article is contributed by Anmol. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/flood-fill-algorithm-implement-fill-paint/
235
Chapter 42
Input : s1 = "hello"
s2 = "geeksforgeeks"
Output : s2 = "hello"
Input : s1 = "geeksforgeeks"
s2 = ""
Output : s2 = "geeksforgeeks"
Iterative :
Copy every character from s1 to s2 starting from index = 0 and in each call increase the
index by 1 until s1 doesn’t reach to end;
236
Chapter 42. Function to copy string (Iterative and Recursive)
{
int i = 0;
for (i=0; s1[i] != '\0'; i++)
s2[i] = s1[i];
s2[i] = '\0';
}
// Driver function
int main()
{
char s1[100] = "GEEKSFORGEEKS";
char s2[100] = "";
myCopy(s1, s2);
cout << s2;
return 0;
}
Output:
GEEKSFORGEEKS
Recursive :
Copy every character from s1 to s2 starting from index = 0 and in each call increase the
index by 1 until s1 doesn’t reach to end;
237
Chapter 42. Function to copy string (Iterative and Recursive)
int main()
{
char s1[100] = "GEEKSFORGEEKS";
char s2[100] = "";
myCopy(s1, s2);
cout << s2;
return 0;
}
Output:
GEEKSFORGEEKS
Source
https://www.geeksforgeeks.org/function-copy-string-iterative-recursive/
238
Chapter 43
Input : K = 3
Output : 000 , 001 , 010 , 100 , 101
Input : K = 4
Output :0000 0001 0010 0100 0101 1000 1001 1010
Idea behind that is IF string ends with ‘1’ then we put only ‘0’ at the end. IF string ends
with ‘0’ then we put both ‘0’ and ‘1’ at the end of string for generating new string.
Below is algorithm
K : size of string
First We Generate All string starts with '0'
initialize n = 1 .
GenerateALLString ( K , Str , n )
a. IF n == K
PRINT str.
b. IF previous character is '1' :: str[n-1] == '1'
put str[n] = '1'
GenerateAllString ( K , str , n+1 )
c. IF previous character is '0' :: str[n-1] == '0'
First We Put zero at end and call function
239
Chapter 43. Generate all binary strings without consecutive 1’s
240
Chapter 43. Generate all binary strings without consecutive 1’s
// function generate all binary string without
// consecutive 1's
void generateAllStrings(int K )
{
// Base case
if (K <= 0)
return ;
// One by one stores every binary string of length K
char str[K];
// Generate all Binary string starts with '0'
str[0] = '0' ;
generateAllStringsUtil ( K , str , 1 ) ;
// Generate all Binary string starts with '1'
str[0] = '1' ;
generateAllStringsUtil ( K , str , 1 );
}
// Driver program to test above function
int main()
{
int K = 3;
generateAllStrings (K) ;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/generate-binary-strings-without-consecutive-1s/
241
Chapter 44
The solution is to use recursion on the given character array. The idea is to pass all possible
lengths and an empty string initially to a helper function. In the helper function we keep
appending all the characters one by one to the current string and recur to fill the remaining
string till the desired length is reached.
It can be better visualized using the below recursion tree:
(a, b)
/ \
a b
/ \ / \
aa ab ba bb
242
Chapter 44. Generate all passwords from given character set
243
Chapter 44. Generate all passwords from given character set
Python 3
244
Chapter 44. Generate all passwords from given character set
Output:
a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc
245
Chapter 44. Generate all passwords from given character set
If we want to see the count of the words, we can uncomment the lines having cnt variable
where n = len. Thus the time complexity of the program is also , hence
exponential. We can also check for a particular password
while generating and break the loop and return if it is found. We can also include other
symbols to be generated and if needed remove duplicates by preprocessing the input using
a HashTable.
Improved By : Smitha Dinesh Semwal
Source
https://www.geeksforgeeks.org/generate-passwords-given-character-set/
246
Chapter 45
Generate all possible sorted arrays from alternate elements of two given sorted arrays -
GeeksforGeeks
Given two sorted arrays A and B, generate all possible arrays such that first element is taken
from A then from B then from A and so on in increasing order till the arrays exhausted.
The generated arrays should end with an element from B.
For Example
A = {10, 15, 25}
B = {1, 5, 20, 30}
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to use recursion. In the recursive function, a flag is passed to indicate whether
current element in output should be taken from ‘A’ or ‘B’. Below is C++ implementation.
C
247
Chapter 45. Generate all possible sorted arrays from alternate elements of two given
sorted arrays
#include<bits/stdc++.h>
using namespace std;
void printArr(int arr[], int n);
/* Function to generates and prints all sorted arrays from alternate elements of
'A[i..m-1]' and 'B[j..n-1]'
If 'flag' is true, then current element is to be included from A otherwise
from B.
'len' is the index in output array C[]. We print output array each time
before including a character from A only if length of output array is
greater than 0. We try than all possible combinations */
void generateUtil(int A[], int B[], int C[], int i, int j, int m, int n,
int len, bool flag)
{
if (flag) // Include valid element from A
{
// Print output if there is at least one 'B' in output array 'C'
if (len)
printArr(C, len+1);
// Recur for all elements of A after current index
for (int k = i; k < m; k++)
{
if (!len)
{
/* this block works for the very first call to include
the first element in the output array */
C[len] = A[k];
// don't increment lem as B is included yet
generateUtil(A, B, C, k+1, j, m, n, len, !flag);
}
else /* include valid element from A and recur */
{
if (A[k] > C[len])
{
C[len+1] = A[k];
generateUtil(A, B, C, k+1, j, m, n, len+1, !flag);
}
}
}
}
else /* Include valid element from B and recur */
{
for (int l = j; l < n; l++)
{
if (B[l] > C[len])
248
Chapter 45. Generate all possible sorted arrays from alternate elements of two given
sorted arrays
{
C[len+1] = B[l];
generateUtil(A, B, C, i, l+1, m, n, len+1, !flag);
}
}
}
}
/* Wrapper function */
void generate(int A[], int B[], int m, int n)
{
int C[m+n]; /* output array */
generateUtil(A, B, C, 0, 0, m, n, 0, true);
}
// A utility function to print an array
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver program
int main()
{
int A[] = {10, 15, 25};
int B[] = {5, 20, 30};
int n = sizeof(A)/sizeof(A[0]);
int m = sizeof(B)/sizeof(B[0]);
generate(A, B, n, m);
return 0;
}
Java
class GenerateArrays {
/* Function to generates and prints all sorted arrays from alternate
elements of 'A[i..m-1]' and 'B[j..n-1]'
If 'flag' is true, then current element is to be included from A
otherwise from B.
'len' is the index in output array C[]. We print output array
each time before including a character from A only if length of
output array is greater than 0. We try than all possible
combinations */
void generateUtil(int A[], int B[], int C[], int i, int j, int m, int n,
int len, boolean flag)
249
Chapter 45. Generate all possible sorted arrays from alternate elements of two given
sorted arrays
{
if (flag) // Include valid element from A
{
// Print output if there is at least one 'B' in output array 'C'
if (len != 0)
printArr(C, len + 1);
// Recur for all elements of A after current index
for (int k = i; k < m; k++)
{
if (len == 0)
{
/* this block works for the very first call to include
the first element in the output array */
C[len] = A[k];
// don't increment lem as B is included yet
generateUtil(A, B, C, k + 1, j, m, n, len, !flag);
}
/* include valid element from A and recur */
else if (A[k] > C[len])
{
C[len + 1] = A[k];
generateUtil(A, B, C, k + 1, j, m, n, len + 1, !flag);
}
}
}
/* Include valid element from B and recur */
else
{
for (int l = j; l < n; l++)
{
if (B[l] > C[len])
{
C[len + 1] = B[l];
generateUtil(A, B, C, i, l + 1, m, n, len + 1, !flag);
}
}
}
}
/* Wrapper function */
void generate(int A[], int B[], int m, int n)
{
int C[] = new int[m + n];
250
Chapter 45. Generate all possible sorted arrays from alternate elements of two given
sorted arrays
Python3
251
Chapter 45. Generate all possible sorted arrays from alternate elements of two given
sorted arrays
# Print output if there is at
# least one 'B' in output array 'C'
if (len):
printArr(C, len+1)
# Recur for all elements of
# A after current index
for k in range(i,m):
if ( not len):
''' this block works for the
very first call to include
the first element in the output array '''
C[len] = A[k]
# don't increment lem
# as B is included yet
generateUtil(A, B, C, k+1, j, m, n, len, not flag)
else:
# include valid element from A and recur
if (A[k] > C[len]):
C[len+1] = A[k]
generateUtil(A, B, C, k+1, j, m, n, len+1, not flag)
else:
# Include valid element from B and recur
for l in range(j,n):
if (B[l] > C[len]):
C[len+1] = B[l]
generateUtil(A, B, C, i, l+1, m, n, len+1, not flag)
# Wrapper function
def generate(A,B,m,n):
C=[] #output array
for i in range(m+n+1):
C.append(0)
generateUtil(A, B, C, 0, 0, m, n, 0, True)
252
Chapter 45. Generate all possible sorted arrays from alternate elements of two given
sorted arrays
# Driver program
A = [10, 15, 25]
B = [5, 20, 30]
n = len(A)
m = len(B)
generate(A, B, n, m)
# This code is contributed
# by Anant Agarwal.
Output:
10 20
10 20 25 30
10 30
15 20
15 20 25 30
15 30
25 30
This article is contributed by Gaurav Ahirwar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above\
Source
https://www.geeksforgeeks.org/generate-all-possible-sorted-arrays-from-alternate-elements-of-two-given-arrays/
253
Chapter 46
Input : [1, 2, 3]
Output : [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]
Input : [1, 2]
Output : [2], [1], [1, 2]
Approach: For every element in the array, there are two choices, either to include it in the
subsequence or not include it. Apply this for every element in the array starting from index
0 until we reach the last index. Print the subsequence once the last index is reached.
Below diagram shows the recursion tree for array, arr[] = {1, 2}.
254
Chapter 46. Generating all possible Subsequences using Recursion
255
Chapter 46. Generating all possible Subsequences using Recursion
subarr+[arr[index]])
return
arr = [1, 2, 3]
printSubsequences(arr, 0, [])
Output:
[3]
[2]
[2, 3]
[1]
[1, 3]
[1, 2]
[1, 2, 3]
Time Complexity:
Source
https://www.geeksforgeeks.org/generating-all-possible-subsequences-using-recursion/
256
Chapter 47
Input : [1, 2, 3]
Output : [1], [1, 2], [2], [1, 2, 3], [2, 3], [3]
Input : [1, 2]
Output : [1], [1, 2], [2]
We have discussed iterative program to generate all subarrays. In this post, recursive is
discussed.
Approach: We use two pointers start and end to maintain the starting and ending point
of the array and follow the steps given below:
257
Chapter 47. Generating subarrays using recursion
Output:
[1]
[1, 2]
[2]
[1, 2, 3]
[2, 3]
[3]
Time Complexity:
Source
https://www.geeksforgeeks.org/generating-subarrays-using-recursion/
258
Chapter 48
Given a matrix of ‘O’ and ‘X’, replace ’O’ with ’X’ if surrounded by ’X’ - GeeksforGeeks
Given a matrix where every element is either ‘O’ or ‘X’, replace ‘O’ with ‘X’ if surrounded
by ‘X’. A ‘O’ (or a set of ‘O’) is considered to be by surrounded by ‘X’ if there are ‘X’ at
locations just below, just above, just left and just right of it.
Examples:
259
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
This is mainly an application of Flood-Fill algorithm. The main difference here is that a
‘O’ is not replaced by ‘X’ if it lies in region that ends on a boundary. Following are simple
steps to do this special flood fill.
1) Traverse the given matrix and replace all ‘O’ with a special character ‘-‘.
2) Traverse four edges of given matrix and call floodFill(‘-‘, ‘O’) for every ‘-‘ on edges. The
remaining ‘-‘ are the characters that indicate ‘O’s (in the original matrix) to be replaced by
‘X’.
3) Traverse the matrix and replace all ‘-‘s with ‘X’s.
Let us see steps of above algorithm with an example. Let following be the
input matrix.
Step 2: Call floodFill(‘-‘, ‘O’) for all edge elements with value equals to ‘-‘
260
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
261
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
262
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
for (int i=0; i<M; i++)
{
for (int j=0; j<N; j++)
cout << mat[i][j] << " ";
cout << endl;
}
return 0;
}
Java
263
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
// Returns size of maximum
// size subsquare matrix
// surrounded by 'X'
static void replaceSurrounded(char mat[][])
{
// Step 1: Replace
// all 'O' with '-'
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
if (mat[i][j] == 'O')
mat[i][j] = '-';
// Call floodFill for
// all '-' lying on edges
for (int i = 0; i < M; i++) // Left side
if (mat[i][0] == '-')
floodFillUtil(mat, i, 0,
'-', 'O');
for (int i = 0; i < M; i++) // Right side
if (mat[i][N - 1] == '-')
floodFillUtil(mat, i, N - 1,
'-', 'O');
for (int i = 0; i < N; i++) // Top side
if (mat[0][i] == '-')
floodFillUtil(mat, 0, i,
'-', 'O');
for (int i = 0; i < N; i++) // Bottom side
if (mat[M - 1][i] == '-')
floodFillUtil(mat, M - 1,
i, '-', 'O');
// Step 3: Replace
// all '-' with 'X'
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
if (mat[i][j] == '-')
mat[i][j] = 'X';
}
// Driver Code
public static void main (String[] args)
{
char[][] mat = {{'X', 'O', 'X',
'O', 'X', 'X'},
{'X', 'O', 'X',
'X', 'O', 'X'},
264
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
C#
// A C# program to replace
// all 'O's with 'X''s if
// surrounded by 'X'
using System;
class GFG
{
static int M = 6;
static int N = 6;
static void floodFillUtil(char [,]mat, int x,
int y, char prevV,
char newV)
{
// Base cases
if (x < 0 || x >= M ||
y < 0 || y >= N)
return;
if (mat[x, y] != prevV)
return;
// Replace the color at (x, y)
265
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
mat[x, y] = newV;
// Recur for north,
// east, south and west
floodFillUtil(mat, x + 1, y,
prevV, newV);
floodFillUtil(mat, x - 1, y,
prevV, newV);
floodFillUtil(mat, x, y + 1,
prevV, newV);
floodFillUtil(mat, x, y - 1,
prevV, newV);
}
// Returns size of maximum
// size subsquare matrix
// surrounded by 'X'
static void replaceSurrounded(char [,]mat)
{
// Step 1: Replace
// all 'O' with '-'
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
if (mat[i, j] == 'O')
mat[i, j] = '-';
// Call floodFill for
// all '-' lying on edges
for (int i = 0; i < M; i++) // Left side
if (mat[i, 0] == '-')
floodFillUtil(mat, i, 0,
'-', 'O');
for (int i = 0; i < M; i++) // Right side
if (mat[i, N - 1] == '-')
floodFillUtil(mat, i, N - 1,
'-', 'O');
for (int i = 0; i < N; i++) // Top side
if (mat[0, i] == '-')
floodFillUtil(mat, 0, i,
'-', 'O');
for (int i = 0; i < N; i++) // Bottom side
if (mat[M - 1, i] == '-')
floodFillUtil(mat, M - 1,
i, '-', 'O');
// Step 3: Replace
// all '-' with 'X'
266
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
PHP
<?php
// A PHP program to replace all
// 'O's with 'X''s if surrounded by 'X'
// Size of given
// matrix is M X N
$M = 6;
$N = 6;
267
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
// A recursive function to replace
// previous value 'prevV' at '(x, y)'
// and all surrounding values of
// (x, y) with new value 'newV'.
function floodFillUtil(&$mat, $x, $y,
$prevV, $newV)
{
// Base cases
if ($x < 0 || $x >= $GLOBALS['M'] ||
$y < 0 || $y >= $GLOBALS['N'])
return;
if ($mat[$x][$y] != $prevV)
return;
// Replace the color at (x, y)
$mat[$x][$y] = $newV;
// Recur for north,
// east, south and west
floodFillUtil($mat, $x + 1, $y, $prevV, $newV);
floodFillUtil($mat, $x - 1, $y, $prevV, $newV);
floodFillUtil($mat, $x, $y + 1, $prevV, $newV);
floodFillUtil($mat, $x, $y - 1, $prevV, $newV);
}
// Returns size of maximum
// size subsquare matrix
// surrounded by 'X'
function replaceSurrounded(&$mat)
{
// Step 1: Replace all 'O' with '-'
for ($i = 0; $i < $GLOBALS['M']; $i++)
for ($j = 0; $j < $GLOBALS['N']; $j++)
if ($mat[$i][$j] == 'O')
$mat[$i][$j] = '-';
// Call floodFill for all
// '-' lying on edges
for ($i = 0;
$i < $GLOBALS['M']; $i++) // Left side
if ($mat[$i][0] == '-')
floodFillUtil($mat, $i, 0, '-', 'O');
for ($i = 0; $i < $GLOBALS['M']; $i++) // Right side
if ($mat[$i][$GLOBALS['N'] - 1] == '-')
268
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
floodFillUtil($mat, $i,
$GLOBALS['N'] - 1, '-', 'O');
for ($i = 0; $i < $GLOBALS['N']; $i++) // Top side
if ($mat[0][$i] == '-')
floodFillUtil($mat, 0, $i, '-', 'O');
for ($i = 0; $i < $GLOBALS['N']; $i++) // Bottom side
if ($mat[$GLOBALS['M'] - 1][$i] == '-')
floodFillUtil($mat, $GLOBALS['M'] - 1,
$i, '-', 'O');
// Step 3: Replace all '-' with 'X'
for ($i = 0; $i < $GLOBALS['M']; $i++)
for ($j = 0; $j < $GLOBALS['N']; $j++)
if ($mat[$i][$j] == '-')
$mat[$i][$j] = 'X';
}
// Driver Code
$mat = array(array('X', 'O', 'X', 'O', 'X', 'X'),
array('X', 'O', 'X', 'X', 'O', 'X'),
array('X', 'X', 'X', 'O', 'X', 'X'),
array('O', 'X', 'X', 'X', 'X', 'X'),
array('X', 'X', 'X', 'O', 'X', 'O'),
array('O', 'O', 'X', 'O', 'O', 'O'));
replaceSurrounded($mat);
for ($i = 0; $i < $GLOBALS['M']; $i++)
{
for ($j = 0; $j < $GLOBALS['N']; $j++)
echo $mat[$i][$j]." ";
echo "\n";
}
// This code is contributed by ChitraNayal
?>
Output:
X O X O X X
X O X X X X
X X X X X X
O X X X X X
X X X O X O
O O X O O O
269
Chapter 48. Given a matrix of ‘O’ and ‘X’, replace ‘O’ with ‘X’ if surrounded by ‘X’
Time Complexity of the above solution is O(MN). Note that every element of matrix is
processed at most three times.
This article is contributed by Anmol. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Improved By : shiv_bhakt, ChitraNayal
Source
https://www.geeksforgeeks.org/given-matrix-o-x-replace-o-x-surrounded-x/
270
Chapter 49
Note that this problem is different fromPalindrome Partitioning Problem, there the task
was to find the partitioning with minimum cuts in input string. Here we need to print all
possible partitions.
The idea is to go through every substring starting from first character, check if it is palin-
drome. If yes, then add the substring to solution and recur for remaining part. Below is
complete algorithm.
Below is C++ implementation of above idea
C++
271
Chapter 49. Given a string, print all possible palindromic partitions
272
Chapter 49. Given a string, print all possible palindromic partitions
{
int n = str.length();
// To Store all palindromic partitions
vector<vector<string> > allPart;
// To store current palindromic partition
vector<string> currPart;
// Call recursive function to generate all partiions
// and store in allPart
allPalPartUtil(allPart, currPart, 0, n, str);
// Print all partitions generated by above call
for (int i=0; i< allPart.size(); i++ )
{
for (int j=0; j<allPart[i].size(); j++)
cout << allPart[i][j] << " ";
cout << "\n";
}
}
// Driver program
int main()
{
string str = "nitin";
allPalPartitions(str);
return 0;
}
Output:
n i t i n
n iti n
nitin
This article is contributed by Ekta Goel. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/given-a-string-print-all-possible-palindromic-partition/
273
Chapter 50
Given an array A[] and a number x, check for pair in A[] with sum as x - GeeksforGeeks
Write a program that, given an array A[] of n numbers and another number x, determines
whether or not there exist two elements in S whose sum is exactly x.
METHOD 1 (Use Sorting)
Algorithm :
Time Complexity: Depends on what sorting algorithm we use. If we use Merge Sort or
Heap Sort then (-)(nlogn) in worst case. If we use Quick Sort then O(n^2) in worst case.
Auxiliary Space : Again, depends on sorting algorithm. For example auxiliary space is
O(n) for merge sort and O(1) for Heap Sort.
274
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
Example :
Let Array be {1, 4, 45, 6, 10, -8} and sum to find be 16
Sort the array
A = {-8, 1, 4, 6, 10, 45}
Initialize l = 0, r = 5
A[l] + A[r] ( -8 + 45) > 16 => decrement r. Now r = 10
A[l] + A[r] ( -8 + 10) increment l. Now l = 1
A[l] + A[r] ( 1 + 10) increment l. Now l = 2
A[l] + A[r] ( 4 + 10) increment l. Now l = 3
A[l] + A[r] ( 6 + 10) == 16 => Found candidates (return 1)
Note: If there are more than one pair having the given sum then this algorithm reports only
one. Can be easily extended for this though.
Below is the implementation of the above approach.
C
275
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
}
/* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING
PURPOSE */
void exchange(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int partition(int A[], int si, int ei)
{
int x = A[ei];
int i = (si - 1);
int j;
for (j = si; j <= ei - 1; j++)
{
if(A[j] <= x)
{
i++;
exchange(&A[i], &A[j]);
}
}
exchange (&A[i + 1], &A[ei]);
return (i + 1);
}
/* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
void quickSort(int A[], int si, int ei)
{
int pi; /* Partitioning index */
if(si < ei)
{
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
/* Driver program to test above function */
int main()
276
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
{
int A[] = {1, 4, 45, 6, 10, -8};
int n = 16;
int arr_size = 6;
if( hasArrayTwoCandidates(A, arr_size, n))
printf("Array has two elements with given sum");
else
printf("Array doesn't have two elements with given sum");
getchar();
return 0;
}
C++
277
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
}
/* Driver program to test above function */
int main()
{
int A[] = {1, 4, 45, 6, 10, -8};
int n = 16;
int arr_size = sizeof(A) / sizeof(A[0]);
// Function calling
if(hasArrayTwoCandidates(A, arr_size, n))
cout << "Array has two elements with given sum";
else
cout << "Array doesn't have two elements with given sum";
return 0;
}
Java
278
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
r--;
}
return false;
}
// Driver code
public static void main(String args[])
{
int A[] = {1, 4, 45, 6, 10, -8};
int n = 16;
int arr_size = A.length;
// Function calling
if(hasArrayTwoCandidates(A, arr_size, n))
System.out.println("Array has two " +
"elements with given sum");
else
System.out.println("Array doesn't have " +
"two elements with given sum");
}
}
Python
279
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
C#
280
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
sort(A, 0, arr_size-1);
/* Now look for the two candidates
in the sorted array*/
l = 0;
r = arr_size-1;
while (l < r)
{
if(A[l] + A[r] == sum)
return true;
else if(A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return false;
}
/* Below functions are only to sort the
array using QuickSort */
/* This function takes last element as pivot,
places the pivot element at its correct
position in sorted array, and places all
smaller (smaller than pivot) to left of
pivot and all greater elements to right
of pivot */
static int partition(int []arr, int low, int high)
{
int pivot = arr[high];
// index of smaller element
int i = (low-1);
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller
// than or equal to pivot
if (arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
281
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
PHP
282
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
<?php
// PHP program to check if given
// array has 2 elements whose sum
// is equal to the given value
// Function to check if array has
// 2 elements whose sum is equal
// to the given value
function hasArrayTwoCandidates($A, $arr_size,
$sum)
{
$l; $r;
/* Sort the elements */
//sort($A, A + arr_size);
sort($A);
/* Now look for the two candidates
in the sorted array*/
$l = 0;
$r = $arr_size - 1;
while ($l < $r)
{
if($A[$l] + $A[$r] == $sum)
return 1;
else if($A[$l] + $A[$r] < $sum)
$l++;
else // A[i] + A[j] > sum
$r--;
}
return 0;
}
// Driver Code
$A = array (1, 4, 45, 6, 10, -8);
$n = 16;
$arr_size = sizeof($A);
// Function calling
if(hasArrayTwoCandidates($A, $arr_size, $n))
echo "Array has two elements " .
"with given sum";
else
echo "Array doesn't have two " .
"elements with given sum";
// This code is contributed by m_kit
?>
283
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
Output :
284
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
C++
Java
285
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
import java.io.*;
import java.util.HashSet;
class PairSum
{
static void printpairs(int arr[],int sum)
{
HashSet<Integer> s = new HashSet<Integer>();
for (int i=0; i<arr.length; ++i)
{
int temp = sum-arr[i];
// checking for condition
if (temp>=0 && s.contains(temp))
{
System.out.println("Pair with given sum " +
sum + " is (" + arr[i] +
", "+temp+")");
}
s.add(arr[i]);
}
}
// Main to test the above function
public static void main (String[] args)
{
int A[] = {1, 4, 45, 6, 10, 8};
int n = 16;
printpairs(A, n);
}
}
// This article is contributed by Aakash Hasija
Python
286
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
C#
287
Chapter 50. Given an array A[] and a number x, check for pair in A[] with sum as x
Output:
Source
https://www.geeksforgeeks.org/given-an-array-a-and-a-number-x-check-for-pair-in-a-with-sum-as-x/
288
Chapter 51
Happy Number
Input: n = 19
Output: True
19 is Happy Number,
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
As we reached to 1, 19 is a Happy Number.
Input: n = 20
Output: False
A number will not be a Happy Number when it makes a loop in its sequence that is it
touches a number in sequence which already been touched. So to check whether a number
is happy or not, we can keep a set, if same number occurs again we flag result as not happy.
A simple function on above approach can be written as below –
289
Chapter 51. Happy Number
n = numSquareSum(n);
if (n == 1)
return true;
if (st.find(n) != st.end())
return false;
st.insert(n);
}
}
We can solve this problem without using extra space and that technique can be used in
some other similar problem also. If we treat every number as a node and replacement by
square sum digit as a link, then this problem is same as finding a loop in a linklist :
So as proposed solution from above link, we will keep two number slow and fast both
initialize from given number, slow is replaced one step at a time and fast is replaced two
steps at a time. If they meet at 1, then the given number is Happy Number otherwise not.
CPP
290
Chapter 51. Happy Number
// move fast number by two iteration
fast = numSquareSum(numSquareSum(fast));
}
while (slow != fast);
// if both number meet at 1, then return true
return (slow == 1);
}
// Driver code to test above methods
int main()
{
int n = 13;
if (isHappynumber(n))
cout << n << " is a Happy number\n";
else
cout << n << " is not a Happy number\n";
}
Java
291
Chapter 51. Happy Number
do
{
// move slow number
// by one iteration
slow = numSquareSum(slow);
// move fast number
// by two iteration
fast = numSquareSum(numSquareSum(fast));
}
while (slow != fast);
// if both number meet at 1,
// then return true
return (slow == 1);
}
// Driver code to test above methods
public static void main(String[] args)
{
int n = 13;
if (isHappynumber(n))
System.out.println(n +
" is a Happy number");
else
System.out.println(n +
" is not a Happy number");
}
}
C#
292
Chapter 51. Happy Number
}
return squareSum;
}
// method return true if
// n is Happy number
static bool isHappynumber(int n)
{
int slow, fast;
// initialize slow and
// fast by n
slow = fast = n;
do
{
// move slow number
// by one iteration
slow = numSquareSum(slow);
// move fast number
// by two iteration
fast = numSquareSum(numSquareSum(fast));
}
while (slow != fast);
// if both number meet at 1,
// then return true
return (slow == 1);
}
// Driver code
public static void Main()
{
int n = 13;
if (isHappynumber(n))
Console.WriteLine(n +
" is a Happy number");
else
Console.WriteLine(n +
" is not a Happy number");
}
}
// This code is contributed by anuj_67.
PHP
293
Chapter 51. Happy Number
<?php
// PHP program to check a number
// is a Happy number or not
// Utility method to return
// sum of square of digit of n
function numSquareSum( $n)
{
$squareSum = 0;
while ($n)
{
$squareSum += ($n % 10) *
($n % 10);
$n /= 10;
}
return $squareSum;
}
// method return true if
// n is Happy number
function isHappynumber( $n)
{
$slow; $fast;
// initialize slow
// and fast by n
$slow = $n;
$fast = $n;
do
{
// move slow number
// by one iteration
$slow = numSquareSum($slow);
// move fast number
// by two iteration
$fast = numSquareSum(numSquareSum($fast));
}
while ($slow != $fast);
// if both number meet at 1,
// then return true
return ($slow == 1);
}
// Driver Code
$n = 13;
294
Chapter 51. Happy Number
if (isHappynumber($n))
echo $n , " is a Happy number\n";
else
echo n , " is not a Happy number\n";
// This code is contributed by anuj_67.
?>
Output :
13 is a Happy Number
Improved By : vt_m
Source
https://www.geeksforgeeks.org/happy-number/
295
Chapter 52
Input : n = 10
Output : 8
Input : n = 19
Output : 16
Input : n = 32
Output : 32
A simple solution is to start checking from n and keep decrementing until we find a power
of 2.
C++
296
Chapter 52. Highest power of 2 less than or equal to given number
Java
297
Chapter 52. Highest power of 2 less than or equal to given number
C#
PHP
<?php
// PHP program to find highest
// power of 2 smaller than or
// equal to n.
function highestPowerof2($n)
{
$res = 0;
for ($i = $n; $i >= 1; $i--)
{
298
Chapter 52. Highest power of 2 less than or equal to given number
// If i is a power of 2
if (($i & ($i - 1)) == 0)
{
$res = $i;
break;
}
}
return $res;
}
// Driver code
$n = 10;
echo highestPowerof2($n);
// This code is contributed by m_kit
?>
Output :
Time complexity : O(n). In worst case, the loop runs floor(n/2) times. The worst case
happens when n is of the form 2x – 1.
An efficient solution is to use bitwise left shift operator to find all powers of 2 starting
from 1. For every power check if it is smaller than or equal to n or not. Below is C++
implementation of the idea.
C++
299
Chapter 52. Highest power of 2 less than or equal to given number
Java
300
Chapter 52. Highest power of 2 less than or equal to given number
res = curr;
}
return res;
}
// Driver code
public static void main(String[] args)
{
int n = 10;
System.out.println(highestPowerof2(n));
}
}
// This code is contributed aj_36
C#
// C# program to find
// highest power of 2 smaller
// than or equal to n.
using System;
class GFG
{
static int highestPowerof2(int n)
{
// Invalid input
if (n < 1)
return 0;
int res = 1;
// Try all powers
// starting from 2^1
for (int i = 0; i < 8 ; i++)
{
int curr = 1 << i;
// If current power is
// more than n, break
if (curr > n)
break;
res = curr;
}
return res;
301
Chapter 52. Highest power of 2 less than or equal to given number
}
// Driver code
static public void Main ()
{
int n = 10;
Console.WriteLine(highestPowerof2(n));
}
}
// This code is contributed ajit
PHP
<?php
// PHP program to find highest
// power of 2 smaller
// than or equal to n.
function highestPowerof2($n)
{
// Invalid input
if ($n < 1)
return 0;
$res = 1;
// Try all powers starting
// from 2^1
for ($i = 0; $i < 8 ; $i++)
{
$curr = 1 << $i;
// If current power is
// more than n, break
if ($curr > $n)
break;
$res = $curr;
}
return $res;
}
// Driver code
$n = 10;
echo highestPowerof2($n);
302
Chapter 52. Highest power of 2 less than or equal to given number
Output :
Java
303
Chapter 52. Highest power of 2 less than or equal to given number
}
// Driver code
public static void main (String[] args)
{
int n = 10;
System.out.println(highestPowerof2(n));
}
}
// This code is contributed
// by m_kit
C#
// C# program to find
// highest power of 2
// smaller than or equal to n.
using System;
class GFG
{
static int highestPowerof2(int n)
{
int p = (int)(Math.Log(n) /
Math.Log(2));
return (int)Math.Pow(2, p);
}
// Driver code
static public void Main ()
{
int n = 10;
Console.WriteLine(highestPowerof2(n));
}
}
// This code is contributed
// by ajit
PHP
<?php
// PHP program to find highest
// power of 2 smaller than or
// equal to n.
function highestPowerof2($n)
304
Chapter 52. Highest power of 2 less than or equal to given number
{
$p = (int)log($n, 2);
return (int)pow(2, $p);
}
// Driver code
$n = 10;
echo highestPowerof2($n);
// This code is contributed by ajit
?>
Output :
Application Problem:
Some people are standing in a queue. A selection process follows a rule where people
standing on even positions are selected. Of the selected people a queue is formed and again
out of these only people on even position are selected. This continues until we are left with
one person. Find out the position of that person in the original queue.
Print the position(original queue) of that person who is left.
Examples :
Input: n = 10
Output:8
Explanation :
1 2 3 4 5 6 7 8 9 10 ===>Given queue
2 4 6 8 10
4 8
8
Input: n = 17
Input: 16
Explanation :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ===>Given queue
2 4 6 8 10 12 14 16
4 8 12 16
8 16
16
Related Article :
Power of 2 greater than or equal to a given number.
Improved By : jit_t
305
Chapter 52. Highest power of 2 less than or equal to given number
Source
https://www.geeksforgeeks.org/highest-power-2-less-equal-given-number/
306
Chapter 53
How to print maximum number of A’s using given four keys - GeeksforGeeks
This is a famous interview question asked in Google, Paytm and many other company
interviews.
Below is the problem statement.
If you can only press the keyboard for N times (with the above four
keys), write a program to produce maximum numbers of A's. That is to
say, the input parameter is N (No. of keys that you can press), the
output is M (No. of As that you can produce).
Examples:
Input: N = 3
Output: 3
We can at most get 3 A's on screen by pressing
following key sequence.
A, A, A
307
Chapter 53. How to print maximum number of A’s using given four keys
Input: N = 7
Output: 9
We can at most get 9 A's on screen by pressing
following key sequence.
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
Input: N = 11
Output: 27
We can at most get 27 A's on screen by pressing
following key sequence.
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V, Ctrl A,
Ctrl C, Ctrl V, Ctrl V
308
Chapter 53. How to print maximum number of A’s using given four keys
Java
309
Chapter 53. How to print maximum number of A’s using given four keys
C#
/* A recursive C# program
to print maximum number
of A's using following
four keys */
using System;
class GFG
{
// A recursive function that
// returns the optimal length
310
Chapter 53. How to print maximum number of A’s using given four keys
311
Chapter 53. How to print maximum number of A’s using given four keys
// This code is contributed by Sam007
Output:
The above function computes the same subproblems again and again. Recomputations
of same subproblems can be avoided by storing the solutions to subproblems and solving
problems in bottom up manner.
Below is Dynamic Programming based C implementation where an auxiliary array screen[N]
is used to store result of subproblems.
312
Chapter 53. How to print maximum number of A’s using given four keys
Java
313
Chapter 53. How to print maximum number of A’s using given four keys
314
Chapter 53. How to print maximum number of A’s using given four keys
// (n-b-1)*screen[b-1];
int curr = (n - b - 1) * screen[b - 1];
if (curr > screen[n - 1])
screen[n - 1] = curr;
}
}
return screen[N - 1];
}
// Driver program
public static void main(String [] args)
{
int N;
// for the rest of the array we will rely on the previous
// entries to compute new ones
for (N = 1; N <= 20; N++)
System.out.println("Maximum Number of A's with keystrokes is "+
N + findoptimal(N));
}
}
// This article is contributed by vt_m.
Output:
315
Chapter 53. How to print maximum number of A’s using given four keys
Thanks to Gaurav Saxena for providing the above approach to solve this problem.
Improved By : Sam007
Source
https://www.geeksforgeeks.org/how-to-print-maximum-number-of-a-using-given-four-keys/
316
Chapter 54
How will you print numbers from 1 to 100 without using loop? - GeeksforGeeks
If we take a look at this problem carefully, we can see that the idea of “loop” is to track
some counter value e.g. “i=0” till “i <= 100”. So if we aren’t allowed to use loop, how else
can be track something in C language!
Well, one possibility is the use of ‘recursion’ provided we use the terminating condition
carefully. Here is a solution that prints numbers using recursion.
#include <stdio.h>
// Prints numbers from 1 to n
void printNos(unsigned int n)
{
if(n > 0)
{
printNos(n - 1);
printf("%d ", n);
}
return;
}
// Driver code
317
Chapter 54. How will you print numbers from 1 to 100 without using loop?
int main()
{
printNos(100);
getchar();
return 0;
}
Java
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class GFG
{
// Prints numbers from 1 to n
static void printNos(int n)
{
if(n > 0)
{
printNos(n - 1);
System.out.print(n + " ");
}
return;
}
// Driver Code
public static void main(String[] args)
{
printNos(100);
}
}
// This code is contributed by Manish_100
Python3
318
Chapter 54. How will you print numbers from 1 to 100 without using loop?
# Driver code
printNos(100)
# This code is contributed by Smitha Dinesh Semwal
C#
PHP
<?php
// PHP program print numbers
// from 1 to 100 without
// using loop
// Prints numbers from 1 to n
function printNos($n)
{
if($n > 0)
{
printNos($n - 1);
319
Chapter 54. How will you print numbers from 1 to 100 without using loop?
Output :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16 17 18 19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49 50 51
52 53 54 55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72 73 74 75
76 77 78 79 80 81 82 83 84 85 86 87
88 89 90 91 92 93 94 95 96 97 98 99
100
Source
https://www.geeksforgeeks.org/how-will-you-print-numbers-from-1-to-200-without-using-loop/
320
Chapter 55
How will you print numbers from 1 to 100 without using loop? | Set-2 - GeeksforGeeks
If we take a look at this problem carefully, we can see that the idea of “loop” is to track
some counter value e.g. “i=0” till “i <= 100”. So if we aren’t allowed to use loop, how else
can be track something in C language!
It can be done in many ways to print numbers using any looping conditions such as for(),
while(), do while(). But the same can be done without using loops (using recursive functions,
goto statement).
Printing numbers from 1 to 100 using recursive functions has already been discussed in Set-1.
In this post, other two methods have been discussed:
#include <stdio.h>
int main()
{
int i = 0;
begin:
i = i + 1;
printf("%d ", i);
if (i < 100)
goto begin;
return 0;
}
321
Chapter 55. How will you print numbers from 1 to 100 without using loop? | Set-2
Output:
1 2 3 4 . . . 97 98 99 100
#include <stdio.h>
int main()
{
static int i = 1;
if (i <= 100) {
printf("%d ", i++);
main();
}
return 0;
}
Output:
1 2 3 4 . . . 97 98 99 100
Source
https://www.geeksforgeeks.org/program-print-upto-100-without-using-loops/
322
Chapter 56
Example:
Input
Map(A -> Set(B,C), B -> Set(D, C), C -> Set(E))
Output:
Map(D -> Set(A), C -> Set(A), E -> Set(A, B))
We strongly recommend you to minimize your browser and try this yourself
first
Here we have iterate over each and every node in Map and find out the grand-parent of each
child.
The idea is to use Recursion. But, it can be solved without Recursion too.
Lets see the Without Recursion solution first:
Solution 1 (Without Recursion):
Here we have to use Mutable Scala Map. Below is the Scala Code.
323
Chapter 56. Identify all Grand-Parent Nodes of each Node in a Map
val input = Map("A" -> Set("B","C"), "B" -> Set("D", "C"), "C" -> Set("E"))
val output: scala.collection.mutable.Map[String, Set[String]]
= scala.collection.mutable.Map()
Here we are iterating over every Node of Map and finding out the grandchildren of each
child in node.This, will help us in creating a Map with Grand-Child and Grand-Parents
relationship.
Solution 2 (With Recursion):
Here we can use Immutable Scala Map as we are using Recursion.
val input = Map("A" -> Set("B","C"), "B" -> Set("D", "C"), "C" -> Set("E"))
val output = findGrandparents(input)
This article is contributed by Himanshu Gupta. Please write comments if you find any-
thing incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/identify-all-grand-parent-nodes-of-each-node-in-a-map/
324
Chapter 57
Syntax :
Advantage :
parallelSort() method uses concept of MultiThreading which makes the sorting faster as
compared to normal sorting method.
325
Chapter 57. Java 8 | Arrays parallelSort() method with Examples
Example
Below are the program that will illustrate the use of Arrays.parallelSort():
Program 1: To demonstrate use of Parallel Sort
326
Chapter 57. Java 8 | Arrays parallelSort() method with Examples
Output:
Unsorted Array: 9 8 7 6 3 1
Sorted Array: 1 3 6 7 8 9
327
Chapter 57. Java 8 | Arrays parallelSort() method with Examples
Output:
328
Chapter 57. Java 8 | Arrays parallelSort() method with Examples
.
For iteration number: 99
Start and End Time in Serial (in ns): 3951050723541:3951050731520
Time taken by Serial Sort(in ns): 7979
Start and End Time in parallel (in ns): 3951050754238:3951050756130
Time taken by Parallel Sort(in ns): 1892
Note : Different time intervals will be printed But parallel sort will be done before normal
sort.
Environment: 2.6 GHz Intel Core i7, java version 8
Source
https://www.geeksforgeeks.org/java-8-arrays-parallelsort-method-with-examples/
329
Chapter 58
Examples:
1. For image 1:
330
Chapter 58. Java Applet | Implementing Flood Fill algorithm
2. For image 2:
331
Chapter 58. Java Applet | Implementing Flood Fill algorithm
3. For image 3:
332
Chapter 58. Java Applet | Implementing Flood Fill algorithm
333
Chapter 58. Java Applet | Implementing Flood Fill algorithm
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
public class floodfill extends JApplet {
public void init()
{
}
// paint function
public void paint(Graphics g)
{
BufferedImage i = null;
try {
// Input the image to be used for FloodFill
// The output is shown for 3 images
// image1, image2 and image2
i = ImageIO.read(new File("image1.jpg"));
// floodfill with color red at point 35, 35
// get color of image at 35, 35
Color c = new Color(i.getRGB(35, 35));
flood(i, g, 35, 35, c, Color.red);
// draw the image after floodfill
g.drawImage(i, 100, 100, this);
}
catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
// draw the image after floodfill
g.drawImage(i, 100, 100, this);
}
// function to floodfill the image
public void flood(BufferedImage i,
Graphics g,
int x,
int y,
Color c,
Color c1)
{
if (x >= 1 && y >= 1
&& x < i.getWidth()
334
Chapter 58. Java Applet | Implementing Flood Fill algorithm
Output:
• for image 1:
Input:
Output :
335
Chapter 58. Java Applet | Implementing Flood Fill algorithm
• for image 2:
Input:
Output :
336
Chapter 58. Java Applet | Implementing Flood Fill algorithm
• for image 3:
Input:
Output :
Note: If a larger area is flood filled (at coordinate 1, 1) using the recursive approach,
then recursive algorithm might get crashed.
Example:
Output:
Explanation:
Since the area to be covered is very large,
therefore only some part is covered by the algorithm,
and after that the program gets crashed.
337
Chapter 58. Java Applet | Implementing Flood Fill algorithm
338
Chapter 58. Java Applet | Implementing Flood Fill algorithm
Color c1)
{
// create a stack using array
int stx[] = new int[100000];
int sty[] = new int[100000], f, r, x, y;
// create a front and rear
f = r = 0;
// initilize them
stx[0] = x1;
sty[0] = y1;
// while front is greater than rear
while (f >= r) {
// pop element out
x = stx[r];
y = sty[r++];
if (x >= 1 && y >= 1
&& x < i.getWidth()
&& y < i.getHeight()) {
// find the color at point x, y
Color c2 = new Color(i.getRGB(x, y));
// if there is no boundary (the color is almost
// same as the color of the point where
// floodfill is to be applied
if (Math.abs(c2.getGreen() - c.getGreen()) < 30
&& Math.abs(c2.getRed() - c.getRed()) < 30
&& Math.abs(c2.getBlue() - c.getBlue()) < 30) {
// change the color of the pixel of image
i.setRGB(x, y, c1.getRGB());
g.drawImage(i, 100, 100, this);
// floodfill in all possible directions
// store them in queue
stx[f] = x;
sty[f++] = y + 1;
stx[f] = x;
sty[f++] = y - 1;
stx[f] = x + 1;
sty[f++] = y;
stx[f] = x - 1;
sty[f++] = y;
}
339
Chapter 58. Java Applet | Implementing Flood Fill algorithm
}
}
}
}
Output:
– For image 1:
Input:
340
Chapter 58. Java Applet | Implementing Flood Fill algorithm
– For image 2:
Input:
341
Chapter 58. Java Applet | Implementing Flood Fill algorithm
– For image 3:
Input:
342
Chapter 58. Java Applet | Implementing Flood Fill algorithm
Source
https://www.geeksforgeeks.org/java-applet-implementing-flood-fill-algorithm/
343
Chapter 59
After the first person (kth from begining) is killed, n-1 persons are left. So we call josephus(n
– 1, k) to get the position with n-1 persons. But the position returned by josephus(n – 1,
k) will consider the position starting from k%n + 1. So, we must make adjustments to the
position returned by josephus(n – 1, k).
344
Chapter 59. Josephus problem | Set 1 (A O(n) Solution)
#include <stdio.h>
int josephus(int n, int k)
{
if (n == 1)
return 1;
else
/* The position returned by josephus(n - 1, k) is adjusted because the
recursive call josephus(n - 1, k) considers the original position
k%n + 1 as position 1 */
return (josephus(n - 1, k) + k-1) % n + 1;
}
// Driver Program to test above function
int main()
{
int n = 14;
int k = 2;
printf("The chosen place is %d", josephus(n, k));
return 0;
}
Java
345
Chapter 59. Josephus problem | Set 1 (A O(n) Solution)
Python3
C#
346
Chapter 59. Josephus problem | Set 1 (A O(n) Solution)
{
if (n == 1)
return 1;
else
/* The position returned
by josephus(n - 1, k) is
adjusted because the
recursive call josephus(n
- 1, k) considers the
original position k%n + 1
as position 1 */
return (josephus(n - 1, k)
+ k-1) % n + 1;
}
// Driver Program to test above
// function
public static void Main()
{
int n = 14;
int k = 2;
Console.WriteLine("The chosen "
+ "place is " + josephus(n, k));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP code for
// Josephus Problem
function josephus($n, $k)
{
if ($n == 1)
return 1;
else
/* The position returned by
josephus(n - 1, k) is
adjusted because the
recursive call josephus
(n - 1, k) considers the
original position k%n + 1
as position 1 */
return (josephus($n - 1, $k) +
$k - 1) % $n + 1;
347
Chapter 59. Josephus problem | Set 1 (A O(n) Solution)
}
// Driver Code
$n = 14;
$k = 2;
echo "The chosen place is ", josephus($n, $k);
// This code is contributed by ajit.
?>
Output:
Source
https://www.geeksforgeeks.org/josephus-problem-set-1-a-on-solution/
348
Chapter 60
Input : n = 5
Output : 2
5! = 5 * 4 * 3 * 2 * 1 = 120
Last non-zero digit in 120 is 2.
Input : n = 33
Output : 4
A Simple Solution is to first find n!, then find last non-zero digit of n. This solution
doesn’t work for even slightly large numbers due to arithmetic overflow.
A Better Solution is based on below recursive formula
Illustration of formula:
For the numbers less than 10 we can easily find the last non-zero digit by above simple
solution, i.e., first computing n!, then finding last digit.
D(1) = 1, D(2) = 2, D(3) = 6, D(4) = 4, D(5) = 2,
D(6) = 2, D(7) = 4, D(8) = 2, D(9) = 8.
349
Chapter 60. Last non-zero digit of a factorial
14! = 14 * 13 * 12 * 11 * 10 * 9 * 8 * 7 *
6 * 5 * 4 * 3 * 2 * 1
14! = 14 * 13 * 12 * 11 * 2 * 9 * 8 * 7 *
6 * 3 * 2 * 1
In n!, number of 2’s are always more than number of 5’s. To remove trailing 0’s, we remove
5’s and equal number of 2’s.
Let a = floor(n/5), b = n % 5. After removing equal number of 5’s and 2’s, we can reduce
the problem from n! to 2a * a! * b!
D(n) = 2a * D(a) * D(b)
Implementation:
C++
350
Chapter 60. Last non-zero digit of a factorial
Java
351
Chapter 60. Last non-zero digit of a factorial
Python3
352
Chapter 60. Last non-zero digit of a factorial
print(lastNon0Digit(n))
# This code is contributed
# by Anant Agarwal.
C#
PHP
<?php
353
Chapter 60. Last non-zero digit of a factorial
Output:
Source
https://www.geeksforgeeks.org/last-non-zero-digit-factorial/
354
Chapter 61
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion) - GeeksforGeeks
Given Preorder traversal of a Binary Search Tree. Then the task is print leaf nodes of the
Binary Search Tree from the given preorder.
Examples :
Input : preorder[] = { 3, 2, 4 };
Output : 2 4
In this post, a simple recursive solution is discussed. The idea is to use two min and
max variables and taking i (index in input array), the index for given preorder array, and
recursively creating root node and correspondingly checking if left and right are existing
or not. This method return boolean variable, and if both left and right are false it simply
means that left and right are null hence it must be a leaf node so print it right there and
return back true as root at that index existed.
355
Chapter 61. Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
C++
PHP
<?php
356
Chapter 61. Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Output :
357
Chapter 61. Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Improved By : jit_t
Source
https://www.geeksforgeeks.org/leaf-nodes-preorder-binary-search-treeusing-recursion/
358
Chapter 62
Method 1 (Recursive)
This problem can bee seen as an extension of the level order traversal post.
To print the nodes in spiral order, nodes at different levels should be printed in alternating
order. An additional Boolean variable ltr is used to change printing order of levels. If ltr is
1 then printGivenLevel() prints nodes from left to right else from right to left. Value of ltr
is flipped in each iteration to change the order.
Function to print level order traversal of tree
printSpiral(tree)
bool ltr = 0;
for d = 1 to height(tree)
printGivenLevel(tree, d, ltr);
ltr ~= ltr /*flip ltr*/
359
Chapter 62. Level order traversal in spiral form
360
Chapter 62. Level order traversal in spiral form
printGivenLevel(root, i, ltr);
/*Revert ltr to traverse next level in opposite order*/
ltr = !ltr;
}
}
/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level, int ltr)
{
if(root == NULL)
return;
if(level == 1)
printf("%d ", root->data);
else if (level > 1)
{
if(ltr)
{
printGivenLevel(root->left, level-1, ltr);
printGivenLevel(root->right, level-1, ltr);
}
else
{
printGivenLevel(root->right, level-1, ltr);
printGivenLevel(root->left, level-1, ltr);
}
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node->left);
int rheight = height(node->right);
/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
361
Chapter 62. Level order traversal in spiral form
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
printf("Spiral Order traversal of binary tree is \n");
printSpiral(root);
return 0;
}
Java
362
Chapter 62. Level order traversal in spiral form
class BinaryTree
{
Node root;
// Function to print the spiral traversal of tree
void printSpiral(Node node)
{
int h = height(node);
int i;
/* ltr -> left to right. If this variable is set then the
given label is transversed from left to right */
boolean ltr = false;
for (i = 1; i <= h; i++)
{
printGivenLevel(node, i, ltr);
/*Revert ltr to traverse next level in opposite order*/
ltr = !ltr;
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node node)
{
if (node == null)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node.left);
int rheight = height(node.right);
/* use the larger one */
if (lheight > rheight)
return (lheight + 1);
else
return (rheight + 1);
}
}
/* Print nodes at a given level */
void printGivenLevel(Node node, int level, boolean ltr)
{
363
Chapter 62. Level order traversal in spiral form
Output:
Time Complexity: Worst case time complexity of the above method is O(n^2). Worst
case occurs in case of skewed trees.
Method 2 (Iterative)
We can print spiral order traversal in O(n) time and O(n) extra space. The idea is to use
two stacks. We can use one stack for printing from left to right and other stack for printing
from right to left. In every iteration, we have nodes of one level in one of the stacks. We
364
Chapter 62. Level order traversal in spiral form
print the nodes, and push nodes of next level in other stack.
C++
365
Chapter 62. Level order traversal in spiral form
{
struct node *temp = s2.top();
s2.pop();
cout << temp->data << " ";
// Note that is left is pushed before right
if (temp->left)
s1.push(temp->left);
if (temp->right)
s1.push(temp->right);
}
}
}
// A utility function to create a new node
struct node* newNode(int data)
{
struct node* node = new struct node;
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
cout << "Spiral Order traversal of binary tree is \n";
printSpiral(root);
return 0;
}
Java
366
Chapter 62. Level order traversal in spiral form
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
static Node root;
void printSpiral(Node node)
{
if (node == null)
return; // NULL check
// Create two stacks to store alternate levels
Stack<Node> s1 = new Stack<Node>();// For levels to be printed from right to left
Stack<Node> s2 = new Stack<Node>();// For levels to be printed from left to right
// Push first level to first stack 's1'
s1.push(node);
// Keep ptinting while any of the stacks has some nodes
while (!s1.empty() || !s2.empty())
{
// Print nodes of current level from s1 and push nodes of
// next level to s2
while (!s1.empty())
{
Node temp = s1.peek();
s1.pop();
System.out.print(temp.data + " ");
// Note that is right is pushed before left
if (temp.right != null)
s2.push(temp.right);
if (temp.left != null)
s2.push(temp.left);
}
367
Chapter 62. Level order traversal in spiral form
// Print nodes of current level from s2 and push nodes of
// next level to s1
while (!s2.empty())
{
Node temp = s2.peek();
s2.pop();
System.out.print(temp.data + " ");
// Note that is left is pushed before right
if (temp.left != null)
s1.push(temp.left);
if (temp.right != null)
s1.push(temp.right);
}
}
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(7);
tree.root.left.right = new Node(6);
tree.root.right.left = new Node(5);
tree.root.right.right = new Node(4);
System.out.println("Spiral Order traversal of Binary Tree is ");
tree.printSpiral(root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output:
Please write comments if you find any bug in the above program/algorithm; or if you want
to share more information about spiral traversal.
Source
https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/
368
Chapter 63
Level order traversal with direction change after every two levels | Recursive Approach -
GeeksforGeeks
Given a binary tree, print the level order traversal in such a way that first two levels are
printed from left to right, next two levels are printed from right to left, then next two from
left to right and so on. So, the problem is to reverse the direction of level order traversal of
the binary tree after every two levels.
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ / \ / \ / \
8 9 3 1 4 2 7 2
/ / \ \
16 17 18 19
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
369
Chapter 63. Level order traversal with direction change after every two levels | Recursive
Approach
Approach: In the previous post, level order traversal using queue and stack has been done
to print the elements. A recursive method has been used over here to print the elements
in every level. Traverse every level in the tree, for every level, check the direction. Use a
flag to know the direction of traversal in the tree. If the flag is set to true, print the nodes
from right to left in the particular level. If the flag is set to false, print the nodes in that
level from left to right. Initially, the flag is set to False, after every 2 levels, flag changes its
value to true and vice versa.
Below is the implementation of the above approach.
370
Chapter 63. Level order traversal with direction change after every two levels | Recursive
Approach
else {
// If the flag is true, we have to print
// level from RIGHT to LEFT.
if (flag) {
printCurrLevel(root->right, level - 1, flag);
printCurrLevel(root->left, level - 1, flag);
}
// If the flag is false, we have to print
// level from LEFT to RIGHT.
else {
printCurrLevel(root->left, level - 1, flag);
printCurrLevel(root->right, level - 1, flag);
}
}
}
// This function returns the height of tree.
int height(node* root)
{
if (!root)
return 0;
// left subtree
int lh = height(root->left);
// right subtree
int rh = height(root->right);
return 1 + max(lh, rh);
}
// Fucntion to traverse level-wise and
// print nodes
void modifiedLevelOrder(node* root)
{
int h = height(root);
// Variable to choose direction.
bool flag = false;
for (int i = 1; i <= h; i++) {
printCurrLevel(root, i, flag);
cout << endl;
// change direction after every two levels.
if (i % 2 == 0)
flag = !flag;
}
371
Chapter 63. Level order traversal with direction change after every two levels | Recursive
Approach
}
// Driver Code
int main()
{
// create tree that is given
// in the example
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(3);
root->left->right->right = newNode(1);
root->right->left->left = newNode(4);
root->right->left->right = newNode(2);
root->right->right->left = newNode(7);
root->right->right->right = newNode(2);
root->left->right->left->left = newNode(16);
root->left->right->left->right = newNode(17);
root->right->left->right->left = newNode(18);
root->right->right->left->right = newNode(19);
modifiedLevelOrder(root);
return 0;
}
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
Source
https://www.geeksforgeeks.org/level-order-traversal-with-direction-change-after-every-two-levels-recursive-approac
372
Chapter 64
Lexicographically Kth smallest way to reach given coordinate from origin - GeeksforGeeks
Given a coordinate (x, y) on a 2D plane. We have to reach (x, y) from the current position
which is at origin i.e (0, 0). In each step, we can either move vertically or horizontally on
the plane. While moving horizontally each step we write ‘H’ and while moving vertically
each step we write ‘V’. So, there can be possibly many strings containing ‘H’ and ‘V’ which
represents a path from (0, 0) to (x, y). The task is to find the lexicographically Kth smallest
string among all the possible strings.
Examples:
Input: x = 2, y = 2, k = 2
Output: HVVH
Explanation: There are 6 ways to reach (2, 2) from (0, 0). The possible
list of strings in lexicographically sorted order: [“HHVV”, “HVHV”, “HVVH”,
“VHHV”, “VHVH”, “VVHH”]. Hence, the lexicographically 2nd smallest string
is HVHV.
Input : x = 2, y = 2, k = 3
Output : VHHV
373
Chapter 64. Lexicographically Kth smallest way to reach given coordinate from origin
have already made a step in the vertical direction, so 1 is subtracted from y. Since ‘H’ is
lexicographically smaller than ‘V’, so among all stringsa starting strings will contains ‘H’ in
the beginning i.e inital movements will be Horizontal.
So, if K <= x + y – 1 Cx – 1 , we will take ‘H’ as first step else we will take ‘V’ as first step
and solve for number of goings to (x, y) from(1, 0) will be K = K – x + y – 1 Cx – 1 .
Below is the implementation of this approach:
C++
374
Chapter 64. Lexicographically Kth smallest way to reach given coordinate from origin
Java
375
Chapter 64. Lexicographically Kth smallest way to reach given coordinate from origin
376
Chapter 64. Lexicographically Kth smallest way to reach given coordinate from origin
System.out.print("V");
// recursive call to
// take next step.
Ksmallest(x, y, k);
}
// If on x-axis
else if (y == 0)
{
// decrement x.
x--;
// Move horizontal.
System.out.print("H");
// recursive call to
// take next step.
Ksmallest(x, y, k);
}
else
{
// If x + y C x is
// greater than K
if (factorial(x - 1, y) > k)
{
// Move Horizontal
System.out.print( "H");
// recursive call to
// take next step.
Ksmallest(x - 1, y, k);
}
else
{
// Move vertical
System.out.print("V");
// recursive call to
// take next step.
Ksmallest(x, y - 1, k -
factorial(x - 1, y));
}
}
}
// Driver Code
public static void main (String[] args)
377
Chapter 64. Lexicographically Kth smallest way to reach given coordinate from origin
{
int x = 2, y = 2, k = 2;
Ksmallest(x, y, k);
}
}
// This code is contributed
// by anuj_67.
Output
HVVH
Improved By : vt_m
Source
https://www.geeksforgeeks.org/lexicographically-kth-smallest-way-reach-given-coordinate-origin/
378
Chapter 65
In below diagram binary tree with longest consecutive path(LCP) are shown :
We can solve above problem recursively. At each node we need information of its parent
node, if current node has value one more than its parent node then it makes a consecutive
path, at each node we will compare node’s value with its parent value and update the longest
consecutive path accordingly.
For getting the value of parent node, we will pass the (node_value + 1) as an argument
to the recursive method and compare the node value with this argument value, if satisfies,
update the current length of consecutive path otherwise reinitialize current path length by
1.
Please see below code for better understanding :
379
Chapter 65. Longest consecutive sequence in Binary tree
struct Node
{
int data;
Node *left, *right;
};
// A utility function to create a node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Utility method to return length of longest
// consecutive sequence of tree
void longestConsecutiveUtil(Node* root, int curLength,
int expected, int& res)
{
if (root == NULL)
return;
// if root data has one more than its parent
// then increase current length
if (root->data == expected)
curLength++;
else
curLength = 1;
// update the maximum by current length
res = max(res, curLength);
// recursively call left and right subtree with
// expected value 1 more than root data
longestConsecutiveUtil(root->left, curLength,
root->data + 1, res);
longestConsecutiveUtil(root->right, curLength,
root->data + 1, res);
}
// method returns length of longest consecutive
// sequence rooted at node root
int longestConsecutive(Node* root)
{
if (root == NULL)
return 0;
380
Chapter 65. Longest consecutive sequence in Binary tree
int res = 0;
// call utility method with current length 0
longestConsecutiveUtil(root, 0, root->data, res);
return res;
}
// Driver code to test above methods
int main()
{
Node* root = newNode(6);
root->right = newNode(9);
root->right->left = newNode(7);
root->right->right = newNode(10);
root->right->right->right = newNode(11);
printf("%d\n", longestConsecutive(root));
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/longest-consecutive-sequence-binary-tree/
381
Chapter 66
Input: N = 7, M = 3, K = 1
arr[] = {2, 10, 7, 18, 5, 33, 0};
Output: 61
Explanation: subsets are: 33, 18, 10 (3 subsets of size 1)
Input: N = 4, M = 2, K = 2
arr[] = {3, 2, 100, 1};
Output: 106
Explanation: subsets are: (3, 2), (100, 1) 2 subsets of size 2
Here we can see that the the we need to find M subarrays each of size K so,
1. We create a presum array, which contains in each index sum of all elements from ‘index‘
to ‘index + K’ in the given array. And size of the sum array will be n+1-k.
2. Now if we include the subarray of size k, then we can not include any of the elements of
that subarray again in any other subarray as it will create overlapping subarrays. So we
make recursive call by excluding the k elements of included subarray.
3. if we exclude a subarray then we can use the next k-1 elements of that subarray in other
subarrays so we will make recursive call by just excluding the first element of that subarray.
4. At last return the max(included sum, excluded sum).
382
Chapter 66. Max sum of M non-overlapping subarrays of size K
C++
383
Chapter 66. Max sum of M non-overlapping subarrays of size K
Java
384
Chapter 66. Max sum of M non-overlapping subarrays of size K
385
Chapter 66. Max sum of M non-overlapping subarrays of size K
C#
386
Chapter 66. Max sum of M non-overlapping subarrays of size K
Output :
61
Improved By : vt_m
387
Chapter 66. Max sum of M non-overlapping subarrays of size K
Source
https://www.geeksforgeeks.org/max-sum-of-m-non-overlapping-subarrays-of-size-k/
388
Chapter 67
389
Chapter 67. Maximize array elements upto given number
or subtract current array element from value obtained so far from previous elements. Start
from index 0, add or subtract arr[0] from given number and recursively call for next index
along with updated number. When entire array is traversed, compare the updated number
with overall maximum value of number obtained so far.
Below is the implementation of above approach :
C++
390
Chapter 67. Maximize array elements upto given number
Java
391
Chapter 67. Maximize array elements upto given number
392
Chapter 67. Maximize array elements upto given number
Python3
393
Chapter 67. Maximize array elements upto given number
# def to find maximum possible
# value that can be obtained using
# array elements and given number.
def findMaxVal(arr, n, num, maxLimit) :
global ans
# variable to store
# current index position.
ind = 0
# call to utility def to
# find maximum possible value
# that can be obtained.
findMaxValUtil(arr, n, num, maxLimit, ind)
return ans
# Driver code
num = 1
arr = [3, 10, 6, 4, 5]
n = len(arr)
maxLimit = 15
print (findMaxVal(arr, n, num, maxLimit))
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
394
Chapter 67. Maximize array elements upto given number
395
Chapter 67. Maximize array elements upto given number
int n = arr.Length;
int maxLimit = 15;
Console.Write(findMaxVal(arr, n, num,
maxLimit));
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP code to find maximum
// value of number obtained by
// using array elements recursively.
// Utility function to find
// maximum possible value
function findMaxValUtil($arr, $n,
$num, $maxLimit,
$ind, &$ans)
{
// If entire array is traversed,
// then compare current value
// in num to overall maximum
// obtained so far.
if ($ind == $n)
{
$ans = max($ans, $num);
return;
}
// Case 1: Subtract current element
// from value so far if result is
// greater than or equal to zero.
if ($num - $arr[$ind] >= 0)
{
findMaxValUtil($arr, $n,
$num - $arr[$ind],
$maxLimit, $ind + 1,
$ans);
}
// Case 2 : Add current element to
// value so far if result is less
// than or equal to maxLimit.
396
Chapter 67. Maximize array elements upto given number
Output:
397
Chapter 67. Maximize array elements upto given number
A boolean DP table can be created in which dp[i][j] is 1 if value j can be obtained using
arr[0..i] and 0 if not. For each index position, start from j = 0 and move to value maxLimit,
and set dp[i][j] either 0 or 1 as described above. Find the maximum possible value that can
be obtained at index position n-1 by finding maximum j when i = n-1 and dp[n-1][j] = 1.
C++
398
Chapter 67. Maximize array elements upto given number
399
Chapter 67. Maximize array elements upto given number
dp[ind][val] = dp[ind-1][val+arr[ind]];
}
else
{
dp[ind][val] = 0;
}
}
}
}
// Find maximum value that is obtained
// at index n-1.
for(val = maxLimit; val >= 0; val--)
{
if(dp[n-1][val])
{
return val;
}
}
// If no solution exists return -1.
return -1;
}
// Driver Code
int main()
{
int num = 1;
int arr[] = {3, 10, 6, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int maxLimit = 15;
cout << findMaxVal(arr, n, num, maxLimit);
return 0;
}
Java
400
Chapter 67. Maximize array elements upto given number
401
Chapter 67. Maximize array elements upto given number
402
Chapter 67. Maximize array elements upto given number
// If no solution
// exists return -1.
return -1;
}
// Driver Code
public static void main(String args[])
{
int num = 1;
int []arr = new int[]{3, 10, 6, 4, 5};
int n = arr.length;
int maxLimit = 15;
System.out.print(findMaxVal(arr, n,
num, maxLimit));
}
}
// This code is contributed
// by Manish Shaw(manishshaw1)
C#
403
Chapter 67. Maximize array elements upto given number
404
Chapter 67. Maximize array elements upto given number
}
else if(val - arr[ind] >= 0)
{
dp[ind,val] = dp[ind-1,val-arr[ind]];
}
else if(val + arr[ind] <= maxLimit)
{
dp[ind,val] = dp[ind-1,val+arr[ind]];
}
else
{
dp[ind,val] = 0;
}
}
}
}
// Find maximum value that is obtained
// at index n-1.
for(val = maxLimit; val >= 0; val--)
{
if(dp[n-1,val] == 1)
{
return val;
}
}
// If no solution exists return -1.
return -1;
}
// Driver Code
static void Main()
{
int num = 1;
int []arr = new int[]{3, 10, 6, 4, 5};
int n = arr.Length;
int maxLimit = 15;
Console.Write(
findMaxVal(arr, n, num, maxLimit));
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
Output:
405
Chapter 67. Maximize array elements upto given number
Time Complexity : O(n*maxLimit), where n is the size of array and maxLimit is the
given max value.
Auxiliary Space : O(n*maxLimit), n is the size of array and maxLimit is the given max
value.
Optimization : The space required can be reduced to O(2*maxLimit). Note that at every
index position, we are only using values from previous row. So we can create a table with
two rows, in which one of the rows store result for previous iteration and other for the
current iteration.
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/maximize-array-elements-upto-given-number/
406
Chapter 68
Approach:
407
Chapter 68. Maximum length of segments of 0’s and 1’s
5. Else only recursively call the function for next index k+1.
6. Return dp[start].
408
Chapter 68. Maximum length of segments of 0’s and 1’s
// Driver Code
int main()
{
string adj = "100110001010001";
// Size of string
int n = adj.size();
int dp[n + 1];
memset(dp, -1, sizeof(dp));
// Calling the function to find the value of function
cout << find(0, adj, n, dp) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximum-length-of-segments-of-0s-and-1s/
409
Chapter 69
1. Tabulation: Bottom Up
2. Memoization: Top Down
One of the easier approaches to solve most of the problems in DP is to write the recursive
code at first and then write the Bottom-up Tabulation Method or Top-down Memoization
of the recursive function. The steps to write the DP solution of Top-down approach to any
problem is to:
1-D Memoization
The first step will be to write the recursive code. In the program below, a program related
to recursion where only one parameter changes its value has been shown. Since only one
parameter is non-constant, this method is known as 1-D memoization. E.g., the Fibonacci
series problem to find the N-th term in the Fibonacci series. The recursive approach has
been discussed over here.
Given below is the recursive code to find the N-th term:
C++
410
Chapter 69. Memoization (1D, 2D and 3D)
Java
411
Chapter 69. Memoization (1D, 2D and 3D)
}
}
// This code is contributed
// by ajit
C#
// C# program to find
// the Nth term of
// Fibonacci series
using System;
class GFG
{
// Fibonacci Series
// using Recursion
static int fib(int n)
{
// Base case
if (n <= 1)
return n;
// recursive calls
return fib(n - 1) +
fib(n - 2);
}
// Driver Code
static public void Main ()
{
int n = 6;
Console.WriteLine(fib(n));
}
}
// This code is contributed
// by akt_mit
PHP
<?php
// PHP program to find
// the Nth term of
// Fibonacci series
// using Recursion
412
Chapter 69. Memoization (1D, 2D and 3D)
function fib($n)
{
// Base case
if ($n <= 1)
return $n;
// recursive calls
return fib($n - 1) +
fib($n - 2);
}
// Driver Code
$n = 6;
echo fib($n);
// This code is contributed
// by ajit
?>
Output:
A common observation is that this implementation does a lot of repeated work (see the
following recursion tree). So this will consume a lot of time for finding the N-th Fibonacci
number if done.
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)
In the above tree fib(3), fib(2), fib(1), fib(0) all are called more then once.
413
Chapter 69. Memoization (1D, 2D and 3D)
the value of fib(x) in an array term at index x and return term[x]. By memoizing
the return value of fib(x) at index x of an array, reduce the number of recursive calls at
the next step when fib(x) has already been called. So without doing further recursive calls
to compute the value of fib(x), return term[x] when fib(x) has already been computed
previously to avoid a lot of repeated work as shown in the tree.
Given below is the memoized recursive code to find the N-th term.
C++
414
Chapter 69. Memoization (1D, 2D and 3D)
Java
415
Chapter 69. Memoization (1D, 2D and 3D)
System.out.println(fib(n));
}
}
// This code is contributed by ajit
Output:
If the recursive code has been written once, then memoization is just modifying the recursive
program and storing the return values to avoid repetitive calls of functions which have been
computed previously.
2-D Memoization
In the above program, the recursive function had only one argument whose value was
not constant after every function call. Below, an implementation where the recursive
program has two non-constant arguments has been shown.
For e.g., Program to solve the standard Dynamic Problem LCS problem when two strings are
given. The general recursive solution of the problem is to generate all subsequences of both
given sequences and find the longest matching subsequence. Total possible combinations
will be 2n . Hence recursive solution will take O(2n ). The approach to write the recursive
solution has been discussed here.
Given below is the recursive solution to the LCS problem:
C++
416
Chapter 69. Memoization (1D, 2D and 3D)
Output:
Length of LCS is 4n
Output:
Length of LCS is 4
Considering the above implementation, the following is a partial recursion tree for input
strings “AXYT” and “AYZX”
lcs("AXYT", "AYZX")
/ \
lcs("AXY", "AYZX") lcs("AXYT", "AYZ")
/ \ / \
lcs("AX", "AYZX") lcs("AXY", "AYZ") lcs("AXY", "AYZ") lcs("AXYT", "AY")
In the above partial recursion tree, lcs(“AXY”, “AYZ”) is being solved twice. On
drawing the complete recursion tree, it has been observed that there are many subproblems
which are solved again and again. So this problem has Overlapping Substructure property
and recomputation of same subproblems can be avoided by either using Memoization or
Tabulation. The tabulation method has been discussed here.
A common point of observation to use memoization in the recursive code will be the two
non-constant arguments M and N in every function call. The function has 4 arguments,
but 2 arguments are constant which do not affect the Memoization. The repetitive calls occur
417
Chapter 69. Memoization (1D, 2D and 3D)
for N and M which have been called previously. So use a 2-D array to store the computed
lcs(m, n) value at arr[m-1][n-1] as the string index starts from 0. Whenever the function
with the same argument m and n are called again, we do not perform any further recursive
call and return arr[m-1][n-1] as the previous computation of the lcs(m, n) has already been
stored in arr[m-1][n-1], hence reducing the recursive calls that happen more then once.
Below is the implementation of the Memoization approach of the recursive code.
C++
418
Chapter 69. Memoization (1D, 2D and 3D)
Output:
Length of LCS is 4
3-D Memoization
In the above program, the recursive function had only two arguments whose value were not
constant after every function call. Below, an implementation where the recursive program
has three non-constant arguments is done.
For e.g., Program to solve the standard Dynamic Problem LCS problem for three strings.
The general recursive solution of the problem is to generate all subsequences of both given
sequences and find the longest matching subsequence. Total possible combinations will be
3n . Hence recursive solution will take O(3n ).
Given below is the recursive solution to the LCS problem:
C++
419
Chapter 69. Memoization (1D, 2D and 3D)
if (m == 0 || n == 0 || o == 0)
return 0;
// if equal, then check for next combination
if (X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]) {
// recursive call
return 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1);
}
else {
// return the maximum of the three other
// possible states in recursion
return max(lcs(X, Y, Z, m, n - 1, o),
max(lcs(X, Y, Z, m - 1, n, o),
lcs(X, Y, Z, m, n, o - 1)));
}
}
// Utility function to get max of 2 integers
int max(int a, int b)
{
return (a > b) ? a : b;
}
// Driver Code
int main()
{
char X[] = "geeks";
char Y[] = "geeksfor";
char Z[] = "geeksforge";
int m = strlen(X);
int n = strlen(Y);
int o = strlen(Z);
printf("Length of LCS is %d", lcs(X, Y, Z, m, n, o));
return 0;
}
Output:
Length of LCS is 5
The tabulation method has been shown here. On drawing the recursion tree completely, it
has been noticed that there are many overlapping sub-problems which are been calculated
420
Chapter 69. Memoization (1D, 2D and 3D)
multiple times. Since the function parameter has three non-constant parameters, hence a
3-D array will be used to memoize the value that was returned when lcs(x, y, z, m, n,
o) for any value of m, n and o was called so that if lcs(x, y, z, m, n, o) is again called
for the same value of m, n and o then the function will return the already stored value as
it has been computed previously in the recursive call. arr[m][n][o] stores the value returned
by the lcs(x, y, z, m, n, o) function call. The only modification that needs to be done in
the recursive program is to store the return value of (m, n, o) state of the recursive function.
The rest remains the same in the above recursive program.
Below is the implementation of the Memoization approach of the recursive code:
C++
421
Chapter 69. Memoization (1D, 2D and 3D)
lcs(X, Y, Z, m, n, o - 1)));
return arr[m - 1][n - 1][o - 1];
}
}
// Utility function to get max of 2 integers
int max(int a, int b)
{
return (a > b) ? a : b;
}
// Driver Code
int main()
{
memset(arr, -1, sizeof(arr));
char X[] = "geeks";
char Y[] = "geeksfor";
char Z[] = "geeksforgeeks";
int m = strlen(X);
int n = strlen(Y);
int o = strlen(Z);
printf("Length of LCS is %d", lcs(X, Y, Z, m, n, o));
return 0;
}
Output:
Length of LCS is 5
Note: The array used to Memoize is initialized to some value (say -1) before the function
call to mark if the function with the same parameters has been previously called or not.
Improved By : jit_t
Source
https://www.geeksforgeeks.org/memoization-1d-2d-and-3d/
422
Chapter 70
<script>
// Create Node of LinkedList
function Node(data) {
this.node = data;
this.next = null;
}
// To initialize a linkedlist
function LinkedList(list) {
this.head = list || null
}
// Function to insert The new Node into the linkedList
423
Chapter 70. Merge Sort for Linked Lists in JavaScript
LinkedList.prototype.insert = function(data) {
// Check if the linked list is empty
// so insert first node and lead head
// points to generic node
if (this.head === null)
this.head = new Node(data);
else {
// If linked list is not empty, insert the node
// at the end of the linked list
let list = this.head;
while (list.next) {
list = list.next;
}
// Now here list pointer points to last
// node let’s insert out new node in it
list.next = new Node(data)
}
}
// Function to print linkedList
LinkedList.prototype.iterate = function() {
// First we will check whether out
// linked list is empty or node
if (this.head === null)
return null;
// If linked list is not empty we will
// iterate from each Node and prints
// it’s value store in “data” property
let list = this.head;
// we will iterate until our list variable
// contains the “Next” value of the last Node
// i.e-> null
while (list) {
document.write(list.node)
if (list.next)
document.write(' -> ')
list = list.next
}
}
424
Chapter 70. Merge Sort for Linked Lists in JavaScript
425
Chapter 70. Merge Sort for Linked Lists in JavaScript
426
Chapter 70. Merge Sort for Linked Lists in JavaScript
l.insert(3)
l.insert(2)
l.insert(1)
// Print the linked list
l.iterate()
// Sort the linked list
l.head = LinkedList.prototype.mergeSort(l.head)
document.write('<br> After sorting : ');
// Print the sorted linked list
l.iterate()
</script>
Output
Source
https://www.geeksforgeeks.org/merge-sort-linked-lists-javascript/
427
Chapter 71
428
Chapter 71. Minimum steps to reach a destination
of steps INT_MAX, so that when i take the minimum of both possibilities, this one gets
eliminated.
If we don’t use this last step, the program enters into an INFINITE recursion and gives
RUN TIME ERROR.
Below is the implementation of above idea. Note that the solution only counts steps.
C++
429
Chapter 71. Minimum steps to reach a destination
return 0;
}
Java
430
Chapter 71. Minimum steps to reach a destination
Python3
431
Chapter 71. Minimum steps to reach a destination
# This code is contributed by Sam007.
C#
432
Chapter 71. Minimum steps to reach a destination
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to count number
// of steps to reach a point
// Function to count number
// of steps required to reach
// a destination
// source -> source vertex
// step -> value of last step taken
// dest -> destination vertex
function steps($source, $step, $dest)
{
// base cases
if (abs($source) > ($dest))
return PHP_INT_MAX;
if ($source == $dest)
return $step;
// at each point we
// can go either way
// if we go on positive side
$pos = steps($source + $step + 1,
$step + 1, $dest);
// if we go on negative side
$neg = steps($source - $step - 1,
$step + 1, $dest);
// minimum of both cases
return min($pos, $neg);
}
// Driver code
$dest = 11;
echo "No. of steps required to reach ",
$dest, " is ", steps(0, 0, $dest);
// This code is contributed by aj_36
?>
433
Chapter 71. Minimum steps to reach a destination
Output :
Source
https://www.geeksforgeeks.org/minimum-steps-to-reach-a-destination/
434
Chapter 72
Input : N = 5, M = 6.
Output : 9
Area of 5 X 6 can be covered with minimum 9 tiles.
6 tiles of 1 X 1, 2 tiles of 2 X 2, 1 tile of 4 X 4.
Input : N = 10, M = 5.
Output : 14
435
Chapter 72. Minimum tiles of sizes in powers of two to cover whole area
C++
#include<bits/stdc++.h>
using namespace std;
int minTiles(int n, int m)
{
// base case, when area is 0.
if (n == 0 || m == 0)
return 0;
// If n and m both are even, calculate tiles for n/2 x m/2
// Halving both dimensions doesn't change the number of tiles
else if (n%2 == 0 && m%2 == 0)
return minTiles(n/2, m/2);
// If n is even and m is odd
// Use a row of 1x1 tiles
else if (n%2 == 0 && m%2 == 1)
return (n + minTiles(n/2, m/2));
// If n is odd and m is even
// Use a column of 1x1 tiles
else if (n%2 == 1 && m%2 == 0)
return (m + minTiles(n/2, m/2));
// If n and m are odd
// add row + column number of tiles
else
return (n + m - 1 + minTiles(n/2, m/2));
}
// Driven Program
int main()
{
int n = 5, m = 6;
cout << minTiles(n, m) << endl;
return 0;
}
Java
436
Chapter 72. Minimum tiles of sizes in powers of two to cover whole area
// whole area
class GFG {
static int minTiles(int n, int m)
{
// base case, when area is 0.
if (n == 0 || m == 0)
return 0;
// If n and m both are even,
// calculate tiles for n/2 x m/2
// Halving both dimensions doesn't
// change the number of tiles
else if (n % 2 == 0 && m % 2 == 0)
return minTiles(n / 2, m / 2);
// If n is even and m is odd
// Use a row of 1x1 tiles
else if (n % 2 == 0 && m % 2 == 1)
return (n + minTiles(n / 2, m / 2));
// If n is odd and m is even
// Use a column of 1x1 tiles
else if (n % 2 == 1 && m % 2 == 0)
return (m + minTiles(n / 2, m / 2));
// If n and m are odd
// add row + column number of tiles
else
return (n + m - 1 + minTiles(n / 2, m / 2));
}
// Driver code
public static void main (String[] args)
{
int n = 5, m = 6;
System.out.println(minTiles(n, m));
}
}
// This code is contributed by Anant Agarwal.
Python3
437
Chapter 72. Minimum tiles of sizes in powers of two to cover whole area
if n == 0 or m == 0:
return 0
# If n and m both are even, calculate
# tiles for n/2 x m/2
# Halfing both dimensions doesn't
# change the number of tiles
elif n%2 == 0 and m%2 == 0:
return minTiles(int(n/2), int(m/2))
# If n is even and m is odd
# Use a row of 1x1 tiles
elif n % 2 == 0 and m % 2 == 1:
return (n + minTiles(int(n/2), int(m/2)))
# If n is odd and m is even
# Use a column of 1x1 tiles
elif n % 2 == 1 and m % 2 == 0:
return (m + minTiles(int(n/2), int(m/2)))
# If n and m are odd add
# row + column number of tiles
else:
return (n + m - 1 + minTiles(int(n/2), int(m/2)))
# Driven Program
n = 5
m = 6
print (minTiles(n, m))
# This code is contributed
# by Shreyanshi Arun.
C#
438
Chapter 72. Minimum tiles of sizes in powers of two to cover whole area
// If n and m both are even,
// calculate tiles for n/2 x m/2
// Halving both dimensions doesn't
// change the number of tiles
else if (n % 2 == 0 && m % 2 == 0)
return minTiles(n / 2, m / 2);
// If n is even and m is odd
// Use a row of 1x1 tiles
else if (n % 2 == 0 && m % 2 == 1)
return (n + minTiles(n / 2, m / 2));
// If n is odd and m is even
// Use a column of 1x1 tiles
else if (n % 2 == 1 && m % 2 == 0)
return (m + minTiles(n / 2, m / 2));
// If n and m are odd
// add row + column number of tiles
else
return (n + m - 1 + minTiles(n / 2, m / 2));
}
// Driver code
public static void Main()
{
int n = 5, m = 6;
Console.WriteLine(minTiles(n, m));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program for Minimum tiles of
// sizes in powers of two to cover
// whole area
function minTiles($n, $m)
{
// base case, when area is 0.
if ($n == 0 or $m == 0)
return 0;
439
Chapter 72. Minimum tiles of sizes in powers of two to cover whole area
// If n and m both are even,
// calculate tiles for n/2 x m/2
// Halving both dimensions doesn't
// change the number of tiles
else if ($n % 2 == 0 and
$m % 2 == 0)
return minTiles($n / 2, $m / 2);
// If n is even and m is odd
// Use a row of 1x1 tiles
else if ($n % 2 == 0 and $m % 2 == 1)
return floor($n + minTiles($n / 2,
$m / 2));
// If n is odd and m is even
// Use a column of 1x1 tiles
else if ($n % 2 == 1 and
$m % 2 == 0)
return ($m + minTiles($n / 2,
$m / 2));
// If n and m are odd
// add row + column number of tiles
else
return floor($n + $m - 1 +
minTiles($n / 2, $m / 2));
}
// Driver Code
$n = 5; $m = 6;
echo minTiles($n, $m);
// This code is contributed by anuj_67.
?>
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/minimum-tiles-of-sizes-in-powers-of-two-to-cover-whole-area/
440
Chapter 73
Modular exponentiation
(Recursive)
Input : a = -3 b = 5 c = 89
Output : 24
441
Chapter 73. Modular exponentiation (Recursive)
Note:
Also as the product of (a ^ b/2) * (a ^ b/2) and a * (a ^( b-1) may cause overflow, hence
we must be careful about those scenarios
Java
442
Chapter 73. Modular exponentiation (Recursive)
class GFG
{
static int exponentMod(int A,
int B, int C)
{
// Base cases
if (A == 0)
return 0;
if (B == 0)
return 1;
// If B is even
long y;
if (B % 2 == 0)
{
y = exponentMod(A, B / 2, C);
y = (y * y) % C;
}
// If B is odd
else
{
y = A % C;
y = (y * exponentMod(A, B - 1,
C) % C) % C;
}
return (int)((y + C) % C);
}
// Driver Code
public static void main(String args[])
{
int A = 2, B = 5, C = 13;
System.out.println("Power is " +
exponentMod(A, B, C));
}
}
// This code is contributed
// by Swetank Modi.
Python3
443
Chapter 73. Modular exponentiation (Recursive)
# Base Cases
if (A == 0):
return 0
if (B == 0):
return 1
# If B is Even
y = 0
if (B % 2 == 0):
y = exponentMod(A, B / 2, C)
y = (y * y) % C
# If B is Odd
else:
y = A % C
y = (y * exponentMod(A, B - 1,
C) % C) % C
return ((y + C) % C)
# Driver Code
A = 2
B = 5
C = 13
print("Power is", exponentMod(A, B, C))
# This code is contributed
# by Swetank Modi.
C#
// Recursive C# program
// to compute modular power
class GFG
{
static int exponentMod(int A, int B, int C)
{
// Base cases
if (A == 0)
return 0;
if (B == 0)
return 1;
// If B is even
long y;
if (B % 2 == 0)
{
444
Chapter 73. Modular exponentiation (Recursive)
PHP
<?php
// Recursive PHP program to
// compute modular power
function exponentMod($A, $B, $C)
{
// Base cases
if ($A == 0)
return 0;
if ($B == 0)
return 1;
// If B is even
if ($B % 2 == 0)
{
$y = exponentMod($A, $B / 2, $C);
$y = ($y * $y) % $C;
}
// If B is odd
445
Chapter 73. Modular exponentiation (Recursive)
else
{
$y = $A % $C;
$y = ($y * exponentMod($A, $B - 1,
$C) % $C) % $C;
}
return (($y + $C) % $C);
}
// Driver Code
$A = 2;
$B = 5;
$C = 13;
echo "Power is " . exponentMod($A, $B, $C);
// This code is contributed
// by Swetank Modi.
?>
Output:
Power is 6
Source
https://www.geeksforgeeks.org/modular-exponentiation-recursive/
446
Chapter 74
Input : 5
Output : 0 1 4 5 16
Input : 10
Output : 0 1 4 5 16 17 20 21 64 65
It is observed that the terms of the sequence follow the recurrence relation :
1) S(2 * n) = 4 * S(n)
2) S(2 * n + 1) = 4 * S(n) + 1
with S(0) = 0 and S(1) = 1
It may be noted here that any number which is the sum of non-distinct powers of 4 are not
a part of the sequence. For example, 8 is not a part of the sequence because it is formed as
the sum of non-distinct powers of 4, that are 4 and 4.
Thus, any number which is not a power of 4 and is present in the sequence must be the sum
of the distinct powers of 4.
For example, 21 is a part of the sequence, even though it is not a power of 4 because it is
the sum of the distinct powers of 4, that are 1, 4 and 16.
Employ the recurrence relation discussed above to generate the sequence, efficiently.
C++
447
Chapter 74. Moser-de Bruijn Sequence
// CPP code to generate first 'n' terms
// of the Moser-de Bruijn Sequence
#include <bits/stdc++.h>
using namespace std;
// Function to generate nth term
// of Moser-de Bruijn Sequence
int gen(int n)
{
// S(0) = 0
if (n == 0)
return 0;
// S(1) = 1
else if (n == 1)
return 1;
// S(2 * n) = 4 * S(n)
else if (n % 2 == 0)
return 4 * gen(n / 2);
// S(2 * n + 1) = 4 * S(n) + 1
else if (n % 2 == 1)
return 4 * gen(n / 2) + 1;
}
// Generating the first 'n' terms
// of Moser-de Bruijn Sequence
void moserDeBruijn(int n)
{
for (int i = 0; i < n; i++)
cout << gen(i) << " ";
cout << "\n";
}
// Driver Code
int main()
{
int n = 15;
cout << "First " << n << " terms of "
<< "Moser-de Bruijn Sequence : \n";
moserDeBruijn(n);
return 0;
}
Java
448
Chapter 74. Moser-de Bruijn Sequence
449
Chapter 74. Moser-de Bruijn Sequence
// This code is contributed by JaideepPyne.
Python3
C#
450
Chapter 74. Moser-de Bruijn Sequence
using System;
class GFG {
// Function to generate nth term
// of Moser-de Bruijn Sequence
public static int gen(int n)
{
// S(0) = 0
if (n == 0)
return 0;
// S(1) = 1
else if (n == 1)
return 1;
// S(2 * n) = 4 * S(n)
else if (n % 2 == 0)
return 4 * gen(n / 2);
// S(2 * n + 1) = 4 * S(n) + 1
else if (n % 2 == 1)
return 4 * gen(n / 2) + 1;
return 0;
}
// Generating the first 'n' terms
// of Moser-de Bruijn Sequence
public static void moserDeBruijn(int n)
{
for (int i = 0; i < n; i++)
Console.Write(gen(i) + " ");
Console.WriteLine();
}
// Driver Code
public static void Main()
{
int n = 15;
Console.WriteLine("First " + n +
" terms of " +
"Moser-de Bruijn Sequence : ");
moserDeBruijn(n);
}
}
// This code is contributed by anuj_67.
451
Chapter 74. Moser-de Bruijn Sequence
PHP
<?php
// PHP code to generate first 'n' terms
// of the Moser-de Bruijn Sequence
// Function to generate nth term
// of Moser-de Bruijn Sequence
function gen($n)
{
// S(0) = 0
if ($n == 0)
return 0;
// S(1) = 1
else if ($n == 1)
return 1;
// S(2 * n) = 4 * S(n)
else if ($n % 2 == 0)
return 4 * gen($n / 2);
// S(2 * n + 1) = 4 * S(n) + 1
else if ($n % 2 == 1)
return 4 * gen($n / 2) + 1;
}
// Generating the first 'n' terms
// of Moser-de Bruijn Sequence
function moserDeBruijn($n)
{
for ($i = 0; $i < $n; $i++)
echo(gen($i) . " ");
echo("\n");
}
// Driver Code
$n = 15;
echo("First " . $n . " terms of " .
"Moser-de Bruijn Sequence : \n");
echo(moserDeBruijn($n));
// This code is contributed by Ajit.
?>
Output :
452
Chapter 74. Moser-de Bruijn Sequence
C++
453
Chapter 74. Moser-de Bruijn Sequence
{
int n = 15;
cout << "First " << n << " terms of "
<< "Moser-de Bruijn Sequence : \n";
moserDeBruijn(n);
return 0;
}
Java
454
Chapter 74. Moser-de Bruijn Sequence
// Driver Code
public static void main(String[] args)
{
int n = 15;
System.out.println("First " + n +
" terms of " +
"Moser-de Bruijn Sequence : ");
moserDeBruijn(n);
}
}
// This code is contributed by
// Smitha Dinesh Semwal.
python3
455
Chapter 74. Moser-de Bruijn Sequence
C#
456
Chapter 74. Moser-de Bruijn Sequence
Console.WriteLine("First " + n +
" terms of " +
"Moser-de Bruijn Sequence : ");
moserDeBruijn(n);
}
}
// This code is contributed by
// Smitha Dinesh Semwal.
PHP
<?php
// PHP code to generate first 'n' terms
// of the Moser-de Bruijn Sequence
// Function to generate nth term
// of Moser-de Bruijn Sequence
function gen( $n)
{
$S = array();
$S[0] = 0;
$S[1] = 1;
for ( $i = 2; $i <= $n; $i++)
{
// S(2 * n) = 4 * S(n)
if ($i % 2 == 0)
$S[$i] = 4 * $S[$i / 2];
// S(2 * n + 1) = 4 * S(n) + 1
else
$S[$i] = 4 * $S[$i/2] + 1;
}
return $S[$n];
}
// Generating the first 'n' terms
// of Moser-de Bruijn Sequence
function moserDeBruijn( $n)
{
for ( $i = 0; $i < $n; $i++)
echo gen($i) , " ";
echo "\n";
}
457
Chapter 74. Moser-de Bruijn Sequence
// Driver Code
$n = 15;
echo "First " ,$n ," terms of "
, "Moser-de Bruijn Sequence : \n";
moserDeBruijn($n);
// This code is contributed by anuj_67.
?>
Output :
Source
https://www.geeksforgeeks.org/moser-de-bruijn-sequence/
458
Chapter 75
Mutual Recursion with example of Hofstadter Female and Male sequences - GeeksforGeeks
Mutual recursion is a variation recursion. Two functions are called mutually recursive if the
first function makes a recursive call to the second function and the second function, in turn,
calls the first one.
In software development this concept is used in circular dependency which is a relation
between two or more modules which either directly or indirectly depend on each other to
function properly. Such modules are also known as mutually recursive.
A great example of mutual recursion would be implementing the Hofstadter Sequence.
Hofstader Sequence
In mathematics, a Hofstadter sequence is a member of a family of related integer sequences
defined by non-linear recurrence relations. In this example we are going to focus on
Hofstadter Female and Male sequences:
459
Chapter 75. Mutual Recursion with example of Hofstadter Female and Male sequences
int hofstaderFemale(int);
int hofstaderMale(int);
// Female function
int hofstaderFemale(int n)
{
if (n < 0)
return;
else
return (n == 0) ? 1 : n - hofstaderFemale(n - 1);
}
// Male function
int hofstaderMale(int n)
{
if (n < 0)
return;
else
return (n == 0) ? 0 : n - hofstaderMale(n - 1);
}
// hard coded driver function to run the program
int main()
{
int i;
printf("F: ");
for (i = 0; i < 20; i++)
printf("%d ", hofstaderFemale(i));
printf("\n");
printf("M: ");
for (i = 0; i < 20; i++)
printf("%d ", hofstaderMale(i));
return 0;
}
Java
460
Chapter 75. Mutual Recursion with example of Hofstadter Female and Male sequences
Python3
461
Chapter 75. Mutual Recursion with example of Hofstadter Female and Male sequences
return;
else:
val = 1 if n == 0 else (
n - hofstaderFemale(n - 1))
return val
# Male function
def hofstaderMale(n):
if n < 0:
return;
else:
val = 0 if n == 0 else (
n - hofstaderMale(n - 1))
return val
# Driver code
print("F:", end = " ")
for i in range(0, 20):
print(hofstaderFemale(i), end = " ")
print("\n")
print("M:", end = " ")
for i in range(0, 20):
print(hofstaderMale(i), end = " ")
# This code is contributed
# by Shantanu Sharma
C#
462
Chapter 75. Mutual Recursion with example of Hofstadter Female and Male sequences
{
if (n < 0)
return 0;
else
return (n == 0) ? 0 : n -
hofstaderMale(n - 1);
}
// Driver Code
static public void Main ()
{
int i;
Console.WriteLine("F: ");
for (i = 0; i < 20; i++)
Console.Write(hofstaderFemale(i) + " ");
Console.WriteLine();
Console.WriteLine("M: ");
for (i = 0; i < 20; i++)
Console.Write(hofstaderMale(i) + " ");
}
}
// This code is contributed by Ajit.
PHP
<?php
// PHP program to implement
// Hofstader Sequence
// using mutual recursion
//function hofstaderFemale(int);
//int hofstaderMale(int);
// Female function
function hofstaderFemale($n)
{
if ($n < 0)
return;
else
return ($n == 0) ? 1 : $n - hofstaderFemale($n - 1);
}
// Male function
function hofstaderMale($n)
{
463
Chapter 75. Mutual Recursion with example of Hofstadter Female and Male sequences
Output:
F: 1 0 2 1 3 2 4 3 5 4 6 5 7 6 8 7 9 8 10 9
M: 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10
1. Circular dependencies can cause a domino effect when a small local change in one
module spreads into other modules and has unwanted global effects
2. Circular dependencies can also result in infinite recursions or other unexpected failures.
3. Circular dependencies may also cause memory leaks by preventing certain very primi-
tive automatic garbage collectors (those that use reference counting) from deallocating
unused objects.
References: Wikipedia
Improved By : jit_t, vt_m, Shantanu Sharma.
Source
https://www.geeksforgeeks.org/mutual-recursion-example-hofstadter-female-male-sequences/
464
Chapter 76
Place(k, i)
// Returns true if a queen can be placed
// in kth row and ith column. Otherwise it
// returns false. X[] is a global array
// whose first (k-1) values have been set.
// Abs( ) returns absolute value of r
{
for j := 1 to k-1 do
return true;
}
Algorithm nQueens(k, n) :
465
Chapter 76. N Queen in O(n) space
C++
466
Chapter 76. N Queen in O(n) space
Output:
---------------------------------
Arrangement No. 1
---------------------------------
_ Q _ _
_ _ _ Q
Q _ _ _
_ _ Q _
---------------------------------
---------------------------------
Arrangement No. 2
467
Chapter 76. N Queen in O(n) space
---------------------------------
_ _ Q _
Q _ _ _
_ _ _ Q
_ Q _ _
---------------------------------
Source
https://www.geeksforgeeks.org/n-queen-in-on-space/
468
Chapter 77
Examples :
Input : n = 2
Output : 1
Input : n = 4
Output : 2
Input : n = 6
469
Chapter 77. Non-crossing lines to connect points in a circle
Output : 5
Input : n = 3
Output : Invalid
n must be even.
We need to draw n/2 lines to connect n points. When we draw a line, we divide the points
in two sets that need to connected. Each set needs to be connected within itself. Below is
recurrence relation for the same.
Let m = n/2
470
Chapter 77. Non-crossing lines to connect points in a circle
Java
471
Chapter 77. Non-crossing lines to connect points in a circle
// A dynamic programming
// based function to find
// nth Catalan number
static int catalanDP(int n)
{
// Table to store
// results of subproblems
int []catalan = new int [n + 1];
// Initialize first
// two values in table
catalan[0] = catalan[1] = 1;
// Fill entries in catalan[]
// using recursive formula
for (int i = 2; i <= n; i++)
{
catalan[i] = 0;
for (int j = 0; j < i; j++)
catalan[i] += catalan[j] *
catalan[i - j - 1];
}
// Return last entry
return catalan[n];
}
// Returns count of ways to
// connect n points on a circle
// such that no two connecting
// lines cross each other and
// every point is connected
// with one other point.
static int countWays(int n)
{
// Throw error if n is odd
if (n < 1)
{
System.out.println("Invalid");
return 0;
}
// Else return n/2'th
// Catalan number
return catalanDP(n / 2);
}
472
Chapter 77. Non-crossing lines to connect points in a circle
// Driver Code
public static void main (String[] args)
{
System.out.println(countWays(6) + " ");
}
}
// This code is contributed
// by akt_mit
C#
473
Chapter 77. Non-crossing lines to connect points in a circle
return catalan[n];
}
// Returns count of ways to
// connect n points on a circle
// such that no two connecting
// lines cross each other and
// every point is connected
// with one other point.
static int countWays(int n)
{
// Throw error if n is odd
if (n < 1)
{
Console.WriteLine("Invalid");
return 0;
}
// Else return n/2'th
// Catalan number
return catalanDP(n / 2);
}
// Driver Code
static public void Main ()
{
Console.WriteLine(countWays(6) + " ");
}
}
// This code is contributed
// by M_kit
PHP
<?php
// PHP program to count number of
// ways to connect n (where n is
// even) points on a circle such
// that no two connecting lines
// cross each other and every
// point is connected with one
// other point.
// A dynamic programming based
// function to find nth Catalan number
function catalanDP($n)
{
474
Chapter 77. Non-crossing lines to connect points in a circle
Output :
475
Chapter 77. Non-crossing lines to connect points in a circle
Source
https://www.geeksforgeeks.org/non-crossing-lines-connect-points-circle/
476
Chapter 78
Number of handshakes such that a person shakes hands only once - GeeksforGeeks
There are N number of persons in a party, find the total number of handshake such that a
person can handshake only once.
Examples:
Input : 5
Output : 10
Input : 9
Output : 36
// Base case
handshake(0) = 0
477
Chapter 78. Number of handshakes such that a person shakes hands only once
C++
478
Chapter 78. Number of handshakes such that a person shakes hands only once
Java
C#
479
Chapter 78. Number of handshakes such that a person shakes hands only once
Python3
480
Chapter 78. Number of handshakes such that a person shakes hands only once
PHP
<?php
// Recursive PHP program to
// count total number of
// handshakes when a person
// can shake hand with only one.
// function to find all
// possible handshakes
function handshake($n)
{
// when n becomes 0 that means
// all the persons have done
// handshake with other
if ($n == 0)
return 0;
else
return ($n - 1) + handshake($n - 1);
}
// Driver Code
$n = 9;
echo(handshake($n));
// This code is contributed
// by Shivi_Aggarwal
?>
Output:
36
C++
481
Chapter 78. Number of handshakes such that a person shakes hands only once
Java
Python3
482
Chapter 78. Number of handshakes such that a person shakes hands only once
PHP
<?php
// Recursive PHP program to
// count total number of
// handshakes when a person
// can shake hand with only one.
// function to find all
// possible handshakes
function handshake($n)
{
return $n * ($n - 1) / 2;
}
// Driver Code
$n = 9;
echo(handshake($n));
// This code is contributed
// by Shivi_Aggarwal
?>
Output:
36
483
Chapter 78. Number of handshakes such that a person shakes hands only once
Source
https://www.geeksforgeeks.org/number-of-handshakes-such-that-a-person-shakes-hands-only-once/
484
Chapter 79
Input : n = 5, val = 1
Output : 5
Explanation:
x1 + x2 + x3 + x4 + x5 = 1
Number of possible solution are :
(0 0 0 0 1), (0 0 0 1 0), (0 0 1 0 0),
(0 1 0 0 0), (1 0 0 0 0)
Total number of possible solutions are 5
Input : n = 5, val = 4
Output : 70
Explanation:
x1 + x2 + x3 + x4 + x5 = 4
Number of possible solution are:
(1 1 1 1 0), (1 0 1 1 1), (0 1 1 1 1),
(2 1 0 0 1), (2 2 0 0 0)........ so on......
Total numbers of possible solutions are 70
485
Chapter 79. Number of non-negative integral solutions of sum equation
Java
486
Chapter 79. Number of non-negative integral solutions of sum equation
Python3
487
Chapter 79. Number of non-negative integral solutions of sum equation
C#
488
Chapter 79. Number of non-negative integral solutions of sum equation
PHP
<?php
// PHP program to find the numbers
// of non negative integral solutions
// return number of non negative
// integral solutions
function countSolutions($n, $val)
{
// initialize total = 0
$total = 0;
// Base Case if n = 1 and
// val >= 0 then it should
// return 1
if ($n == 1 && $val >=0)
return 1;
// iterate the loop
// till equal the val
for ($i = 0; $i <= $val; $i++)
{
// total solution of equations
// and again call the recursive
// function Solutions(variable,value)
489
Chapter 79. Number of non-negative integral solutions of sum equation
Output :
10626
Source
https://www.geeksforgeeks.org/number-of-non-negative-integral-solutions-of-sum-equation/
490
Chapter 80
Number of ways to divide a given number as a set of integers in decreasing order - Geeks-
forGeeks
Given two numbers and . The task is to find the number of ways in which a can be rep-
Input : a = 4, m = 4
Output : 2 –> ({4}, {3, 1})
Note: {2, 2} is not a valid set as values are not in decreasing order
Input : a = 7, m = 5
Output : 5 –> ({7}, {6, 1}, {5, 2}, {4, 3}, {4, 2, 1})
Approach: This problem can be solved by Divide and Conquer using a recursive approach
which follows the following conditions:
491
Chapter 80. Number of ways to divide a given number as a set of integers in decreasing
order
492
Chapter 80. Number of ways to divide a given number as a set of integers in decreasing
order
numWays[(a,m,prev)] += countNumOfWays(a-i,m-1,i)
return numWays[(a, m, prev)]
# Values of 'a' and 'm' for which
# solution is to be found
# MAX_CONST is extremely large value
# used for first comparison in the function
a, m, MAX_CONST = 7, 5, 10**5
print(countNumOfWays(a, m, MAX_CONST))
Output:
Source
https://www.geeksforgeeks.org/number-of-ways-to-divide-a-given-number-as-a-set-of-integers-in-decreasing-order/
493
Chapter 81
Partition given string in such manner that i’th substring is sum of (i-1)’th and (i-2)’th
substring - GeeksforGeeks
Partition given string in such manner that i’th substring is sum of (i-1)’th and (i-2)’nd
substring.
Examples:
Input : "11235813"
Output : ["1", "1", "2", "3", "5", "8", "13"]
Input : "1111223"
Output : ["1", "11", "12", "23"]
Input : "1111213"
Output : ["11", "1", "12", "13"]
Input : "11121114"
Output : []
1. Iterate through the given string by picking 3 numbers (first, seconds and third) at a time
starting from one digit each.
2. If first + second = third, recursively call check() with second as first and third as second.
The third is picked based on next possible number of digits. (The result of addition of two
494
Chapter 81. Partition given string in such manner that i’th substring is sum of (i-1)’th
and (i-2)’th substring
495
Chapter 81. Partition given string in such manner that i’th substring is sum of (i-1)’th
and (i-2)’th substring
496
Chapter 81. Partition given string in such manner that i’th substring is sum of (i-1)’th
and (i-2)’th substring
// To get a subarray with starting from given
// index and offset
private static char[] subArr(char[] chars, int index, int offset) {
int trueOffset = Math.min(chars.length - index, offset);
char[] destArr = new char[trueOffset];
System.arraycopy(chars, index, destArr, 0, trueOffset);
return destArr;
}
private static int intOf(char... chars) {
return Integer.valueOf(new String(chars));
}
public static void main(String[] args) {
String numStr = "11235813";
char[] chars = numStr.toCharArray();
System.out.println(check(chars, 1, 1, 1, false));
System.out.println(resultList);
}
}
Output:
true
[1, 1, 2, 3, 5, 8, 13]
Source
https://www.geeksforgeeks.org/partition-given-string-manner-ith-substring-sum-1th-2th-substring/
497
Chapter 82
Perform n steps to convert every digit of a number in the format [count][digit] - Geeks-
forGeeks
Given a number num as a string and a number N. The task is to write a program which
converts the given number num to another number after performing N steps. At each step,
every digit of num will be written in the format [count][digit] in the new number, where
count is the number of times a digit occurs consecutively in num.
Examples:
Approach: Parse the string’s characters as a single digit and maintain a count for that
digit till a different digit is found. Once a different digit is found, add the count of the digit
to the new string and number to it. Once the string is parsed completely, recur for the
function again with this new string till n steps are done.
Below is the implementation of the above approach:
498
Chapter 82. Perform n steps to convert every digit of a number in the format [count][digit]
499
Chapter 82. Perform n steps to convert every digit of a number in the format [count][digit]
Output:
1321123113
Source
https://www.geeksforgeeks.org/perform-n-steps-to-convert-every-digit-of-a-number-in-the-format-countdigit/
500
Chapter 83
Input : abc
Output : a ab abc ac b bc c
The idea is to sort array first. After sorting, one by one fix characters and recursively
generates all subsets starting from them. After every recursive call, we remove last
character so that next permutation can be generated.
C++
501
Chapter 83. Power Set in Lexicographic order
PHP
<?php
// PHP program to generate power
// set in lexicographic order.
// str : Stores input string
// n : Length of str.
// curr : Stores current permutation
// index : Index in current permutation, curr
function permuteRec($str, $n, $index = -1,
$curr = "")
{
// base case
if ($index == $n)
return;
502
Chapter 83. Power Set in Lexicographic order
echo $curr."\n";
for ($i = $index + 1; $i < $n; $i++)
{
$curr=$curr.$str[$i];
permuteRec($str, $n, $i, $curr);
// backtracking
$curr ="";
}
return;
}
// Generates power set in lexicographic
// order.
function powerSet($str)
{
$str = str_split($str);
sort($str);
permuteRec($str, sizeof($str));
}
// Driver code
$str = "cab";
powerSet($str);
// This code is contributed by Mithun Kumar
?>
Output :
a
ab
abc
ac
b
bc
c
Source
https://www.geeksforgeeks.org/powet-set-lexicographic-order/
503
Chapter 84
Answer: The function fun() calculates and returns ((1 + 2 … + x-1 + x) +y) which is
x(x+1)/2 + y. For example if x is 5 and y is 2, then fun should return 15 + 2 = 17.
Question 2
504
Chapter 84. Practice Questions for Recursion | Set 1
temp = arr[start_index];
arr[start_index] = arr[min_index];
arr[min_index] = temp;
fun2(arr, start_index + 1, end_index);
}
Source
https://www.geeksforgeeks.org/practice-questions-for-recursion/
505
Chapter 85
506
Chapter 85. Practice Questions for Recursion | Set 2
Answer: The function fun2() prints binary equivalent of n. For example, if n is 21 then
fun2() prints 10101.
Note that above functions are just for practicing recursion, they are not the ideal implemen-
tation of the functionality they provide.
Source
https://www.geeksforgeeks.org/practice-questions-for-recursion-set-2/
507
Chapter 86
void fun1(int n)
{
int i = 0;
if (n > 1)
fun1(n-1);
for (i = 0; i < n; i++)
printf(" * ");
}
508
Chapter 86. Practice Questions for Recursion | Set 3
Answer: For a positive n, fun2(n) prints the values of n, 2n, 4n, 8n … while the value is
smaller than LIMIT. After printing values in increasing order, it prints same numbers again
in reverse order. For example fun2(100) prints 100, 200, 400, 800, 800, 400, 200, 100.
If n is negative, the function is returned immediately.
Improved By : hoangdang
Source
https://www.geeksforgeeks.org/practice-questions-for-recursion-set-3/
509
Chapter 87
#include<stdio.h>
void fun(int x)
{
if(x > 0)
{
fun(--x);
printf("%d\t", x);
fun(--x);
}
}
int main()
{
int a = 4;
fun(a);
getchar();
return 0;
}
Output: 0 1 2 0 3 0 1
fun(4);
/
510
Chapter 87. Practice Questions for Recursion | Set 4
Question 2
Predict the output of following program. What does the following fun() do in general?
Output: 100
fun() returns the maximum value in the input array a[] of size n.
Question 3
Predict the output of following program. What does the following fun() do in general?
int fun(int i)
{
if ( i%2 ) return (i++);
else return fun(fun( i - 1 ));
}
int main()
{
printf(" %d ", fun(200));
getchar();
511
Chapter 87. Practice Questions for Recursion | Set 4
return 0;
}
Output: 199
If n is odd then returns n, else returns (n-1). Eg., for n = 12, you get 11 and for n = 11 you
get 11. The statement “return i++;” returns value of i only as it is a post increment.
Source
https://www.geeksforgeeks.org/practice-questions-for-recursion-set-4/
512
Chapter 88
#include<stdio.h>
int fun(int a, int b)
{
if (b == 0)
return 0;
if (b % 2 == 0)
return fun(a+a, b/2);
return fun(a+a, b/2) + a;
}
int main()
{
printf("%d", fun(4, 3));
getchar();
return 0;
}
Output: 12
It calulates a*b (a multipied b).
Question 2
In question 1, if we replace + with * and replace return 0 with return 1, then what does the
changed function do? Following is the changed function.
513
Chapter 88. Practice Questions for Recursion | Set 5
#include<stdio.h>
int fun(int a, int b)
{
if (b == 0)
return 1;
if (b % 2 == 0)
return fun(a*a, b/2);
return fun(a*a, b/2)*a;
}
int main()
{
printf("%d", fun(4, 3));
getchar();
return 0;
}
Output: 64
It calulates a^b (a raised to power b).
Question 3
Predict the output of following program. What does the following fun() do in general?
#include<stdio.h>
int fun(int n)
{
if (n > 100)
return n - 10;
return fun(fun(n+11));
}
int main()
{
printf(" %d ", fun(99));
getchar();
return 0;
}
Output: 91
514
Chapter 88. Practice Questions for Recursion | Set 5
Returned value of fun() is 91 for all integer rguments n <= 101, and n - 10 for n > 101.
This function is known as McCarthy 91 function.
Source
https://www.geeksforgeeks.org/practice-questions-for-recursion-set-5/
515
Chapter 89
num = 2^len-1
516
Chapter 89. Practice Questions for Recursion | Set 6
#include<stdio.h>
void abc(char *s)
{
if(s[0] == '\0')
return;
abc(s + 1);
abc(s + 1);
printf("%c", s[0]);
}
int main()
{
abc("xyz");
return 0;
}
#include<stdio.h>
int fun(int count)
{
printf("%d\n", count);
if(count < 3)
{
fun(fun(fun(++count)));
}
return count;
}
int main()
{
fun(1);
return 0;
}
Output:
1
2
3
517
Chapter 89. Practice Questions for Recursion | Set 6
3
3
3
3
The main() function calls fun(1). fun(1) prints “1” and calls fun(fun(fun(2))).
fun(2) prints “2” and calls fun(fun(fun(3))). So the function call sequence becomes
fun(fun(fun(fun(fun(3))))). fun(3) prints “3” and returns 3 (note that count is not
incremented and no more functions are called as the if condition is not true for count 3).
So the function call sequence reduces to fun(fun(fun(fun(3)))). fun(3) again prints “3” and
returns 3. So the function call again reduces to fun(fun(fun(3))) which again prints “3” and
reduces to fun(fun(3)). This continues and we get “3” printed 5 times on the screen.
Source
https://www.geeksforgeeks.org/practice-questions-for-recursion-set-6/
518
Chapter 90
#include <stdio.h>
int fun ( int n, int *fp )
{
int t, f;
if ( n <= 1 )
{
*fp = 1;
return 1;
}
t = fun ( n-1, fp );
f = t + *fp;
*fp = t;
return f;
}
int main()
{
int x = 15;
printf("%d\n",fun(5, &x));
return 0;
}
519
Chapter 90. Practice Questions for Recursion | Set 7
Output:
The program calculates nth Fibonacci Number. The statement t = fun ( n-1, fp ) gives the
(n-1)th Fibonacci number and *fp is used to store the (n-2)th Fibonacci Number. Initial
value of *fp (which is 15 in the above prgram) doesn’t matter. Following recursion tree
shows all steps from 1 to 10, for exceution of fun(5, &x).
#include <stdio.h>
void fun(int n)
{
if(n > 0)
{
fun(n-1);
printf("%d ", n);
fun(n-1);
}
}
int main()
{
fun(4);
return 0;
}
Output
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
520
Chapter 90. Practice Questions for Recursion | Set 7
fun(4)
/
fun(3), print(4), fun(3) [fun(3) prints 1 2 1 3 1 2 1]
/
fun(2), print(3), fun(2) [fun(2) prints 1 2 1]
/
fun(1), print(2), fun(1) [fun(1) prints 1]
/
fun(0), print(1), fun(0) [fun(0) does nothing]
Source
https://www.geeksforgeeks.org/practice-questions-for-recursion-set-7/
521
Chapter 91
struct Node
{
int data;
struct Node *next;
};
fun1() prints the given Linked List in reverse manner. For Linked List 1->2->3->4->5,
fun1() prints 5->4->3->2->1.
2. What does the following function do for a given Linked List ?
522
Chapter 91. Practice questions for Linked List and Recursion
{
if(head== NULL)
return;
printf("%d ", head->data);
if(head->next != NULL )
fun2(head->next->next);
printf("%d ", head->data);
}
fun2() prints alternate nodes of the given Linked List, first from head to end, and then from
end to head. If Linked List has even number of nodes, then fun2() skips the last node. For
Linked List 1->2->3->4->5, fun2() prints 1 3 5 5 3 1. For Linked List 1->2->3->4->5->6,
fun2() prints 1 3 5 5 3 1.
Below is a complete running program to test above functions.
#include<stdio.h>
#include<stdlib.h>
/* A linked list node */
struct Node
{
int data;
struct Node *next;
};
/* Prints a linked list in reverse manner */
void fun1(struct Node* head)
{
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);
}
/* prints alternate nodes of a Linked List, first
from head to end, and then from end to head. */
void fun2(struct Node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun2(start->next->next);
523
Chapter 91. Practice questions for Linked List and Recursion
524
Chapter 91. Practice questions for Linked List and Recursion
Source
https://www.geeksforgeeks.org/practice-questions-for-linked-list-and-recursion/
525
Chapter 92
#include <iostream>
using namespace std;
template<int N>
class PrintOneToN
{
public:
static void print()
{
PrintOneToN<N-1>::print(); // Note that this is not recursion
cout << N << endl;
}
};
template<>
class PrintOneToN<1>
{
public:
static void print()
{
cout << 1 << endl;
}
};
int main()
{
const int N = 100;
526
Chapter 92. Print 1 to 100 in C++, without loop and recursion
PrintOneToN<N>::print();
return 0;
}
Output:
1
2
3
..
..
98
99
100
The program prints all numbers from 1 to n without using a loop and recursion. The concept
used in this program is Template Metaprogramming.
Let us see how this works. Templates in C++ allow non-datatypes also as parameter.
Non-datatype means a value, not a datatype. For example, in the above program, N is
passed as a value which is not a datatype. A new instance of a generic class is created
for every parameter and these classes are created at compile time. In the above program,
when compiler sees the statement “PrintOneToN<>::print()” with N = 100, it creates an
instance PrintOneToN<100>. In function PrintOneToN<100>::print(), another function
PrintOneToN<99>::print() is called, therefore an instance PrintOneToN<99> is created.
Similarly, all instances from PrintOneToN<100> to PrintOneToN<2> are created. Print-
OneToN<1>::print() is already there and prints 1. The function PrintOneToN<2> prints
2 and so on. Therefore we get all numbers from 1 to N printed on the screen.
Following is another approach to print 1 to 100 without loop and recursion.
#include<iostream>
using namespace std;
class A
{
public:
static int a;
A()
{ cout<<a++<<endl; }
};
int A::a = 1;
int main()
{
int N = 100;
A obj[N];
return 0;
}
527
Chapter 92. Print 1 to 100 in C++, without loop and recursion
The output of this program is same as above program. In the above program, class A has a
static variable ‘a’, which is incremented with every instance of A. The default constructor
of class A prints the value of ‘a’. When we create an array of objects of type A, the default
constructor is called for all objects one by one. Value of ‘a’ is printed and incremented with
every call. Therefore, we get all values from 1 to 100 printed on the screen.
Thanks to Lakshmanan for suggesting this approach.
Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above.
Source
https://www.geeksforgeeks.org/output-of-c-program-set-18-3/
528
Chapter 93
Print N-bit binary numbers having more 1’s than 0’s in all prefixes - GeeksforGeeks
Given a positive integer n, print all n-bit binary numbers having more 1’s than 0’s for any
prefix of the number.
Examples:
Input : n = 2
Output : 11 10
Input : n = 4
Output : 1111 1110 1101 1100 1011 1010
A simple but not efficient solution will be to generate all N-bit binary numbers and print
those numbers that satisfy the conditions. The time complexity of this solution is exponen-
tial.
An efficient solution is to generate only those N-bit numbers that satisfy the given conditions.
We use recursion. At each point in the recursion, we append 0 and 1 to the partially formed
number and recur with one less digit.
C++
529
Chapter 93. Print N-bit binary numbers having more 1’s than 0’s in all prefixes
Java
530
Chapter 93. Print N-bit binary numbers having more 1’s than 0’s in all prefixes
C#
531
Chapter 93. Print N-bit binary numbers having more 1’s than 0’s in all prefixes
{
// if number generated
if (0 == remainingPlaces)
{
Console.Write( number +" ");
return;
}
// Append 1 at the current number and
// reduce the remaining places by one
printRec(number + "1", extraOnes + 1,
remainingPlaces - 1);
// If more ones than zeros, append
// 0 to the current number and
// reduce the remaining places
// by one
if (0 < extraOnes)
printRec(number + "0", extraOnes - 1,
remainingPlaces - 1);
}
static void printNums(int n)
{
String str = "";
printRec(str, 0, n);
}
// Driver code
public static void Main ()
{
int n = 4;
printNums(n);
}
}
// This code is contributed by Nitin Mittal.
Output:
532
Chapter 93. Print N-bit binary numbers having more 1’s than 0’s in all prefixes
Source
https://www.geeksforgeeks.org/print-n-bit-binary-numbers-1s-0s-prefixes/
533
Chapter 94
Input: n = 16
Output: 16, 11, 6, 1, -4, 1, 6, 11, 16
Input: n = 10
Output: 10, 5, 0, 5, 10
We basically first reduce 5 one by one until we reach a negative or 0. After we reach 0 or
negative, we one add 5 until we reach n.
Source: Microsoft Interview Question.
The idea is to use recursion. It is an interesting question to try on your own.
Below is the Code. The code uses a flag variable to indicate whether we are moving toward
0 or we are moving toward the back to n.
C++
534
Chapter 94. Print a pattern without using any loop
Java
535
Chapter 94. Print a pattern without using any loop
{
// Print m.
System.out.print(m + " ");
// If we are moving back toward the n and
// we have reached there, then we are done
if (flag == false && n == m)
return;
// If we are moving toward 0 or negative.
if (flag) {
// If m is greater, then 5, recur with
// true flag
if (m - 5 > 0)
printPattern(n, m - 5, true);
else // recur with false flag
printPattern(n, m - 5, false);
}
else // If flag is false.
printPattern(n, m + 5, false);
}
// Driver Program
public static void main(String[] args)
{
int n = 16;
printPattern(n, n, true);
}
}
// This code is contributed by vt_m
C#
536
Chapter 94. Print a pattern without using any loop
PHP
<?php
// PHP program to print pattern
// that first reduces 5 one by one,
// then adds 5. Without any loop
// Recursive function to print
// the pattern. n indicates input
// value m indicates current value
// to be printed flag indicates whether
// we need to add 5 or subtract 5.
537
Chapter 94. Print a pattern without using any loop
Python3
538
Chapter 94. Print a pattern without using any loop
Output :
How to print above pattern without any extra variable and loop?
The above program works fine and prints the desired out but uses extra variables. We
can use two print statements. First one before the recursive call that prints all decreasing
sequence. Second one after the recursive call to print increasing sequence. Below is the
implementation of the idea.
C++
539
Chapter 94. Print a pattern without using any loop
#include <iostream>
using namespace std;
// Recursive function to print the pattern without any extra
// variable
void printPattern(int n)
{
// Base case (When n becomes 0 or negative)
if (n ==0 || n<0)
{
cout << n << " ";
return;
}
// First print decreasing order
cout << n << " ";
printPattern(n-5);
// Then print increasing order
cout << n << " ";
}
// Driver Program
int main()
{
int n = 16;
printPattern(n);
return 0;
}
Java
540
Chapter 94. Print a pattern without using any loop
System.out.print(n + " ");
return;
}
// First print decreasing order
System.out.print(n + " ");
printPattern(n - 5);
// Then print increasing order
System.out.print(n + " ");
}
// Driver Program
public static void main(String[] args)
{
int n = 16;
printPattern(n);
}
}
// This code is contributed by vt_m
C#
541
Chapter 94. Print a pattern without using any loop
return;
}
// First print decreasing order
Console.Write(n + " ");
printPattern(n - 5);
// Then print increasing order
Console.Write(n + " ");
}
// Driver Program
public static void Main()
{
int n = 16;
printPattern(n);
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to print pattern
// that first reduces 5 one
// by one, then adds 5. Without
// any loop an extra variable.
// Recursive function to print the
// pattern without any extra variable
function printPattern( $n)
{
// Base case (When n becomes
// 0 or negative)
if ($n == 0 or $n < 0)
{
echo $n , " ";
return;
}
// First print decreasing order
echo $n , " ";
printPattern($n-5);
542
Chapter 94. Print a pattern without using any loop
// Then print increasing order
echo $n , " ";
}
// Driver Code
$n = 16;
printPattern($n);
// This code is conntributed by anuj_67.
?>
Output:
Source
https://www.geeksforgeeks.org/print-a-pattern-without-using-any-loop/
543
Chapter 95
Input : 16
Output :2 2 2 2
2 2 4
2 8
4 4
Input : 12
Output : 2 2 3
2 6
3 4
To solve this problem we take one array of array of integers or list of list of integers to store
all the factors combination possible for the given n. So, to achieve this we can have one
recursive function which can store the factors combination in each of its iteration. And each
of those list should be stored in the final result list.
Below is the implementation of the above approach .
544
Chapter 95. Print all combinations of factors (Ways to factorize)
545
Chapter 95. Print all combinations of factors (Ways to factorize)
// if i divides n
// properly then it
// is factor of n
if (n % i == 0) {
// it is added to 'single_result_list' list
single_result_list.add(i);
// Here function is called recursively
// and when (i*each_prod) is equal to n
// we will store the 'single_result_list' (it is
// basically the list containing all
// combination of factors) into result_list.
factorsListFunc(i, i * each_prod, n,
result_list, single_result_list);
// here we will empty the 'single_result_list'
// List so that new combination of factors
// get stored in it.
single_result_list.remove(single_result_list.size() - 1);
}
}
}
// Driver code
public static void main(String[] args)
{
int n = 16;
List<List<Integer> > resultant = factComb(n);
// printing all possible combination
// of factors stored in resultant list
for (List<Integer> i : resultant) {
for (int j : i)
System.out.print(j + " ");
System.out.println();
}
}
}
Output:
2 2 2 2
2 2 4
2 8
4 4
546
Chapter 95. Print all combinations of factors (Ways to factorize)
Source
https://www.geeksforgeeks.org/print-combinations-factors-ways-factorize/
547
Chapter 96
Print all distinct integers that can be formed by K numbers from a given array of N numbers
- GeeksforGeeks
Given an array of N elements and an integer K, print all the distinct integers which can be
formed by choosing K numbers from the given N numbers. A number from an array can be
chosen any number of times.
Examples:
Approach: The problem will be solved using recursion. All combinations are to be tried,
when the count of elements selected is equal to k, then we keep the num formed in the set
so that the repetitive elements are not counted twice. The function generateNumber(int
count, int a[], int n, int num, int k) is a recursive function, in which the base case is
when the count becomes K which signifies that K elements from the array have been chosen.
num in the parameter signifies the number formed by count number of numbers. In the
function, iterate over the array and for every element, call the recursive function with count
as count+1 and num as num+a[i].
548
Chapter 96. Print all distinct integers that can be formed by K numbers from a given
array of N numbers
C++
549
Chapter 96. Print all distinct integers that can be formed by K numbers from a given
array of N numbers
{
int a[] = { 3, 8, 17, 5 };
int n = sizeof(a) / sizeof(a[0]);
int k = 2;
// Calling Function
printDistinctIntegers(k, a, n);
return 0;
}
Java
550
Chapter 96. Print all distinct integers that can be formed by K numbers from a given
array of N numbers
Output:
Source
https://www.geeksforgeeks.org/print-all-distinct-integers-that-can-be-formed-by-k-numbers-from-a-given-array-of-
551
Chapter 97
Print all increasing sequences of length k from first n natural numbers - GeeksforGeeks
Given two positive integers n and k, print all increasing sequences of length k such that the
elements in every sequence are from first n natural numbers.
Examples:
Input: k = 2, n = 3
Output: 1 2
1 3
2 3
Input: k = 5, n = 5
Output: 1 2 3 4 5
Input: k = 3, n = 5
Output: 1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
552
Chapter 97. Print all increasing sequences of length k from first n natural numbers
We strongly recommend to minimize the browser and try this yourself first.
It’s a good recursion question. The idea is to create an array of length k. The array stores
current sequence. For every position in array, we check the previous element and one by
one put all elements greater than the previous element. If there is no previous element (first
position), we put all numbers from 1 to n.
Below is the implementation of above idea :
C++
553
Chapter 97. Print all increasing sequences of length k from first n natural numbers
// Put all numbers (which are greater than the previous
// element) at new position.
while (i<=n)
{
arr[len-1] = i;
printSeqUtil(n, k, len, arr);
i++;
}
// This is important. The variable 'len' is shared among
// all function calls in recursion tree. Its value must be
// brought back before next iteration of while loop
len--;
}
// This function prints all increasing sequences of
// first n natural numbers. The length of every sequence
// must be k. This function mainly uses printSeqUtil()
void printSeq(int n, int k)
{
int arr[k]; // An array to store individual sequences
int len = 0; // Initial length of current sequence
printSeqUtil(n, k, len, arr);
}
// Driver program to test above functions
int main()
{
int k = 3, n = 7;
printSeq(n, k);
return 0;
}
Java
554
Chapter 97. Print all increasing sequences of length k from first n natural numbers
555
Chapter 97. Print all increasing sequences of length k from first n natural numbers
C#
556
Chapter 97. Print all increasing sequences of length k from first n natural numbers
// A utility function to print
// contents of arr[0..k-1]
static void printArr(int[] arr, int k)
{
for (int i = 0; i < k; i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// A recursive function to print
// all increasing sequences
// of first n natural numbers.
// Every sequence should be
// length k. The array arr[] is
// used to store current sequence
static void printSeqUtil(int n, int k,
int len, int[] arr)
{
// If length of current increasing
// sequence becomes k, print it
if (len == k)
{
printArr(arr, k);
return;
}
// Decide the starting number
// to put at current position:
// If length is 0, then there
// are no previous elements
// in arr[]. So start putting
// new numbers with 1.
// If length is not 0,
// then start from value of
// previous element plus 1.
int i = (len == 0) ? 1 : arr[len - 1] + 1;
// Increase length
len++;
// Put all numbers (which are
// greater than the previous
// element) at new position.
while (i <= n)
{
arr[len - 1] = i;
557
Chapter 97. Print all increasing sequences of length k from first n natural numbers
PHP
<?php
// PHP program to print all
// increasing sequences of
// length 'k' such that the
558
Chapter 97. Print all increasing sequences of length k from first n natural numbers
559
Chapter 97. Print all increasing sequences of length k from first n natural numbers
Output:
1 2 3
1 2 4
560
Chapter 97. Print all increasing sequences of length k from first n natural numbers
1 2 5
1 2 6
1 2 7
1 3 4
1 3 5
1 3 6
1 3 7
1 4 5
1 4 6
1 4 7
1 5 6
1 5 7
1 6 7
2 3 4
2 3 5
2 3 6
2 3 7
2 4 5
2 4 6
2 4 7
2 5 6
2 5 7
2 6 7
3 4 5
3 4 6
3 4 7
3 5 6
3 5 7
3 6 7
4 5 6
4 5 7
4 6 7
5 6 7
This article is contributed by Arjun. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : jit_t, Smitha Dinesh Semwal
Source
https://www.geeksforgeeks.org/print-increasing-sequences-length-k-first-n-natural-numbers/
561
Chapter 98
Print all leaf nodes of a Binary Tree from left to right - GeeksforGeeks
Given a binary tree, we need to write a program to print all leaf nodes of the given binary
tree from left to right. That is, the nodes should be printed in the order they appear from
left to right in the given tree.
For Example,
4 6 7 9 10
The idea to do this is similar to DFS algorithm. Below is step by step algorithm to do this:
1. Check if given node is null. If null, then return from the function.
562
Chapter 98. Print all leaf nodes of a Binary Tree from left to right
2. Check if it is a leaf node. If the node is a leaf node, then print its data.
3. If in above step, node is not a leaf node then check if left and right childs of node
exists. If yes then call function for left and right childs of the node recursively.
563
Chapter 98. Print all leaf nodes of a Binary Tree from left to right
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in
// above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(8);
root->right->left->left = newNode(6);
root->right->left->right = newNode(7);
root->right->right->left = newNode(9);
root->right->right->right = newNode(10);
// print leaf nodes of the given tree
printLeafNodes(root);
return 0;
}
Output:
4 6 7 9 10
Source
https://www.geeksforgeeks.org/print-leaf-nodes-left-right-binary-tree/
564
Chapter 99
This problem is an extension of longest common subsequence. We first find length of LCS
and store all LCS in 2D table using Memoization (or Dynamic Programming). Then we
search all characters from ‘a’ to ‘z’ (to output sorted order) in both strings. If a character is
found in both strings and current positions of character lead to LCS, we recursively search
all occurrences with current LCS length plus 1.
Below is the implementation of algorithm.
565
Chapter 99. Print all longest common sub-sequences in lexicographical order
566
Chapter 99. Print all longest common sub-sequences in lexicographical order
}
// if we are done with all the characters of both string
if (indx1==len1 || indx2==len2)
return;
// here we have to print all sub-sequences lexicographically,
// that's why we start from 'a'to'z' if this character is
// present in both of them then append it in data[] and same
// remaining part
for (char ch='a'; ch<='z'; ch++)
{
// done is a flag to tell that we have printed all the
// subsequences corresponding to current character
bool done = false;
for (int i=indx1; i<len1; i++)
{
// if character ch is present in str1 then check if
// it is present in str2
if (ch==str1[i])
{
for (int j=indx2; j<len2; j++)
{
// if ch is present in both of them and
// remaining length is equal to remaining
// lcs length then add ch in sub-sequenece
if (ch==str2[j] &&
lcs(str1, str2, len1, len2, i, j) == lcslen-currlcs)
{
data[currlcs] = ch;
printAll(str1, str2, len1, len2, data, i+1, j+1, currlcs+1);
done = true;
break;
}
}
}
// If we found LCS beginning with current character.
if (done)
break;
}
}
}
// This function prints all LCS of str1 and str2
// in lexicographic order.
void prinlAllLCSSorted(string str1, string str2)
567
Chapter 99. Print all longest common sub-sequences in lexicographical order
{
// Find lengths of both strings
int len1 = str1.length(), len2 = str2.length();
// Find length of LCS
memset(dp, -1, sizeof(dp));
lcslen = lcs(str1, str2, len1, len2, 0, 0);
// Print all LCS using recursive backtracking
// data[] is used to store individual LCS.
char data[MAX];
printAll(str1, str2, len1, len2, data, 0, 0, 0);
}
// Driver program to run the case
int main()
{
string str1 = "abcabcaa", str2 = "acbacba";
prinlAllLCSSorted(str1, str2);
return 0;
}
Output:
ababa
abaca
abcba
acaba
acaca
acbaa
acbca
Source
https://www.geeksforgeeks.org/print-longest-common-sub-sequences-lexicographical-order/
568
Chapter 100
Input: n = 2
Output:
01 02 03 04 05 06 07 08 09 12 13 14 15 16 17 18 19 23 24 25 26 27 28
29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89
Input: n = 3
Output:
012 013 014 015 016 017 018 019 023 024 025 026 027 028 029 034
035 036 037 038 039 045 046 047 048 049 056 057 058 059 067 068
069 078 079 089 123 124 125 126 127 128 129 134 135 136 137 138
139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189
234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267
268 269 278 279 289 345 346 347 348 349 356 357 358 359 367 368
369 378 379 389 456 457 458 459 467 468 469 478 479 489 567 568
569 578 579 589 678 679 689 789
Input: n = 1
Output: 0 1 2 3 4 5 6 7 8 9
The idea is to use recursion. We start from the leftmost position of a possible N-digit number
and fill it from set of all digits greater than its previous digit. i.e. fill current position with
569
Chapter 100. Print all n-digit strictly increasing numbers
digits (i to 9] where i is its previous digit. After filling current position, we recurse for next
position with strictly increasing numbers.
Below is implementation of above idea –
CPP
Java
570
Chapter 100. Print all n-digit strictly increasing numbers
C#
571
Chapter 100. Print all n-digit strictly increasing numbers
Output:
012 013 014 015 016 017 018 019 023 024 025 026 027 028 029 034
035 036 037 038 039 045 046 047 048 049 056 057 058 059 067 068
069 078 079 089 123 124 125 126 127 128 129 134 135 136 137 138
139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189
234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267
268 269 278 279 289 345 346 347 348 349 356 357 358 359 367 368
369 378 379 389 456 457 458 459 467 468 469 478 479 489 567 568
572
Chapter 100. Print all n-digit strictly increasing numbers
Exercise: Print all n-digit numbers whose digits are strictly decreasing from left to right.
Improved By : Sam007
Source
https://www.geeksforgeeks.org/print-all-n-digit-strictly-increasing-numbers/
573
Chapter 101
Input: x = 3
Output: 1 1 1
2 1
3
Input: x = 4
Output: 1 1 1 1
2 1 1
2 2
3 1
4
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to use a recursive function, an array arr[] to store all sequences one by one and
an index variable curr_idx to store current next index in arr[]. Below is algorithm.
1) If current sum is equal to x, then print current sequence.
2) Place all possible numbers from 1 to x-curr_sum numbers at curr_idx in array. Here
curr_sum is sum of current elements in arr[]. After placing a number, recur for curr_sum
+ number and curr_idx+1,
574
Chapter 101. Print all non-increasing sequences of sum equal to a given number x
C++
575
Chapter 101. Print all non-increasing sequences of sum equal to a given number x
// A wrapper over generateUtil()
void generate(int x)
{
int arr[x]; // Array to store sequences on by one
generateUtil(x, arr, 0, 0);
}
// Driver program
int main()
{
int x = 5;
generate(x);
return 0;
}
Java
576
Chapter 101. Print all non-increasing sequences of sum equal to a given number x
// Try placing all numbers from 1 to
// x-curr_sum at current index
int num = 1;
// The placed number must also be smaller
// than previously placed numbers, i.e.,
// arr[curr_idx-1] if there exists a
// pevious number
while (num <= x - curr_sum &&
(curr_idx == 0 ||
num <= arr[curr_idx - 1]))
{
// Place number at curr_idx
arr[curr_idx] = num;
// Recur
generateUtil(x, arr, curr_sum+num,
curr_idx + 1);
// Try next number
num++;
}
}
// A wrapper over generateUtil()
static void generate(int x)
{
// Array to store sequences on by one
int arr[] = new int [x];
generateUtil(x, arr, 0, 0);
}
// Driver program
public static void main(String[] args)
{
int x = 5;
generate(x);
}
}
// This code is contributed by Smitha.
Python 3
577
Chapter 101. Print all non-increasing sequences of sum equal to a given number x
578
Chapter 101. Print all non-increasing sequences of sum equal to a given number x
# Recur
generateUtil(x, arr,
curr_sum + num, curr_idx + 1)
# Try next number
num += 1
# A wrapper over generateUtil()
def generate(x):
# Array to store sequences
# on by one
arr = [0] * x
generateUtil(x, arr, 0, 0)
# Driver program
x = 5
generate(x)
# This code is contributed
# by Smitha.
C#
579
Chapter 101. Print all non-increasing sequences of sum equal to a given number x
580
Chapter 101. Print all non-increasing sequences of sum equal to a given number x
{
int x = 5;
generate(x);
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to generate all
// non-increasing sequences
// of sum equals to x
// function to print array
// arr[0..n-1]
function printArr($arr, $n)
{
for ($i = 0; $i < $n; $i++)
echo $arr[$i] , " ";
echo " \n";
}
// Recursive Function to generate
// all non-increasing sequences
// with sum x
// arr[] --> Elements of current sequence
// curr_sum --> Current Sum
// curr_idx --> Current index in arr[]
function generateUtil($x, $arr, $curr_sum,
$curr_idx)
{
// If current sum is equal to x,
// then we found a sequence
if ($curr_sum == $x)
{
printArr($arr, $curr_idx);
return;
}
// Try placing all numbers from
// 1 to x-curr_sum at current index
$num = 1;
// The placed number must also
// be smaller than previously
581
Chapter 101. Print all non-increasing sequences of sum equal to a given number x
Output:
1 1 1 1 1
2 1 1 1
2 2 1
3 1 1
3 2
4 1
5
This article is contributed by Ashish Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Smitha Dinesh Semwal, nitin mittal, vt_m
582
Chapter 101. Print all non-increasing sequences of sum equal to a given number x
Source
https://www.geeksforgeeks.org/print-all-non-increasing-sequences-of-sum-equal-to-a-given-number/
583
Chapter 102
584
Chapter 102. Print all possible combinations of r elements in a given array of size n
585
Chapter 102. Print all possible combinations of r elements in a given array of size n
Java
586
Chapter 102. Print all possible combinations of r elements in a given array of size n
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
static void printCombination(int arr[], int n, int r)
{
// A temporary array to store all combination one by one
int data[]=new int[r];
// Print all combination using temprary array 'data[]'
combinationUtil(arr, data, 0, n-1, 0, r);
}
/*Driver function to check for above function*/
public static void main (String[] args) {
int arr[] = {1, 2, 3, 4, 5};
int r = 3;
int n = arr.length;
printCombination(arr, n, r);
}
}
/* This code is contributed by Devesh Agrawal */
C#
587
Chapter 102. Print all possible combinations of r elements in a given array of size n
indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination
to be printed */
static void combinationUtil(int []arr, int []data,
int start, int end,
int index, int r)
{
// Current combination is
// ready to be printed,
// print it
if (index == r)
{
for (int j = 0; j < r; j++)
Console.Write(data[j] + " ");
Console.WriteLine("");
return;
}
// replace index with all
// possible elements. The
// condition "end-i+1 >=
// r-index" makes sure that
// including one element
// at index will make a
// combination with remaining
// elements at remaining positions
for (int i = start; i <= end &&
end - i + 1 >= r - index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i + 1,
end, index + 1, r);
}
}
// The main function that prints
// all combinations of size r
// in arr[] of size n. This
// function mainly uses combinationUtil()
static void printCombination(int []arr,
int n, int r)
{
// A temporary array to store
// all combination one by one
int []data = new int[r];
// Print all combination
588
Chapter 102. Print all possible combinations of r elements in a given array of size n
PHP
<?php
// Program to print all
// combination of size r
// in an array of size n
// The main function that
// prints all combinations
// of size r in arr[] of
// size n. This function
// mainly uses combinationUtil()
function printCombination($arr,
$n, $r)
{
// A temporary array to
// store all combination
// one by one
$data = array();
// Print all combination
// using temprary array 'data[]'
combinationUtil($arr, $data, 0,
$n - 1, 0, $r);
}
/* arr[] ---> Input Array
data[] ---> Temporary array to
store current combination
start & end ---> Staring and Ending
indexes in arr[]
589
Chapter 102. Print all possible combinations of r elements in a given array of size n
Output:
1 2 3
1 2 4
590
Chapter 102. Print all possible combinations of r elements in a given array of size n
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
591
Chapter 102. Print all possible combinations of r elements in a given array of size n
Java
592
Chapter 102. Print all possible combinations of r elements in a given array of size n
593
Chapter 102. Print all possible combinations of r elements in a given array of size n
C#
594
Chapter 102. Print all possible combinations of r elements in a given array of size n
combinationUtil(arr, n, r,
index + 1, data, i + 1);
// current is excluded, replace
// it with next (Note that
// i+1 is passed, but index
// is not changed)
combinationUtil(arr, n, r, index,
data, i + 1);
}
// The main function that prints
// all combinations of size r
// in arr[] of size n. This
// function mainly uses combinationUtil()
static void printCombination(int []arr,
int n, int r)
{
// A temporary array to store
// all combination one by one
int []data = new int[r];
// Print all combination
// using temprary array 'data[]'
combinationUtil(arr, n, r, 0, data, 0);
}
// Driver Code
static public void Main ()
{
int []arr = {1, 2, 3, 4, 5};
int r = 3;
int n = arr.Length;
printCombination(arr, n, r);
}
}
// This code is contributed by ajit
PHP
<?php
// Program to print all
// combination of size r
// in an array of size n
// The main function that prints
// all combinations of size r in
595
Chapter 102. Print all possible combinations of r elements in a given array of size n
596
Chapter 102. Print all possible combinations of r elements in a given array of size n
Output :
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
597
Chapter 102. Print all possible combinations of r elements in a given array of size n
Source
https://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/
598
Chapter 103
This problem can be solved by putting all possible binary operator in mid between to digits
and evaluating them and then check they evaluate to target or not.
• While writing the recursive code, we need to keep these variable as argument of re-
cursive method – result vector, input string, current expression string, target value,
position till which input is processed, current evaluated value and last value in evalu-
ation.
• Last value is kept in recursion because of multiplication operation, while doing multi-
plication we need last value for correct evaluation.
599
Chapter 103. Print all possible expressions that evaluate to a target
Another thing to note in below code is, we have ignored all numbers which start from 0 by
imposing a condition as first condition inside the loop so that we will not process number
like 03, 05 etc.
See the use of c_str() function, this function converts the C++ string into C char array,
this function is used in below code because atoi() function expects a character array as an
argument not the string. It converts character array to number.
600
Chapter 103. Print all possible expressions that evaluate to a target
601
Chapter 103. Print all possible expressions that evaluate to a target
Output:
1+2+3 1*2*3
1*2+5 12-5
Source
https://www.geeksforgeeks.org/print-all-possible-expressions-that-evaluate-to-a-target/
602
Chapter 104
Print all possible strings of length k that can be formed from a set of n characters - Geeks-
forGeeks
Given a set of characters and a positive integer k, print all possible strings of length k that
can be formed from the given set.
Examples:
Input:
set[] = {'a', 'b'}, k = 3
Output:
aaa
aab
aba
abb
baa
bab
bba
bbb
Input:
set[] = {'a', 'b', 'c', 'd'}, k = 1
Output:
a
b
603
Chapter 104. Print all possible strings of length k that can be formed from a set of n
characters
c
d
For a given set of size n, there will be n^k possible strings of length k. The idea is to
start from an empty output string (we call it prefix in following code). One by one add all
characters to prefix. For every character added, print all possible strings with current prefix
by recursively calling for k equals to k-1.
Below is the implementation of above idea :
Java
604
Chapter 104. Print all possible strings of length k that can be formed from a set of n
characters
C#
605
Chapter 104. Print all possible strings of length k that can be formed from a set of n
characters
int n, int k)
{
// Base case: k is 0,
// print prefix
if (k == 0)
{
Console.WriteLine(prefix);
return;
}
// One by one add all characters
// from set and recursively
// call for k equals to k-1
for (int i = 0; i < n; ++i)
{
// Next character of input added
String newPrefix = prefix + set[i];
// k is decreased, because
// we have added a new character
printAllKLengthRec(set, newPrefix,
n, k - 1);
}
}
// Driver Code
static public void Main ()
{
Console.WriteLine("First Test");
char[] set1 = {'a', 'b'};
int k = 3;
printAllKLength(set1, k);
Console.WriteLine("\nSecond Test");
char[] set2 = {'a', 'b', 'c', 'd'};
k = 1;
printAllKLength(set2, k);
}
}
// This code is contributed by Ajit.
Output:
First Test
aaa
606
Chapter 104. Print all possible strings of length k that can be formed from a set of n
characters
aab
aba
abb
baa
bab
bba
bbb
Second Test
a
b
c
d
Source
https://www.geeksforgeeks.org/print-all-combinations-of-given-length/
607
Chapter 105
Print all possible strings that can be made by placing spaces - GeeksforGeeks
Given a string you need to print all possible strings that can be made by placing spaces
(zero or one) in between them.
608
Chapter 105. Print all possible strings that can be made by placing spaces
Java
609
Chapter 105. Print all possible strings that can be made by placing spaces
class Permutation
{
// Function recursively prints the strings having space pattern
// i and j are indices in 'String str' and 'buf[]' respectively
static void printPatternUtil(String str, char buf[], int i, int j, int n)
{
if(i == n)
{
buf[j] = '\0';
System.out.println(buf);
return;
}
// Either put the character
buf[j] = str.charAt(i);
printPatternUtil(str, buf, i+1, j+1, n);
// Or put a space followed by next character
buf[j] = ' ';
buf[j+1] = str.charAt(i);
printPatternUtil(str, buf, i+1, j+2, n);
}
// Function creates buf[] to store individual output string and uses
// printPatternUtil() to print all permutations
static void printPattern(String str)
{
int len = str.length();
// Buffer to hold the string containing spaces
// 2n-1 characters and 1 string terminator
char[] buf = new char[2*len];
// Copy the first character as it is, since it will be always
// at first position
buf[0] = str.charAt(0);
printPatternUtil(str, buf, 1, 1, len);
}
// Driver program
public static void main (String[] args)
{
String str = "ABCD";
printPattern(str);
}
}
610
Chapter 105. Print all possible strings that can be made by placing spaces
Python
611
Chapter 105. Print all possible strings that can be made by placing spaces
printPattern(string)
# This code is contributed by BHAVYA JAIN
C#
612
Chapter 105. Print all possible strings that can be made by placing spaces
// terminator
char []buf = new char[2*len];
// Copy the first character as it is,
// since it will be always at first
// position
buf[0] = str[0];
printPatternUtil(str, buf, 1, 1, len);
}
// Driver program
public static void Main ()
{
string str = "ABCD";
printPattern(str);
}
}
// This code is contributed by nitin mittal.
Output:
ABCD
ABC D
AB CD
AB C D
A BCD
A BC D
A B CD
A B C D
Time Complexity: Since number of Gaps are n-1, there are total 2^(n-1) patters each having
length ranging from n to 2n-1. Thus overall complexity would be O(n*(2^n)).
This article is contributed by Gaurav Sharma. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/print-possible-strings-can-made-placing-spaces/
613
Chapter 106
Given a keypad as shown in diagram, and a n digit number, list all words which
are possible by pressing these numbers.
For example if input number is 234, possible words which can be formed are (Alphabetical
order):
614
Chapter 106. Print all possible words from phone digits
adg adh adi aeg aeh aei afg afh afi bdg bdh bdi beg beh bei bfg bfh bfi cdg cdh cdi ceg ceh cei
cfg cfh cfi
Let’s do some calculations first. How many words are possible with seven digits with each
digit representing n letters? For first digit we have at most four choices, and for each choice
for first letter, we have at most four choices for second digit and so on. So it’s simple maths
it will be O(4n ). Since keys 0 and 1 don’t have any corresponding alphabet and many
characters have 3 characters, 4n would be the upper bound of number of words and not the
minimum words.
Now let’s do some examples.
For number above 234. Do you see any pattern? Yes, we notice that the last character
always either G,H or I and whenever it resets its value from I to G, the digit at the left of
it gets changed.
Similarly whenever the second last alphabet resets its value, the third last alphabet gets
changes and so on. First character resets only once when we have generated all words. This
can be looked from other end also. That is to say whenever character at position i changes,
character at position i+1 goes through all possible characters and it creates ripple effect till
we reach at end.
Since 0 and 1 don’t have any characters associated with them. we should break as there
will no iteration for these digits.
Let’s take the second approach as it will be easy to implement it using recursion. We go
till the end and come back one by one. Perfect condition for recursion. let’s search for base
case.
When we reach at the last character, we print the word with all possible characters for last
digit and return. Simple base case.
When we reach at the last character, we print the word with all possible characters for last
digit and return. Simple base case.
Following is C implementation of recursive approach to print all possible word corresponding
to a n digit input number. Note that input number is represented as an array to simplify
the code.
#include <stdio.h>
#include <string.h>
// hashTable[i] stores all characters that correspond to digit i in phone
const char hashTable[10][5] = {"", "", "abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"};
// A recursive function to print all possible words that can be obtained
// by input number[] of size n. The output words are one by one stored
// in output[]
void printWordsUtil(int number[], int curr_digit, char output[], int n)
{
// Base case, if current output word is prepared
int i;
if (curr_digit == n)
{
615
Chapter 106. Print all possible words from phone digits
Output:
adg adh adi aeg aeh aei afg afh afi bdg
bdh bdi beg beh bei bfg bfh bfi cdg cdh
cdi ceg ceh cei cfg cfh cfi
Process returned 0 (0x0) execution time : 0.025 s
Press any key to continue.
Time Complexity: Time complexity of above code is O(4n ) where n is number of digits
in input number.
Reference:
Buy Programming Interviews Exposed: Secrets to Landing Your Next Job 3rd Edition from
Flipkart.com
616
Chapter 106. Print all possible words from phone digits
This article is contributed by Jitendra Sangar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : ABHISHEKSINGH15BCE1009
Source
https://www.geeksforgeeks.org/find-possible-words-phone-digits/
617
Chapter 107
Print all sequences starting with n and consecutive difference limited to k - GeeksforGeeks
Given three positive integer n, s and k. The task is to print all possible sequence of length
s, starting with n and the absolute difference between consecutive element is less than k.
Examples :
Input : n = 5, s = 3, k = 2
Output :
5 5 5
5 5 6
5 5 4
5 6 6
5 6 7
5 6 5
5 4 4
5 4 5
5 4 3
Input : n = 3, s = 2, k = 1
Output :
3 3
Observe, to get the absolute difference between consecutive element less than k, we can
increase from 0 to k – 1. Similarly, we can decrease the next element from 1 to k – 1.
Now, to form the required sequence, we will first push ‘n’ to the vector. And then try to fill
618
Chapter 107. Print all sequences starting with n and consecutive difference limited to k
the other element of the sequence by making recursive call for each element in the sequence.
At each recursive call we run a loop from 0 to k – 1 and add (n + i) to the sequence. Once
we make the sequence of size ‘s’, we will print the whole sequence and return back to the
recursively calling function and remove (n + i).
Similarly, we can run loop from 1 to k – 1 and insert (n – i) to next element position.
To check the number of remaining element required we will pass size – 1 to recursive call
and when size become 0, we will print the whole sequence.
Below is the implementation of this approach:
C++
619
Chapter 107. Print all sequences starting with n and consecutive difference limited to k
v.pop_back();
}
}
// Wrapper Function
void wrapper(int n, int s, int k)
{
vector<int> v;
v.push_back(n);
printSequence(v, n, s - 1, k);
}
// Driven Program
int main()
{
int n = 5, s = 3, k = 2;
wrapper(n, s, k);
return 0;
}
Java
620
Chapter 107. Print all sequences starting with n and consecutive difference limited to k
Python3
621
Chapter 107. Print all sequences starting with n and consecutive difference limited to k
if (s == 0) :
for i in range(0, len(v)):
print ("{} ".format(v[i]), end="")
print ("")
return;
# Increment the next element and make
# recursive call after inserting the
# (n + i) to the sequence.
for i in range(0,k):
v.append(n + i)
printSequence(v, n + i, s - 1, k)
v.pop()
# Decrementing the next element and'
# make recursive call after inserting
# the (n - i) to the sequence.
for i in range(1,k):
v.append(n - i)
printSequence(v, n - i, s - 1, k)
v.pop()
# Wrapper Function
def wrapper(n, s, k):
v = []
v.append(n)
printSequence(v, n, s - 1, k)
# Driven Program
n = 5; s = 3; k = 2;
wrapper(n, s, k);
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
622
Chapter 107. Print all sequences starting with n and consecutive difference limited to k
class GFG {
// Recursive function to print all sequence
// of length s starting with n such that
// difference between consecutive element
// is less than k.
static void printSequence(ref List<int> v, int n,
int s, int k)
{
// If size become 0, print the sequence.
if (s == 0) {
for (int i = 0; i < v.Count; i++)
Console.Write(v[i] + " ");
Console.WriteLine();
return;
}
// Increment the next element and make
// recursive call after inserting the
// (n + i) to the sequence.
for (int i = 0; i < k; i++) {
v.Add(n + i);
printSequence(ref v, n + i, s - 1, k);
v.RemoveAt(v.Count - 1);
}
// Decrementing the next element and'
// make recursive call after inserting
// the (n - i) to the sequence.
for (int i = 1; i < k; i++) {
v.Add(n - i);
printSequence(ref v, n - i, s - 1, k);
v.RemoveAt(v.Count - 1);
}
}
// Wrapper Function
static void wrapper(int n, int s, int k)
{
List<int> v = new List<int>();
v.Add(n);
printSequence(ref v, n, s - 1, k);
}
// Driven Program
public static void Main()
{
623
Chapter 107. Print all sequences starting with n and consecutive difference limited to k
int n = 5, s = 3, k = 2;
wrapper(n, s, k);
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP Program all sequence of
// length s starting with n
// such that difference between
// consecutive element is less than k.
// Recursive function to print
// all sequence of length s
// starting with n such that
// difference between consecutive
// element is less than k.
function printSequence($v, $n,
$s, $k)
{
// If size become 0,
// print the sequence.
if ($s == 0)
{
for ($i = 0; $i < count($v); $i++)
echo ($v[$i]." ");
echo ("\n");
return;
}
// Increment the next element
// and make recursive call
// after inserting the (n + i)
// to the sequence.
for ($i = 0; $i < $k; $i++)
{
array_push($v, $n + $i);
printSequence($v, $n + $i,
$s - 1, $k);
array_pop($v);
}
// Decrementing the next element
// and make recursive call after
624
Chapter 107. Print all sequences starting with n and consecutive difference limited to k
Output :
5 5 5
5 5 6
5 5 4
5 6 6
5 6 7
5 6 5
5 4 4
5 4 5
5 4 3
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/print-sequences-starting-n-consecutive-difference-limited-k/
625
Chapter 108
Input : abc
Output : a, b, c, ab, bc, ac, abc
Input : aaa
Output : a, aa, aaa
Explanation :
626
Chapter 108. Print all subsequences of a string
Output:
627
Chapter 108. Print all subsequences of a string
Alternate Solution :
One by one fix characters and recursively generates all subsets starting from them. After
every recursive call, we remove last character so that next permutation can be generated.
628
Chapter 108. Print all subsequences of a string
Source
https://www.geeksforgeeks.org/print-subsequences-string/
629
Chapter 109
Input: ED
Output:
D
DE
E
630
Chapter 109. Print all the combinations of a string in lexicographical order
ED
Approach: Count the occurrences of all the characters in the string using a map, then
using recursion all the possible combinations can be printed. Store the elements and their
counts in two different arrays. Three arrays are used, input[] array which has the characters,
count[] array has the count of characters and result[] is a temporary array which is used
in recursion to generate all the combinations. Using recursion and backtracking all the
combinations can be printed.
Below is the implementation of the above approach.
631
Chapter 109. Print all the combinations of a string in lexicographical order
// call the function from level +1
stringCombination(result, str, count,
level + 1, size, length);
// backtracking
count[i]++;
}
}
void combination(string str)
{
// declare the map for store
// each char with occurrence
map<char, int> mp;
for (int i = 0; i < str.size(); i++) {
if (mp.find(str[i]) != mp.end())
mp[str[i]] = mp[str[i]] + 1;
else
mp[str[i]] = 1;
}
// initialize the input array
// with all unique char
char* input = new char[mp.size()];
// initialize the count array with
// occurrence the unique char
int* count = new int[mp.size()];
// temporary char array for store the result
char* result = new char[str.size()];
map<char, int>::iterator it = mp.begin();
int i = 0;
for (it; it != mp.end(); it++) {
// store the element of input array
input[i] = it->first;
// store the element of count array
count[i] = it->second;
i++;
}
632
Chapter 109. Print all the combinations of a string in lexicographical order
Output:
A
AB
ABC
AC
ACB
B
BA
BAC
BC
BCA
C
CA
CAB
CB
CBA
Source
https://www.geeksforgeeks.org/print-all-the-combinations-of-a-string-in-lexicographical-order/
633
Chapter 110
Input : 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10
Output : 1 -> 3 -> 5 -> 7 -> 9
Input : 10 -> 9
Output : 10
Recursive Approach :
1. Initialize a static variable(say flag)
2. If flag is odd print the node
3. increase head and flag by 1, and recurse for next nodes.
C++
634
Chapter 110. Print alternate nodes of a linked list using recursion
// Inserting node at the beginning
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
// Function to print alternate nodes of linked list.
// The boolean flag isOdd is used to find if the current
// node is even or odd.
void printAlternate(struct Node* node, bool isOdd=true)
{
if (node == NULL)
return;
if (isOdd == true)
cout << node->data << " ";
printAlternate(node->next, !isOdd);
}
// Driver code
int main()
{
// Start with the empty list
struct Node* head = NULL;
// construct below list
// 1->2->3->4->5->6->7->8->9->10
push(&head, 10);
push(&head, 9);
push(&head, 8);
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printAlternate(head);
return 0;
}
635
Chapter 110. Print alternate nodes of a linked list using recursion
Output:
1 3 5 7 9
Source
https://www.geeksforgeeks.org/print-alternate-nodes-linked-list-using-recursion/
636
Chapter 111
Method 1 (Recursive)
We can recursively solve this problem. There are total 2n subsets. For every element, we
consider two choices, we include it in a subset and we don’t include it in a subset. Below is
recursive solution based on this idea.
C++
637
Chapter 111. Print sums of all subsets of a given set
{
// Print current subset
if (l > r)
{
cout << sum << " ";
return;
}
// Subset including arr[l]
subsetSums(arr, l+1, r, sum+arr[l]);
// Subset excluding arr[l]
subsetSums(arr, l+1, r, sum);
}
// Driver code
int main()
{
int arr[] = {5, 4, 3};
int n = sizeof(arr)/sizeof(arr[0]);
subsetSums(arr, 0, n-1);
return 0;
}
Java
638
Chapter 111. Print sums of all subsets of a given set
subsetSums(arr, l + 1, r,
sum + arr[l]);
// Subset excluding arr[l]
subsetSums(arr, l + 1, r, sum);
}
// Driver code
public static void main (String[] args)
{
int []arr = {5, 4, 3};
int n = arr.length;
subsetSums(arr, 0, n - 1, 0);
}
}
// This code is contributed by anuj_67
Python3
C#
639
Chapter 111. Print sums of all subsets of a given set
// subsets.
using System;
class GFG {
// Prints sums of all subsets of
// arr[l..r]
static void subsetSums(int []arr, int l,
int r, int sum )
{
// Print current subset
if (l > r)
{
Console.Write(sum + " ");
return;
}
// Subset including arr[l]
subsetSums(arr, l+1, r, sum + arr[l]);
// Subset excluding arr[l]
subsetSums(arr, l+1, r, sum);
}
// Driver code
public static void Main ()
{
int []arr = {5, 4, 3};
int n = arr.Length;
subsetSums(arr, 0, n-1,0);
}
}
// This code is contributed by anuj_67
PHP
<?php
// PHP program to print sums
// of all possible subsets.
// Prints sums of all
// subsets of arr[l..r]
function subsetSums($arr, $l,
$r, $sum = 0)
{
640
Chapter 111. Print sums of all subsets of a given set
Output :
12 9 8 5 7 4 3 0
Method 2 (Iterative)
As discussed above, there are total 2n subsets. The idea is generate loop from 0 to 2n – 1.
For every number, pick all array elements which correspond to 1s in binary representation
of current number.
C++
641
Chapter 111. Print sums of all subsets of a given set
Output :
0 5 4 9 3 8 7 12
Source
https://www.geeksforgeeks.org/print-sums-subsets-given-set/
642
Chapter 112
Input : x = 5, y = 2
Output : 10
Input : x = 100, y = 5
Output : 500
Method
1) If x is less than y, swap the two variables value
2) Recursively find y times the sum of x
3) If any of them become zero, return 0
C++
643
Chapter 112. Product of 2 Numbers using Recursion
Java
644
Chapter 112. Product of 2 Numbers using Recursion
Python3
C#
645
Chapter 112. Product of 2 Numbers using Recursion
PHP
<?php
// PHP Program to find Product
// of 2 Numbers using Recursion
// recursive function to calculate
// multiplication of two numbers
function product($x, $y)
{
// if x is less than
646
Chapter 112. Product of 2 Numbers using Recursion
Output :
10
Improved By : jit_t
Source
https://www.geeksforgeeks.org/product-2-numbers-using-recursion/
647
Chapter 113
It may be assumed that all given values are positive integers and greater than 1.
Examples:
648
Chapter 113. Program for Chocolate and Wrapper Puzzle
C++
649
Chapter 113. Program for Chocolate and Wrapper Puzzle
}
// Driver code
int main()
{
int money = 15 ; // total money
int price = 1; // cost of each candy
int wrap = 3 ; // no of wrappers needs to be
// exchanged for one chocolate.
cout << countMaxChoco(money, price, wrap);
return 0;
}
Java
650
Chapter 113. Program for Chocolate and Wrapper Puzzle
C#
651
Chapter 113. Program for Chocolate and Wrapper Puzzle
652
Chapter 113. Program for Chocolate and Wrapper Puzzle
PHP
<?php
// Recursive PHP program to find maximum
// number of chocolates
// Returns number of chocolates we can
// have from given number of chocolates
// and number of wrappers required to
// get a chocolate.
function countRec($choc, $wrap)
{
// If number of chocolates is less than
// number of wrappers required.
if ($choc < $wrap)
return 0;
// We can immediatly get newChoc using
// wrappers of choc.
$newChoc = $choc/$wrap;
// Now we have "newChoc + choc%wrap" wrappers.
return $newChoc + countRec($newChoc + $choc % $wrap,
$wrap);
}
// Returns maximum number of chocolates we can eat
// with given money, price of chocolate and number
// of wrappers required to get a chocolate.
function countMaxChoco($money, $price, $wrap)
{
// We can directly buy below
// number of chocolates
$choc = $money/$price;
// countRec returns number
// of chocolates we can
// have from given number
// of chocolates
return floor($choc + countRec($choc, $wrap));
}
// Driver code
// total money
$money = 15;
653
Chapter 113. Program for Chocolate and Wrapper Puzzle
Output :
22
In above naive implementation, we noticed that after finding initial number of chocolates,
we recursively divide the number of chocolates with the number of wrappers required. until
we left with 1 chocolate or wrapper.
We are recomputing the values i.e. ((choc/wrap + choc%wrap)/wrap until we get 1.
It is observed that, we can get the result by just reducing the values of chocolates and
wrappers by 1 and then divide them to get the result (choc-1)/(wrap-1)
C++
654
Chapter 113. Program for Chocolate and Wrapper Puzzle
return 0;
// First find number of chocolates that
// can be purchased with the given amount
int choc = money / price;
// Now just add number of chocolates with the
// chocolates gained by wrapprices
choc = choc + (choc - 1) / (wrap - 1);
return choc;
}
// Driver code
int main()
{
int money = 15 ; // total money
int price = 1; // cost of each candy
int wrap = 3 ; // no of wrappers needs to be
// exchanged for one chocolate.
cout << countMaxChoco(money, price, wrap);
return 0;
}
Java
655
Chapter 113. Program for Chocolate and Wrapper Puzzle
// Now just add number of chocolates
// with the chocolates gained by
// wrapprices
choc = choc + (choc - 1) / (wrap - 1);
return choc;
}
// Driver code
public static void main (String[] args)
{
// total money
int money = 15;
// cost of each candy
int price = 1;
// no of wrappers needs to be
int wrap = 3 ;
// exchanged for one chocolate.
System.out.println(
countMaxChoco(money, price, wrap));
}
}
// This code is contributed by anuj_67.
C#
656
Chapter 113. Program for Chocolate and Wrapper Puzzle
// First find number of chocolates
// that can be purchased with the
// given amount
int choc = money / price;
// Now just add number of chocolates
// with the chocolates gained by
// wrapprices
choc = choc + (choc - 1) / (wrap - 1);
return choc;
}
// Driver code
public static void Main ()
{
// total money
int money = 15;
// cost of each candy
int price = 1;
// no of wrappers needs to be
int wrap = 3 ;
// exchanged for one chocolate.
Console.WriteLine(
countMaxChoco(money, price, wrap));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// Efficient PHP program to find maximum
// number of chocolates
// Returns maximum number
// of chocolates we can eat
// with given money, price
// of chocolate and number
// of wrapprices required
// to get a chocolate.
function countMaxChoco($money, $price, $wrap)
{
657
Chapter 113. Program for Chocolate and Wrapper Puzzle
Output :
22
Source
https://www.geeksforgeeks.org/program-chocolate-wrapper-puzzle/
658
Chapter 114
Input : n = 687
Output : 21
Input : n = 12
Output : 3
659
Chapter 114. Program for Sum the digits of a given number
n = n/10;
}
return sum;
}
int main()
{
int n = 687;
printf(" %d ", getSum(n));
return 0;
}
Java
Python3
# Python 3 program to
660
Chapter 114. Program for Sum the digits of a given number
C#
// C# program to compute
// sum of digits in number.
using System;
class GFG
{
/* Function to get sum of digits */
static int getSum(int n)
{
int sum = 0;
while (n != 0)
{
sum = sum + n % 10;
n = n/10;
}
return sum;
}
// Driver program
public static void Main()
{
int n = 687;
Console.Write(getSum(n));
}
}
// This code is contributed by Sam007
661
Chapter 114. Program for Sum the digits of a given number
PHP
<?php
// PHP Code to compute sum
// of digits in number.
// Function to get
// $sum of digits
function getsum($n)
{
$sum = 0;
while ($n != 0)
{
$sum = $sum + $n % 10;
$n = $n/10;
}
return $sum;
}
// Driver Code
$n = 687;
$res = getsum($n);
echo("$res");
// This code is contributed by
// Smitha Dinesh Semwal.
?>
Output :
21
# include<stdio.h>
/* Function to get sum of digits */
int getSum(int n)
{
int sum;
/* Single line that calculates sum */
for (sum = 0; n > 0; sum += n % 10, n /= 10);
662
Chapter 114. Program for Sum the digits of a given number
return sum;
}
int main()
{
int n = 687;
printf(" %d ", getSum(n));
return 0;
}
Java
Python3
663
Chapter 114. Program for Sum the digits of a given number
sum = 0
# Single line that calculates sum
while(n > 0):
sum += int(n%10)
n = int(n/10)
return sum
# Driver code
n = 687
print(getSum(n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to compute
// sum of digits in number.
using System;
class GFG
{
static int getSum(int n)
{
int sum;
/* Single line that calculates sum */
for (sum = 0; n > 0; sum += n % 10,
n /= 10);
return sum;
}
// Driver code
public static void Main()
{
int n = 687;
Console.Write(getSum(n));
}
}
// This code is contributed by Sam007
PHP
664
Chapter 114. Program for Sum the digits of a given number
<?php
// PHP Code for Sum the
// digits of a given number
// Function to get sum of digits
function getsum($n)
{
// Single line that calculates $sum
for ($sum = 0; $n > 0; $sum += $n % 10,
$n /= 10);
return $sum;
}
// Driver Code
$n = 687;
echo(getsum($n));
// This code is contributed by
// Smitha Dinesh Semwal.
?>
Output :
21
2. Recursive
Thanks to ayesha for providing the below recursive solution.
Java
665
Chapter 114. Program for Sum the digits of a given number
import java.io.*;
class GFG {
/* Function to get sum of digits */
static int sumDigits(int no)
{
return no == 0 ? 0 : no%10 +
sumDigits(no/10) ;
}
// Driver code
public static void main(String[] args)
{
System.out.println(sumDigits(687));
}
}
// This code is contributed by Gitanjali
Python3
C#
// C# program to compute
// sum of digits in number.
using System;
class GFG
{
/* Function to get sum of digits */
static int sumDigits(int no)
{
return no == 0 ? 0 : no % 10 +
sumDigits(no / 10);
666
Chapter 114. Program for Sum the digits of a given number
}
// Driver code
public static void Main()
{
Console.Write(sumDigits(687));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to compute
// sum of digits in number.
function sumDigits($no)
{
return $no == 0 ? 0 : $no % 10 +
sumDigits($no / 10) ;
}
// Driver Code
echo sumDigits(687);
// This code is contributed by aj_36
?>
Output :
21
Improved By : jit_t
Source
https://www.geeksforgeeks.org/program-for-sum-the-digits-of-a-given-number/
667
Chapter 115
recLen(str)
{
If str is NULL
return 0
Else
return 1 + recLen(str + 1)
}
C++
668
Chapter 115. Program for length of a string using recursion
Java
669
Chapter 115. Program for length of a string using recursion
}
}
// This code is contributed by Sam007.
Python3
C#
670
Chapter 115. Program for length of a string using recursion
return recLen(str.Substring(1)) + 1;
}
/* Driver program to test above function */
public static void Main()
{
string str ="GeeksforGeeks";
Console.WriteLine(recLen(str));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to calculate
// length of a string using
// recursion
// Function to
// calculate length
function recLen(&$str, $i)
{
// if we reach at the
// end of the string
if ($i == strlen($str))
return 0;
else
return 1 +
recLen($str,
$i + 1);
}
// Driver Code
$str = "GeeksforGeeks";
echo (recLen($str, 0));
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
13
671
Chapter 115. Program for length of a string using recursion
Source
https://www.geeksforgeeks.org/program-for-length-of-a-string-using-recursion/
672
Chapter 116
1
2 3
4 5 6
7 8 9 10
You can put water to only top glass. If you put more than 1 litre water to 1st glass, water
overflows and fills equally in both 2nd and 3rd glasses. Glass 5 will get water from both
2nd glass and 3rd glass and so on.
If you have X litre of water and you put that water in top glass, how much water will be
contained by jth glass in ith row?
Example. If you will put 2 litre on top.
1st – 1 litre
2nd – 1/2 litre
3rd – 1/2 litre
The approach is similar to Method 2 of the Pascal’s Triangle. If we take a closer look at the
problem, the problem boils down to Pascal’s Triangle.
1 ---------------- 1
2 3 ---------------- 2
4 5 6 ------------ 3
7 8 9 10 --------- 4
673
Chapter 116. Program to find amount of water in a given glass
Each glass contributes to the two glasses down the glass. Initially, we put all water in first
glass. Then we keep 1 litre (or less than 1 litre) in it, and move rest of the water to two
glasses down to it. We follow the same process for the two glasses and all other glasses till
ith row. There will be i*(i+1)/2 glasses till ith row.
C++
674
Chapter 116. Program to find amount of water in a given glass
Java
675
Chapter 116. Program to find amount of water in a given glass
System.out.println("Incorrect Input");
System.exit(0);
}
// There will be i*(i+1)/2 glasses
// till ith row (including ith row)
int ll = Math.round((i * (i + 1) ));
float[] glass = new float[ll + 2];
// Put all water in first glass
int index = 0;
glass[index] = X;
// Now let the water flow to the
// downward glasses till the row
// number is less than or/ equal
// to i (given row)
// correction : X can be zero for side
// glasses as they have lower rate to fill
for (int row = 1; row <= i ; ++row)
{
// Fill glasses in a given row. Number of
// columns in a row is equal to row number
for (int col = 1;
col <= row; ++col, ++index)
{
// Get the water from current glass
X = glass[index];
// Keep the amount less than or
// equal to capacity in current glass
glass[index] = (X >= 1.0f) ? 1.0f : X;
// Get the remaining amount
X = (X >= 1.0f) ? (X - 1) : 0.0f;
// Distribute the remaining amount
// to the down two glasses
glass[index + row] += X / 2;
glass[index + row + 1] += X / 2;
}
}
// The index of jth glass in ith
// row will be i*(i-1)/2 + j - 1
return glass[(int)(i * (i - 1) /
2 + j - 1)];
}
676
Chapter 116. Program to find amount of water in a given glass
// Driver Code
public static void main(String[] args)
{
int i = 2, j = 2;
float X = 2.0f; // Total amount of water
System.out.println("Amount of water in jth " +
"glass of ith row is: " +
findWater(i, j, X));
}
}
// This code is contributed by mits
Python3
677
Chapter 116. Program to find amount of water in a given glass
C#
// Program to find the amount
// of water in j-th glass
// of i-th row
using System;
class GFG
678
Chapter 116. Program to find amount of water in a given glass
{
// Returns the amount of water
// in jth glass of ith row
static float findWater(int i, int j,
float X)
{
// A row number i has maximum i
// columns. So input column
// number must be less than i
if (j > i)
{
Console.WriteLine(“Incorrect Input”);
Environment.Exit(0);
}
// There will be i*(i+1)/2 glasses
// till ith row (including ith row)
int ll = (int)Math.Round((double)(i * (i + 1)));
float[] glass = new float[ll + 2];
// Put all water in first glass
int index = 0;
glass[index] = X;
// Now let the water flow to the
// downward glasses till the row
// number is less than or/ equal
// to i (given row)
// correction : X can be zero
// for side glasses as they have
// lower rate to fill
for (int row = 1; row <= i ; ++row) { // Fill glasses in a given row. // Number of columns
in a row // is equal to row number for (int col = 1; col <= row; ++col, ++index) { // Get
the water from current glass X = glass[index]; // Keep the amount less than // or equal to
capacity in // current glass glass[index] = (X >= 1.0f) ?
1.0f : X;
// Get the remaining amount
X = (X >= 1.0f) ? (X – 1) : 0.0f;
// Distribute the remaining amount
// to the down two glasses
glass[index + row] += X / 2;
glass[index + row + 1] += X / 2;
}
}
// The index of jth glass in ith
// row will be i*(i-1)/2 + j – 1
return glass[(int)(i * (i – 1) /
2 + j – 1)];
679
Chapter 116. Program to find amount of water in a given glass
}
// Driver Code
static void Main()
{
int i = 2, j = 2;
float X = 2.0f; // Total amount of water
Console.WriteLine(“Amount of water in jth ” +
“glass of ith row is: ” +
findWater(i, j, X));
}
}
// This code is contributed by mits
PHP
<?php
// Program to find the amount
// of water in j-th glass of
// i-th row
// Returns the amount of water
// in jth glass of ith row
function findWater($i, $j, $X)
{
// A row number i has maximum
// i columns. So input column
// number must be less than i
if ($j > $i)
{
echo "Incorrect Input\n";
return;
}
// There will be i*(i+1)/2
// glasses till ith row
// (including ith row)
// and Initialize all glasses
// as empty
$glass = array_fill(0, (int)($i *
($i + 1) / 2), 0);
// Put all water
// in first glass
$index = 0;
$glass[$index] = $X;
// Now let the water flow to
680
Chapter 116. Program to find amount of water in a given glass
681
Chapter 116. Program to find amount of water in a given glass
str_pad(findWater($i, $j,
$X), 8, '0');
// This Code is contributed by mits
?>
Output:
Source
https://www.geeksforgeeks.org/find-water-in-a-glass/
682
Chapter 117
C++
683
Chapter 117. Program to find the minimum (or maximum) element of an array
int main()
{
int arr[] = { 12, 1234, 45, 67, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Minimum element of array: " << getMin(arr, n) << "\n";
cout << "Maximum element of array: " << getMax(arr, n);
return 0;
}
Java
684
Chapter 117. Program to find the minimum (or maximum) element of an array
Python3
C#
// C# program to find
// minimum (or maximum)
// element in an array.
using System;
class GFG
{
static int getMin(int []arr,
int n)
{
int res = arr[0];
for (int i = 1; i < n; i++)
res = Math.Min(res, arr[i]);
return res;
}
685
Chapter 117. Program to find the minimum (or maximum) element of an array
PHP
<?php
// PHP program to find minimum
// (or maximum) element in an
// array.
function getMin($arr, $n)
{
$res = $arr[0];
for ($i = 1; $i < $n; $i++)
$res = min($res, $arr[$i]);
return $res;
}
function getMax($arr, $n)
{
$res = $arr[0];
for ($i = 1; $i < $n; $i++)
$res = max($res, $arr[$i]);
return $res;
}
686
Chapter 117. Program to find the minimum (or maximum) element of an array
// Driver Code
$arr = array(12, 1234, 45, 67, 1);
$n = sizeof($arr);
echo "Minimum element of array: "
, getMin($arr, $n), "\n";
echo "Maximum element of array: "
,getMax($arr, $n);
// This code is contributed by ajit
?>
Output:
Time Complexity:O(n)
Recursive Solution
C++
687
Chapter 117. Program to find the minimum (or maximum) element of an array
Output:
Min of array: 1
Max of array: 1234
C++
Output:
Min of array: 1
Max of array: 1234
688
Chapter 117. Program to find the minimum (or maximum) element of an array
Source
https://www.geeksforgeeks.org/program-find-minimum-maximum-element-array/
689
Chapter 118
For example, for n = 12, we get the sequence 12, 6, 3, 10, 5, 16, 8, 4, 2, 1.
Examples:
Input : n = 4
Output : Yes
Input : n = 5
Output : Yes
The idea is to simply follow given rules and recursively call function with reduced values
until it reaches 1. If a value is seen again during recursion, then there is a cycle and we
can’t reach 1. In this case, we return false.
C++
690
Chapter 118. Program to implement Collatz Conjecture
Output:
Yes
The above program is inefficient. The idea is to use Collatz Conjecture. It states that if n
is a positive then somehow it will reaches to 1 after a certain amount of time. So, by using
this fact it can be done in O(1) i.e. just check if n is a positive integer or not.
Note that the answer would be false for negative numbers. For negative numbers, the above
operations would keep number negative and it would never reach 1.
C++
691
Chapter 118. Program to implement Collatz Conjecture
Java
692
Chapter 118. Program to implement Collatz Conjecture
Python 3
C#
// C# program to implement
// Collatz Conjecture
using System;
class GFG {
// Function to find if n
// reaches to 1 or not.
static bool isToOne(int n)
{
// Return true if n
// is positive
return (n > 0);
}
// Drivers code
public static void Main()
{
int n = 5;
693
Chapter 118. Program to implement Collatz Conjecture
if(isToOne(n) == true)
Console.Write("Yes") ;
else
Console.Write("No");
}
}
// This code is contributed
// by Smitha.
Output:
Yes
Source
https://www.geeksforgeeks.org/c-program-implement-collatz-conjecture/
694
Chapter 119
C++
695
Chapter 119. Program to reverse a string (Iterative and Recursive)
Output:
skeegrofskeeg
696
Chapter 119. Program to reverse a string (Iterative and Recursive)
Java
Python
697
Chapter 119. Program to reverse a string (Iterative and Recursive)
# initialising a empty
# string 'str1'
str1 = ''
i = n - 1
while i >= 0:
# copy str
# to str1
str1 += str[i]
i -= 1
print(str1)
# Driver Code
def main():
str = "geeksforgeeks";
reverseStr(str);
if __name__=="__main__":
main()
# This code is contributed
# by prabhat kumar singh
PHP
<?php
// A Simple Iterative PHP
// program to reverse
// a string
// Function to reverse a string
function reverseStr(&$str)
{
$n = strlen($str);
// Swap character starting
// from two corners
for ($i = 0; $i < $n / 2; $i++)
//swap the string
list($str[$i],
$str[$n - $i - 1]) = array($str[$n - $i - 1],
$str[$i]);
}
// Driver Code
$str = "geeksforgeeks";
698
Chapter 119. Program to reverse a string (Iterative and Recursive)
reverseStr($str);
echo $str;
// This code is contributed by ajit
?>
Output:
skeegrofskeeg
C++
PHP
<?php
699
Chapter 119. Program to reverse a string (Iterative and Recursive)
Output:
skeegrofskeeg
C++
700
Chapter 119. Program to reverse a string (Iterative and Recursive)
Output:
skeegrofskeeg
C++
Python
701
Chapter 119. Program to reverse a string (Iterative and Recursive)
# reverse a string
def reverseStr(str):
# print the string
# from last
print(str[::-1])
# Driver Code
def main():
str = "geeksforgeeks";
reverseStr(str);
if __name__=="__main__":
main()
# This code is contributed
# by prabhat kumar singh
Output:
skeegrofskeeg
Source
https://www.geeksforgeeks.org/program-reverse-string-iterative-recursive/
702
Chapter 120
703
Chapter 120. Python | Convert a nested list into a flat list
Output:
Source
https://www.geeksforgeeks.org/python-convert-a-nested-list-into-a-flat-list/
704
Chapter 121
Recaman’s sequence
Input : n = 6
Output : 0, 1, 3, 6, 2, 7
Input : n = 17
Output : 0, 1, 3, 6, 2, 7, 13, 20, 12, 21,
11, 22, 10, 23, 9, 24, 8
a(0) = 0,
if n > 0 and the number is not
already included in the sequence,
a(n) = a(n - 1) - n
else
a(n) = a(n-1) + n.
C++
705
Chapter 121. Recaman’s sequence
Java
706
Chapter 121. Recaman’s sequence
// sequence
import java.io.*;
class GFG {
// Prints first n terms of Recaman sequence
static void recaman(int n)
{
// Create an array to store terms
int arr[] = new int[n];
// First term of the sequence is always 0
arr[0] = 0;
System.out.print(arr[0]+" ,");
// Fill remaining terms using recursive
// formula.
for (int i = 1; i < n; i++)
{
int curr = arr[i - 1] - i;
int j;
for (j = 0; j < i; j++)
{
// If arr[i-1] - i is negative or
// already exists.
if ((arr[j] == curr) || curr < 0)
{
curr = arr[i - 1] + i;
break;
}
}
arr[i] = curr;
System.out.print(arr[i]+", ");
}
}
// Driver code
public static void main (String[] args)
{
int n = 17;
recaman(n);
}
}
// This code is contributed by vt_m
707
Chapter 121. Recaman’s sequence
Python 3
C#
708
Chapter 121. Recaman’s sequence
class GFG {
// Prints first n terms of Recaman sequence
static void recaman(int n)
{
// Create an array to store terms
int []arr = new int[n];
// First term of the sequence is always 0
arr[0] = 0;
Console.Write(arr[0]+" ,");
// Fill remaining terms using recursive
// formula.
for (int i = 1; i < n; i++)
{
int curr = arr[i - 1] - i;
int j;
for (j = 0; j < i; j++)
{
// If arr[i-1] - i is negative or
// already exists.
if ((arr[j] == curr) || curr < 0)
{
curr = arr[i - 1] + i;
break;
}
}
arr[i] = curr;
Console.Write(arr[i]+", ");
}
}
// Driver code
public static void Main ()
{
int n = 17;
recaman(n);
}
}
// This code is contributed by vt_m.
PHP
709
Chapter 121. Recaman’s sequence
<?php
// PHP program to print n-th
// number in Recaman's sequence
// Prints first n terms
// of Recaman sequence
function recaman($n)
{
// First term of the
// sequence is always 0
$arr[0] = 0;
echo $arr[0], ", ";
// Fill remaining terms
// using recursive formula.
for ($i = 1; $i < $n; $i++)
{
$curr = $arr[$i - 1] - $i;
$j;
for ($j = 0; $j < $i; $j++)
{
// If arr[i-1] - i
// is negative or
// already exists.
if (($arr[$j] == $curr) || $curr < 0)
{
$curr = $arr[$i-1] + $i;
break;
}
}
$arr[$i] = $curr;
echo $arr[$i], ", ";
}
}
// Driver Code
$n = 17;
recaman($n);
// This code is contributed by Ajit
?>
Output:
710
Chapter 121. Recaman’s sequence
Optimizations :
We can us hashing to store previously computed values and can make this program work in
O(n) time.
711
Chapter 121. Recaman’s sequence
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/recamans-sequence/
712
Chapter 122
Recursion
Recursion - GeeksforGeeks
What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain
problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH),
Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
What is base condition in recursion?
In recursive program, the solution to base case is provided and solution of bigger problem
is expressed in terms of smaller problems.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, base case for n < = 1 is defined and larger value of number can be
solved by converting to smaller one till base case is reached.
How a particular problem is solved using recursion?
The idea is represent a problem in terms of one or more smaller problems, and add one or
more base conditions that stop recursion. For example, we compute factorial n if we know
factorial of (n-1). Base case for factorial would be n = 0. We return 1 when n = 0.
Why Stack Overflow error occurs in recursion?
If base case is not reached or not defined, then stack overflow problem may arise. Let us
take an example to understand this.
713
Chapter 122. Recursion
int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;
else
return n*fact(n-1);
}
If fact(10) is called, it will call fact(9), fact(8), fact(7) and so on but number will never
reach 100. So, the base case is not reached. If the memory is exhausted by these functions
on stack, it will cause stack overflow error.
What is the difference between direct and indirect recursion?
A function fun is called direct recursive if it calls the same function fun. A function fun
is called indirect recursive if it calls another function say fun_new and fun_new calls fun
directly or indirectly. Difference between direct and indirect recursion has been illustrated
in Table 1.
directRecFun();
// Some code...
}
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
714
Chapter 122. Recursion
// Some code...
}
CPP
Java
715
Chapter 122. Recursion
{
if (test < 1)
return;
else
{
System.out.printf("%d ",test);
printFun(test-1); // statement 2
System.out.printf("%d ",test);
return;
}
}
public static void main(String[] args)
{
int test = 3;
printFun(test);
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python3
# A Python 3 program to
# demonstrate working of
# recursion
def printFun(test):
if (test < 1):
return
else:
print( test,end = " ")
printFun(test-1) # statement 2
print( test,end = " ")
return
test = 3
printFun(test)
# This code is contributed by
# Smitha Dinesh Semwal
C#
716
Chapter 122. Recursion
// A C# program to demonstrate
// working of recursion
using System;
class GFG {
// function to demonstrate
// working of recursion
static void printFun(int test)
{
if (test < 1)
return;
else
{
Console.Write(test + " ");
// statement 2
printFun(test - 1);
Console.Write(test + " ");
return;
}
}
// Driver Code
public static void Main(String[] args)
{
int test = 3;
printFun(test);
}
}
// This code is contributed by Anshul Aggarwal.
PHP
<?php
// PHP program to demonstrate
// working of recursion
// function to demonstrate
// working of recursion
function printFun($test)
{
if ($test < 1)
return;
else
{
717
Chapter 122. Recursion
echo("$test ");
// statement 2
printFun($test-1);
echo("$test ");
return;
}
}
// Driver Code
$test = 3;
printFun($test);
// This code is contributed by
// Smitha Dinesh Semwal.
?>
Output :
3 2 1 1 2 3
When printFun(3) is called from main(), memory is allocated to printFun(3) and a local
variable test is initialized to 3 and statement 1 to 4 are pushed on the stack as shown in
below diagram. It first prints ‘3’. In statement 2, printFun(2) is called and memory is
allocated to printFun(2) and a local variable test is initialized to 2 and statement 1 to 4
are pushed in the stack. Similarly, printFun(2) calls printFun(1) and printFun(1) calls
printFun(0). printFun(0) goes to if statement and it return to printFun(1). Remaining
statements of printFun(1) are executed and it returns to printFun(2) and so on. In the
output, value from 3 to 1 are printed and then 1 to 3 are printed. The memory stack has
been shown in below diagram.
718
Chapter 122. Recursion
719
Chapter 122. Recursion
Source
https://www.geeksforgeeks.org/recursion/
720
Chapter 123
Recursive Approach to find nth node from the end in the linked list - GeeksforGeeks
Find the nth node from the end in the given linked list using a recursive approach.
Examples:
Algorithm:
findNthFromLastUtil(head, n)
Initialize nth_last = NULL
Initialize count = 0
721
Chapter 123. Recursive Approach to find nth node from the end in the linked list
722
Chapter 123. Recursive Approach to find nth node from the end in the linked list
*count = *count + 1;
// if true, then head is the nth node from the last
if (*count == n)
*nth_last = head;
}
// utility function to find the nth node from
// the last of the linked list
void findNthFromLastUtil(Node* head, int n)
{
// Initialize
Node* nth_last = NULL;
int count = 0;
// find nth node from the last
findNthFromLast(head, n, &count, &nth_last);
// if node exists, then print it
if (nth_last != NULL)
cout << "Nth node from last is: "
<< nth_last->data;
else
cout << "Node does not exists";
}
// Driver program to test above
int main()
{
// linked list: 4->2->1->5->3
Node* head = getNode(4);
head->next = getNode(2);
head->next->next = getNode(1);
head->next->next->next = getNode(5);
head->next->next->next->next = getNode(3);
int n = 2;
findNthFromLastUtil(head, n);
return 0;
}
Java
// Java implementation to recursively
// find the nth node from the last
// of the linked list
import java.util.*;
723
Chapter 123. Recursive Approach to find nth node from the end in the linked list
class GFG
{
static int count = 0, data = 0;
// a node of a linked list
static class Node
{
int data;
Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate space
Node newNode = new Node();
// put in data
newNode.data = data;
newNode.next = null;
return newNode;
}
// funnction to recursively
// find the nth node from
// the last of the linked list
static void findNthFromLast(Node head, int n,
Node nth_last)
{
// if list is empty
if (head == null)
return;
// recursive call
findNthFromLast(head.next, n, nth_last);
// increment count
count = count + 1;
// if true, then head is the
// nth node from the last
if (count == n)
{
data = head.data;
}
}
// utility function to find
// the nth node from the last
// of the linked list
static void findNthFromLastUtil(Node head, int n)
{
724
Chapter 123. Recursive Approach to find nth node from the end in the linked list
// Initialize
Node nth_last = new Node();
count = 0;
// find nth node from the last
findNthFromLast(head, n, nth_last);
// if node exists, then print it
if (nth_last != null)
System.out.println(“Nth node from last is: ” +
data);
else
System.out.println(“Node does not exists”);
}
// Driver Code
public static void main(String args[])
{
// linked list: 4.2.1.5.3
Node head = getNode(4);
head.next = getNode(2);
head.next.next = getNode(1);
head.next.next.next = getNode(5);
head.next.next.next.next = getNode(3);
int n = 2;
findNthFromLastUtil(head, n);
}
}
// This code is contributed
// by Arnab Kundu
Output:
Time Complexity: O(n), where ‘n’ is the number of nodes in the linked list.
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/recursive-approach-to-find-nth-node-from-the-end-in-the-linked-list/
725
Chapter 124
726
Chapter 124. Recursive Bubble Sort
{
for (i = 0; i < n-1; i++)
727
Chapter 124. Recursive Bubble Sort
Java
728
Chapter 124. Recursive Bubble Sort
arr[i+1] = temp;
}
// Largest element is fixed,
// recur for remaining array
bubbleSort(arr, n-1);
}
// Driver Method
public static void main(String[] args)
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr, arr.length);
System.out.println("Sorted array : ");
System.out.println(Arrays.toString(arr));
}
}
Python3
C#
729
Chapter 124. Recursive Bubble Sort
730
Chapter 124. Recursive Bubble Sort
// This code is contributed
// by Sam007
Output :
Sorted array :
11 12 22 25 34 64 90
Improved By : Sam007
Source
https://www.geeksforgeeks.org/recursive-bubble-sort/
731
Chapter 125
Recursive Functions
732
Chapter 125. Recursive Functions
proximately 1.6n . It means the same computer takes almost 60% more time for next Fi-
bonacci number. Recursive Fibonacci algorithm has overlapped subproblems. There are
other techniques like dynamic programming to improve such overlapped algorithms.
However, few algorithms, (e.g. merge sort, quick sort, etc…) results in optimal time com-
plexity using recursion.
Base Case:
One critical requirement of recursive functions is termination point or base case. Every
recursive program must have base case to make sure that the function will terminate. Miss-
ing base case results in unexpected behaviour.
Different Ways of Writing Recursive Functions
Function calling itself: (Direct way)
Most of us aware atleast two different ways of writing recursive programs. Given below is
towers of Hanoi code. It is an example of direct calling.
CPP
733
Chapter 125. Recursive Functions
Java
Python3
734
Chapter 125. Recursive Functions
# Move first n-1 disks
# from source pole
# to auxiliary pole
# using destination as
# temporary pole
tower(n-1, sourcePole, auxiliaryPole, destinationPole)
# Move the remaining
# disk from source
# pole to destination pole
print("Move the disk",sourcePole,"from",sourcePole,"to",destinationPole)
# Move the n-1 disks from
# auxiliary (now source)
# pole to destination pole
# using source pole as
# temporary (auxiliary) pole
tower(n-1, auxiliaryPole, destinationPole,sourcePole)
# Driver code
tower(3, 'S', 'D', 'A')
C#
735
Chapter 125. Recursive Functions
PHP
<?php
// Assuming n-th disk is
// bottom disk (count down)
function tower($n, $sourcePole,
$destinationPole,
$auxiliaryPole)
{
// Base case
// (termination condition)
if(0 == $n)
return;
// Move first n-1 disks
// from source pole to
// auxiliary pole using
// destination as temporary
// pole
tower($n - 1, $sourcePole,
$auxiliaryPole,
$destinationPole);
// Move the remaining
736
Chapter 125. Recursive Functions
Output :
Indirect calling. Though least pratical, a function [funA()] can call another function
737
Chapter 125. Recursive Functions
[funB()] which inturn calls [funA()] former function. In this case both the functions should
have the base case.
Defensive Programming:
We can combine defensive coding techniques with recursion for graceful functionality of
application. Usually recursive programming is not allowed in safety critical applications,
such as flight controls, health monitoring, etc. However, one can use a static count technique
to avoid uncontrolled calls (NOT in safety critical systems, may be used in soft real time
systems).
callDepth depth depends on function stack frame size and maximum stack size.
Recursion using function pointers: (Indirect way)
Recursion can also implemented with function pointers. An example is signal han-
dler in POSIX complaint systems. If the handler causes to trigger same event due to which
the handler being called, the function will reenter.
Related Articles:
Thanks to Venki for writing the above post. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : jit_t
738
Chapter 125. Recursive Functions
Source
https://www.geeksforgeeks.org/recursive-functions/
739
Chapter 126
Recursive Implementation of
atoi()
740
Chapter 126. Recursive Implementation of atoi()
int main(void)
{
char str[] = "112";
int n = strlen(str);
printf("%d", myAtoiRecursive(str, n));
return 0;
}
Output:
112
This article is contributed by Narendra Kangralkar. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/recursive-implementation-of-atoi/
741
Chapter 127
Example:
742
Chapter 127. Recursive Insertion Sort
743
Chapter 127. Recursive Insertion Sort
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
for (int i=0; i < n; i++)
cout << arr[i] <<" ";
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
insertionSortRecursive(arr, n);
printArray(arr, n);
return 0;
}
Java
744
Chapter 127. Recursive Insertion Sort
{
arr[j+1] = arr[j];
j--;
}
arr[j+1] = last;
}
// Driver Method
public static void main(String[] args)
{
int arr[] = {12, 11, 13, 5, 6};
insertionSortRecursive(arr, arr.length);
System.out.println(Arrays.toString(arr));
}
}
Python
745
Chapter 127. Recursive Insertion Sort
# Driver program to test insertion sort
arr = [12,11,13,5,6]
n = len(arr)
insertionSortRecursive(arr, n)
printArray(arr, n)
# Contributed by Harsh Valecha
C#
// Recursive C# program
// for insertion sort
using System;
class GFG
{
// Recursive function to sort
// an array using insertion sort
static void insertionSortRecursive(int []arr,
int n)
{
// Base case
if (n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive(arr, n - 1);
// Insert last element at
// its correct position
// in sorted array.
int last = arr[n - 1];
int j = n - 2;
/* Move elements of arr[0..i-1],
that are greater than key, to
one position ahead of their
current position */
while (j >= 0 && arr[j] > last)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = last;
}
746
Chapter 127. Recursive Insertion Sort
//Driver Code
static void Main()
{
int []arr = {12, 11, 13, 5, 6};
insertionSortRecursive(arr, arr.Length);
for(int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Sam007
PHP
<?php
// Recursive PHP program for insertion sort
// Recursive function to sort an
// array using insertion sort
function insertionSortRecursive(&$arr, $n)
{
// Base case
if ($n <= 1)
return;
// Sort first n-1 elements
insertionSortRecursive($arr, $n - 1);
// Insert last element at its correct
// position in sorted array.
$last = $arr[$n - 1];
$j = $n - 2;
// Move elements of arr[0..i-1], that are
// greater than key, to one position ahead
// of their current position
while ($j >= 0 && $arr[$j] > $last)
{
$arr[$j + 1] = $arr[$j];
$j--;
}
$arr[$j + 1] = $last;
}
// A utility function to
747
Chapter 127. Recursive Insertion Sort
Output :
5 6 11 12 13
Source
https://www.geeksforgeeks.org/recursive-insertion-sort/
748
Chapter 128
• Recursion
• Recursive Functions
• Tail Recursion
749
Chapter 128. Recursive Practice Problems with Solutions
750
Chapter 128. Recursive Practice Problems with Solutions
751
Chapter 129
752
Chapter 130
Source
https://www.geeksforgeeks.org/recursion-practice-problems-solutions/
753
Chapter 131
Input : 3
Output :
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 3 from rod A to rod D
Move disk 2 from rod C to rod D
Move disk 1 from rod B to rod D
Input : 5
Output :
Move disk 1 from rod A to rod C
754
Chapter 131. Recursive Tower of Hanoi using 4 pegs / rods
C/C++
755
Chapter 131. Recursive Tower of Hanoi using 4 pegs / rods
Java
756
Chapter 131. Recursive Tower of Hanoi using 4 pegs / rods
Python 3
C#
757
Chapter 131. Recursive Tower of Hanoi using 4 pegs / rods
// recursive function to solve
// Tower of Hanoi puzzle
static void towerOfHanoi(int n, char from_rod,
char to_rod, char aux_rod1,
char aux_rod2)
{
if (n == 0)
return;
if (n == 1) {
Console.WriteLine("Move disk " + n +
" from rod " + from_rod +
" to rod " + to_rod);
return;
}
towerOfHanoi(n - 2, from_rod, aux_rod1,
aux_rod2, to_rod);
Console.WriteLine("Move disk " + (n - 1)
+ " from rod " + from_rod
+ " to rod " + aux_rod2);
Console.WriteLine("Move disk " + n +
" from rod " + from_rod
+ " to rod " + to_rod);
Console.WriteLine("Move disk " + (n - 1)
+ " from rod " + aux_rod2
+ " to rod " + to_rod);
towerOfHanoi(n - 2, aux_rod1, to_rod,
from_rod, aux_rod2);
}
// Driver method
public static void Main()
{
int n = 4; // Number of disks
// A, B, C and D are names of rods
towerOfHanoi(n, 'A', 'D', 'B', 'C');
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// Recursive PHP program -
// Tower of Hanoi
758
Chapter 131. Recursive Tower of Hanoi using 4 pegs / rods
// Recursive function to solve
// Tower of Hanoi puzzle
function towerOfHanoi($n, $from_rod, $to_rod,
$aux_rod1, $aux_rod2)
{
if ($n == 0)
return;
if ($n == 1)
{
echo"\n", "Move disk", $n
, " from rod ", $from_rod
, " to rod", $to_rod;
return;
}
towerOfHanoi($n - 2, $from_rod,
$aux_rod1, $aux_rod2,
$to_rod);
echo "\n Move disk ", $n - 1,
" from rod ", $from_rod,
" to rod ", $aux_rod2;
echo "\n Move disk ", $n,
" from rod ", $from_rod,
" to rod ", $to_rod ;
echo "\n Move disk ", $n-1,
" from rod ", $aux_rod2,
" to rod ", $to_rod;
towerOfHanoi($n - 2, $aux_rod1,
$to_rod, $from_rod,
$aux_rod2);
}
// Driver Code
// Number of disks
$n = 4;
// A, B, C and D are
// names of rods
towerOfHanoi($n, 'A', 'D', 'B', 'C');
// This code is contributed by Ajit
?>
759
Chapter 131. Recursive Tower of Hanoi using 4 pegs / rods
Output:
Source
https://www.geeksforgeeks.org/recursive-tower-hanoi-using-4-pegs-rods/
760
Chapter 132
Input : 1 2 3 4 5 6 7
Output : 1 3 5 7
2 4 6
Input : 1 4 5 6
Output : 1 5
4 6
761
Chapter 132. Recursive approach for alternating split of Linked List
// Function to push nodes
// into linked list
void push(Node** head, int new_data)
{
Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head);
(*head) = new_node;
}
// We basically remove link between 'a'
// and its next. Similarly we remove link
// between 'b' and its next. Then we recur
// for remaining lists.
void moveNode(Node* a, Node* b)
{
if (b == NULL || a == NULL)
return;
if (a->next != NULL)
a->next = a->next->next;
if (b->next != NULL)
b->next = b->next->next;
moveNode(a->next, b->next);
}
// function to split linked list
void alternateSplitLinkedList(Node* head, Node** aRef,
Node** bRef)
{
Node* curr = head;
*aRef = curr;
*bRef = curr->next;
moveNode(*aRef, *bRef);
}
void display(Node* head)
{
Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
}
762
Chapter 132. Recursive approach for alternating split of Linked List
// Driver code
int main()
{
Node* head = NULL;
Node *a = NULL, *b = NULL;
push(&head, 7);
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
alternateSplitLinkedList(head, &a, &b);
printf("a : ");
display(a);
printf("\nb : ");
display(b);
return 0;
}
Output:
a : 1 3 5 7
b : 2 4 6
Source
https://www.geeksforgeeks.org/recursive-approach-alternating-split-linked-list/
763
Chapter 133
We recursively reduce value of k. When k reaches 1, we delete current node and return next
of current node as new node. When function returns, we link the returned node as next of
previous node.
764
Chapter 133. Recursive function to delete k-th node from linked list
765
Chapter 133. Recursive function to delete k-th node from linked list
12->15->10->11->5->6->2->3 */
push(&head,3);
push(&head,2);
push(&head,6);
push(&head,5);
push(&head,11);
push(&head,10);
push(&head,15);
push(&head,12);
int k = 3;
head = deleteNode(head, k);
printf("\nModified Linked List: ");
printList(head);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/recursive-function-delete-k-th-node-linked-list/
766
Chapter 134
767
Chapter 134. Recursive insertion and traversal linked list
Complete Program:
Below is complete program to demonstrate working of insert and traverse a linked list.
768
Chapter 134. Recursive insertion and traversal linked list
Output:
6 8 10 12 14
Source
https://www.geeksforgeeks.org/recursive-insertion-and-traversal-linked-list/
769
Chapter 135
Input : n = 11
Output : Yes
Input : n = 15
Output : No
770
Chapter 135. Recursive program for prime number
if (n % i == 0)
return false;
if (i * i > n)
return true;
// Check for next divisor
return isPrime(n, i + 1);
}
// Driver Program
int main()
{
int n = 15;
if (isPrime(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
771
Chapter 135. Recursive program for prime number
Python3
C#
772
Chapter 135. Recursive program for prime number
PHP
<?php
// PHP Program to find whether a Number
// is Prime or Not using Recursion
// Returns true if n is prime, else
// return false.
773
Chapter 135. Recursive program for prime number
Output:
No
Source
https://www.geeksforgeeks.org/recursive-program-prime-number/
774
Chapter 136
Method 1 : The idea is to fix a prefix, general all subsets beginning with current prefix.
After all subsets with a prefix are generated, replace last character with one of the remaining
characters.
775
Chapter 136. Recursive program to generate power set
// base case
if (index == n)
return;
// First print current subset
cout << curr << "\n";
// Try appending remaining characters
// to current subset
for (int i = index + 1; i < n; i++) {
curr += str[i];
powerSet(str, i, curr);
// Once all subsets beginning with
// initial "curr" are printed, remove
// last character to consider a different
// prefix of subsets.
curr.erase(curr.size() - 1);
}
return;
}
// Driver code
int main()
{
string str = "abc";
powerSet(str);
return 0;
}
Output:
a
ab
abc
ac
b
bc
c
Method 2 : The idea is to consider two cases for every character. (i) Consider current
character as part of current subset (ii) Do not consider current character as part of current
subset.
776
Chapter 136. Recursive program to generate power set
Output:
abc
ab
ac
a
bc
b
c
777
Chapter 136. Recursive program to generate power set
Source
https://www.geeksforgeeks.org/recursive-program-to-generate-power-set/
778
Chapter 137
Input : n = 3
Output : gcd(int, gcd(int, int))
Input : n = 5
Output : gcd(int, gcd(int, gcd(int, gcd(int, int))))
Approach: The idea is to use recursion to print the single line command. Now, to write
a recursive function, say recursiveFun(n), the required string is composed of gcd(int, +
recursiveFun(n – 1) + ). This means that the recursiveFun(n) should return a string that
contains a call to itself and in order to evaluate that value, the recursive function will begin
again for n – 1. This will, in turn, return another string with a call to n – 1 and so until n
== 1 and the recursive function instead returns the string “int”.
Below is implementation of the above approach:
C++
779
Chapter 137. Recursive program to print formula for GCD of n integers
Java
780
Chapter 137. Recursive program to print formula for GCD of n integers
{
int n = 5;
System.out.println(recursiveFun(n));
}
}
// This code is contributed
// by Smitha
C#
Output:
781
Chapter 137. Recursive program to print formula for GCD of n integers
Source
https://www.geeksforgeeks.org/single-line-command-gcd-n-integers/
782
Chapter 138
Recursive solution to count substrings with same first and last characters - GeeksforGeeks
We are given a string S, we need to find count of all contiguous substrings starting and
ending with same character.
Examples :
Input : S = "abcab"
Output : 7
There are 15 substrings of "abcab"
a, ab, abc, abca, abcab, b, bc, bca
bcab, c, ca, cab, a, ab, b
Out of the above substrings, there
are 7 substrings : a, abca, b, bcab,
c, a and b.
Input : S = "aba"
Output : 4
The substrings are a, b, a and aba
C++
783
Chapter 138. Recursive solution to count substrings with same first and last characters
Java
784
Chapter 138. Recursive solution to count substrings with same first and last characters
if (n == 1)
return 1;
if (n <= 0)
return 0;
int res = countSubstrs(str, i + 1, j, n - 1) +
countSubstrs(str, i, j - 1, n - 1) -
countSubstrs(str, i + 1, j - 1, n - 2);
if (str.charAt(i) == str.charAt(j))
res++;
return res;
}
// Driver code
public static void main (String[] args)
{
String str = "abcab";
int n = str.length();
System.out.print(countSubstrs(str, 0, n - 1, n));
}
}
// This code is contributed by Anant Agarwal.
Python 3
785
Chapter 138. Recursive solution to count substrings with same first and last characters
return res
# driver code
str = "abcab"
n = len(str)
print(countSubstrs(str, 0, n - 1, n))
# This code is contributed by Smitha
C#
786
Chapter 138. Recursive solution to count substrings with same first and last characters
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to count
// substrings with same
// first and last characters
//Function to count subtrings
// with same first and
// last characters
function countSubstrs($str, $i,
$j, $n)
{
// base cases
if ($n == 1)
return 1;
if ($n <= 0)
return 0;
$res = countSubstrs($str, $i + 1, $j, $n - 1) +
countSubstrs($str, $i, $j - 1, $n - 1) -
countSubstrs($str, $i + 1, $j - 1, $n - 2);
if ($str[$i] == $str[$j])
$res++;
return $res;
}
// Driver Code
$str = "abcab";
$n = strlen($str);
echo(countSubstrs($str, 0, $n - 1, $n));
// This code is contributed by Ajit.
?>
Output:
787
Chapter 138. Recursive solution to count substrings with same first and last characters
The time complexity of above solution is exponential. In Worst case, we may end up doing
O(3n ) operations.
Source
https://www.geeksforgeeks.org/recursive-solution-count-substrings-first-last-characters/
788
Chapter 139
Input : NULL
Output : NULL
Input : 1->NULL
Output : 1->NULL
We have discussed an iterative and two recursive approaches in previous post on reverse a
linked list.
In this approach of reversing a linked list by passing a single pointer what we are trying to
do is that we are making the previous node of the current node as his next node to reverse
the linked list.
789
Chapter 139. Recursively Reversing a linked list (A simple implementation)
1. We return the pointer of next node to his previous(current) node and then make the
previous node as the next node of returned node and then returning the current node.
2. We first traverse till the last node and making the last node as the head node of
reversed linked list and then applying the above procedure in the recursive manner.
790
Chapter 139. Recursively Reversing a linked list (A simple implementation)
Output:
Source
https://www.geeksforgeeks.org/recursively-reversing-a-linked-list-a-simple-implementation/
791
Chapter 140
Input: azxxzy
Output: ay
First "azxxzy" is reduced to "azzy".
The string "azzy" contains duplicates,
so it is further reduced to "ay".
Input: geeksforgeeg
Output: gksfor
First "geeksforgeeg" is reduced to
"gksforgg". The string "gksforgg"
contains duplicates, so it is further
reduced to "gksfor".
Input: caaabbbaacdddd
Output: Empty String
Input: acaaabbbacdddd
Output: acac
A simple approach would be to run the input string through multiple passes. In every pass
remove all adjacent duplicates from left to right. Stop running passes when there are no
duplicates. The worst time complexity of this method would be O(n^2).
792
Chapter 140. Recursively remove all adjacent duplicates
// from a string
#include <iostream>
#include <string.h>
using namespace std;
// This function recursively removes duplicates
// and returns modified string
char* removeDup(char * str, int n)
{
int len = strlen(str);
int k = 0; // To store index of result
// Start from second character and add
// unique ones
for (int i=1; i< len; i++)
{
// If different, increment k and add
// previous character
if (str[i-1] != str[i])
str[k++] = str[i-1];
else
// Keep skipping (removing) characters
// while they are same.
while (str[i-1] == str[i])
i++;
}
// Add last character and terminator
str[k++] = str[i-1];
str[k] = '\0';
// Recur for string if there were some removed
// character
if (k != n)
removeDup(str, k);// Shlemial Painter's Algorithm
// If all characters were unique
else return str;
}
int main()
{
char str1[] = "geeksforgeeg";
cout << removeDup(str1, strlen(str1)) << endl;
char str2[] = "azxxxzy";
cout << removeDup(str2, strlen(str2)) << endl;
793
Chapter 140. Recursively remove all adjacent duplicates
char str3[] = "caaabbbaac";
cout << removeDup(str3, strlen(str3)) << endl;
char str4[] = "gghhg";
cout << removeDup(str4, strlen(str4)) << endl;
char str5[] = "aaaacddddcappp";
cout << removeDup(str5, strlen(str5)) << endl;
char str6[] = "aaaaaaaaaa";
cout << removeDup(str6, strlen(str6)) << endl;
char str7[] = "qpaaaaadaaaaadprq";
cout << removeDup(str7, strlen(str7)) << endl;
char str8[] = "acaaabbbacdddd";
cout << removeDup(str8, strlen(str8)) << endl;
char str9[] = "acbbcddc";
cout << removeDup(str9, strlen(str9)) << endl;
}
// This code is contributed by Aditya Goel.
Output:
gksfor
ay
g
a
qrq
acac
a
794
Chapter 140. Recursively remove all adjacent duplicates
……..c) Else, append the first character of the original string at the beginning of rem_str.
4) Return rem_str.
Following are C++ and Python implementations of the above algorithm.
C++
795
Chapter 140. Recursively remove all adjacent duplicates
// If the two first characters of str and rem_str don't match,
// append first character of str before the first character of
// rem_str.
rem_str--;
rem_str[0] = str[0];
return rem_str;
}
char *remove(char *str)
{
char last_removed = '\0';
return removeUtil(str, &last_removed);
}
// Driver program to test above functions
int main()
{
char str1[] = "geeksforgeeg";
cout << remove(str1) << endl;
char str2[] = "azxxxzy";
cout << remove(str2) << endl;
char str3[] = "caaabbbaac";
cout << remove(str3) << endl;
char str4[] = "gghhg";
cout << remove(str4) << endl;
char str5[] = "aaaacddddcappp";
cout << remove(str5) << endl;
char str6[] = "aaaaaaaaaa";
cout << remove(str6) << endl;
char str7[] = "qpaaaaadaaaaadprq";
cout << remove(str7) << endl;
char str8[] = "acaaabbbacdddd";
cout << remove(str8) << endl;
char str9[] = "acbbcddc";
cout << remove(str9) << endl;
return 0;
}
796
Chapter 140. Recursively remove all adjacent duplicates
Python
797
Chapter 140. Recursively remove all adjacent duplicates
# Utility functions
def toList(string):
x = []
for i in string:
x.append(i)
return x
def toString(x):
return ''.join(x)
# Driver program
string1 = "geeksforgeeg"
print remove(string1)
string2 = "azxxxzy"
print remove(string2)
string3 = "caaabbbaac"
print remove(string3)
string4 = "gghhg"
print remove(string4)
string5 = "aaaacddddcappp"
print remove(string5)
string6 = "aaaaaaaaaa"
print remove(string6)
string7 = "qpaaaaadaaaaadprq"
print remove(string7)
string8 = "acaaabbbacdddd"
print remove(string8)
string9 = "acbbcddc"
print remove(string9)
# This code is contributed by BHAVYA JAIN
Output:
gksfor
ay
g
a
798
Chapter 140. Recursively remove all adjacent duplicates
qrq
acac
a
Time Complexity: The time complexity of the solution can be written as T(n) = T(n-k)
+ O(k) where n is length of the input string and k is the number of first characters which
are same. Solution of the recurrence is O(n)
Thanks to Prachi Bodke for suggesting this problem and initial solution. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above
Source
https://www.geeksforgeeks.org/recursively-remove-adjacent-duplicates-given-string/
799
Chapter 141
Reduce a number to 1 by
performing given operations
• Operation 1: If the number is even then you can divide the number by 2.
• Operation 2: If the number is odd then you are allowed to perform either (n+1) or
(n-1).
You need to print the minimum number of steps required to reduce the number N to 1 by
performing the above operations.
Examples:
Input : n = 15
Output : 5
15 is odd 15+1=16
16 is even 16/2=8
8 is even 8/2=4
4 is even 4/2=2
2 is even 2/2=1
Input : n = 7
Output : 4
7->6
6->3
3->2
2->1
800
Chapter 141. Reduce a number to 1 by performing given operations
• If the number is even, then we are allowed to only divide the number by 2.
• But, when the number is Odd, we can either increment or decrement it by 1. So, we
will use recursion for both n-1 and n+1 and return the one with the minimum number
of operations.
C++
Java
801
Chapter 141. Reduce a number to 1 by performing given operations
{
if (n == 1)
return 0;
else if (n % 2 == 0)
return 1 + countways(n / 2);
else
return 1 + Math.min(countways(n - 1),
countways(n + 1));
}
// Driver code
public static void main(String args[])
{
int n = 15;
System.out.println(countways(n));
}
}
// This code is contributed by ankita_saini
Output:
Improved By : ankita_saini
Source
https://www.geeksforgeeks.org/reduce-a-number-to-1-by-performing-given-operations/
802
Chapter 142
803
Chapter 142. Remove duplicates from a sorted linked list using recursion
804
Chapter 142. Remove duplicates from a sorted linked list using recursion
push(&head, 13);
push(&head, 13);
push(&head, 11);
push(&head, 11);
push(&head, 11);
printf("\n Linked list before duplicate removal ");
printList(head);
/* Remove duplicates from linked list */
struct Node* h = removeDuplicates(head);
printf("\n Linked list after duplicate removal ");
printList(h);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/remove-duplicates-sorted-linked-list-using-recursion/
805
Chapter 143
We have discussed
Iterative solution to reverse a Doubly Linked List
Algorithm
1) If list is empty, return
2) Reverse head by swapping head->prev and head->next
3) If prev = NULL it means that list is fully reversed. Else reverse(head->prev)
806
Chapter 143. Reverse a Doubly linked list using recursion
807
Chapter 143. Reverse a Doubly linked list using recursion
Output:
Original list: 10 8 4 2
Reversed list: 2 4 8 10
808
Chapter 143. Reverse a Doubly linked list using recursion
Source
https://www.geeksforgeeks.org/reverse-doubly-linked-list-using-recursion/
809
Chapter 144
1 <-- top
2
3
4
810
Chapter 144. Reverse a stack using recursion
So we need a function that inserts at the bottom of a stack using the above given basic stack
function.
void insertAtBottom((): First pops all stack items and stores the popped item in function
call stack using recursion. And when stack becomes empty, pushes new item and all items
stored in call stack.
void reverse(): This function mainly uses insertAtBottom() to pop all items one by one
and insert the popped items at the bottom.
C
// C program to reverse a
// stack using recursion
#include<stdio.h>
#include<stdlib.h>
#define bool int
// structure of a stack node
struct sNode
{
char data;
struct sNode *next;
};
// Function Prototypes
void push(struct sNode** top_ref,
int new_data);
int pop(struct sNode** top_ref);
bool isEmpty(struct sNode* top);
void print(struct sNode* top);
// Below is a recursive function
// that inserts an element
// at the bottom of a stack.
void insertAtBottom(struct sNode** top_ref,
int item)
{
if (isEmpty(*top_ref))
push(top_ref, item);
else
{
811
Chapter 144. Reverse a stack using recursion
812
Chapter 144. Reverse a stack using recursion
813
Chapter 144. Reverse a stack using recursion
C++
814
Chapter 144. Reverse a stack using recursion
if(st.size() == 0)
st.push(x);
else
{
// All items are held in Function Call
// Stack until we reach end of the stack
// When the stack becomes empty, the
// st.size() becomes 0, the above if
// part is executed and the item is
// inserted at the bottom
char a = st.top();
st.pop();
insert_at_bottom(x);
// push allthe items held in
// Function Call Stack
// once the item is inserted
// at the bottom
st.push(a);
}
}
// Below is the function that
// reverses the given stack using
// insert_at_bottom()
char reverse()
{
if(st.size()>0)
{
// Hold all items in Function
// Call Stack until we
// reach end of the stack
char x = st.top();
st.pop();
reverse();
// Insert all the items held
// in Function Call Stack
// one by one from the bottom
// to top. Every item is
// inserted at the bottom
insert_at_bottom(x);
}
815
Chapter 144. Reverse a stack using recursion
}
// Driver Code
int main()
{
// push elements into
// the stack
st.push('1');
st.push('2');
st.push('3');
st.push('4');
cout<<"Original Stack"<<endl;
// print the elements
// of original stack
cout<<"1"<<" "<<"2"<<" "
<<"3"<<" "<<"4"
<<endl;
// function to reverse
// the stack
reverse();
cout<<"Reversed Stack"
<<endl;
// storing values of reversed
// stack into a string for display
while(!st.empty())
{
char p=st.top();
st.pop();
ns+=p;
}
//display of reversed stack
cout<<ns[3]<<" "<<ns[2]<<" "
<<ns[1]<<" "<<ns[0]<<endl;
return 0;
}
// This code is contributed by Gautam Singh
Java
816
Chapter 144. Reverse a stack using recursion
import java.util.Stack;
class Test {
// using Stack class for
// stack implementation
static Stack<Character> st = new Stack<>();
// Below is a recursive function
// that inserts an element
// at the bottom of a stack.
static void insert_at_bottom(char x)
{
if(st.isEmpty())
st.push(x);
else
{
// All items are held in Function
// Call Stack until we reach end
// of the stack. When the stack becomes
// empty, the st.size() becomes 0, the
// above if part is executed and
// the item is inserted at the bottom
char a = st.peek();
st.pop();
insert_at_bottom(x);
// push allthe items held
// in Function Call Stack
// once the item is inserted
// at the bottom
st.push(a);
}
}
// Below is the function that
// reverses the given stack using
// insert_at_bottom()
static void reverse()
{
if(st.size() > 0)
{
// Hold all items in Function
// Call Stack until we
817
Chapter 144. Reverse a stack using recursion
Python3
818
Chapter 144. Reverse a stack using recursion
if isEmpty(stack):
push(stack, item)
else:
temp = pop(stack)
insertAtBottom(stack, item)
push(stack, temp)
# Below is the function that
# reverses the given stack
# using insertAtBottom()
def reverse(stack):
if not isEmpty(stack):
temp = pop(stack)
reverse(stack)
insertAtBottom(stack, temp)
# Below is a complete running
# program for testing above
# functions.
# Function to create a stack.
# It initializes size of stack
# as 0
def createStack():
stack = []
return stack
# Function to check if
# the stack is empty
def isEmpty( stack ):
return len(stack) == 0
# Function to push an
# item to stack
def push( stack, item ):
stack.append( item )
# Function to pop an
# item from stack
def pop( stack ):
# If stack is empty
# then error
if(isEmpty( stack )):
print("Stack Underflow ")
exit(1)
return stack.pop()
819
Chapter 144. Reverse a stack using recursion
# Function to print the stack
def prints(stack):
for i in range(len(stack)-1, -1, -1):
print(stack[i], end = ' ')
print()
# Driver Code
stack = createStack()
push( stack, str(4) )
push( stack, str(3) )
push( stack, str(2) )
push( stack, str(1) )
print("Original Stack ")
prints(stack)
reverse(stack)
print("Reversed Stack ")
prints(stack)
# This code is contributed by Sunny Karira
Output:
Original Stack
1 2 3 4
Reversed Stack
4 3 2 1
Improved By : SBanzal
Source
https://www.geeksforgeeks.org/reverse-a-stack-using-recursion/
820
Chapter 145
Input : Q = [8, 7, 2, 5, 1]
Output : Q = [1, 5, 2, 7, 8]
Recursive Algorithm :
1) Pop element from the queue if the queue has elements otherwise return empty queue.
2) Call reverseQueue function for the remaining queue.
3) Push the popped element in the resultant reversed queue.
821
Chapter 145. Reversing a queue using recursion
Pseudo Code :
queue reverseFunction(queue)
{
if (queue is empty)
return queue;
else {
data = queue.front()
queue.pop()
queue = reverseFunction(queue);
q.push(data);
return queue;
}
}
C++
822
Chapter 145. Reversing a queue using recursion
}
// Recursive function to reverse the queue
void reverseQueue(queue<long long int>& q)
{
// Base case
if (q.empty())
return;
// Dequeue current item (from front)
long long int data = q.front();
q.pop();
// Reverse remaining queue
reverseQueue(q);
// Enqueue current item (to rear)
q.push(data);
}
// Driver code
int main()
{
queue<long long int> Queue;
Queue.push(56);
Queue.push(27);
Queue.push(30);
Queue.push(45);
Queue.push(85);
Queue.push(92);
Queue.push(58);
Queue.push(80);
Queue.push(90);
Queue.push(100);
reverseQueue(Queue);
printQueue(Queue);
}
Java
823
Chapter 145. Reversing a queue using recursion
824
Chapter 145. Reversing a queue using recursion
}
}
Python3
# Queue Class
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def add(self, item):
self.items.append(item)
def pop(self):
return self.items.pop(0)
def front(self):
return self.items[0]
def printQueue(self):
for i in self.items:
print(i, end =" ")
print("")
# Recursive Function to reverse the queue
def reverseQueue(q):
# Base case
if (q.isEmpty()):
return
# Dequeue current item (from front)
data = q.front();
q.pop();
# Reverse remaining queue
reverseQueue(q)
# Enqueue current item (to rear)
q.add(data)
# Driver Code
825
Chapter 145. Reversing a queue using recursion
q = Queue()
q.add(56)
q.add(27)
q.add(30)
q.add(45)
q.add(85)
q.add(92)
q.add(58)
q.add(80)
q.add(90)
q.add(100)
reverseQueue(q)
q.printQueue()
C#
826
Chapter 145. Reversing a queue using recursion
// Enqueue current
// item (to rear)
q.Enqueue(data);
}
// Driver code
static void Main()
{
Queue<long> queue = new Queue<long>();
queue.Enqueue(56);
queue.Enqueue(27);
queue.Enqueue(30);
queue.Enqueue(45);
queue.Enqueue(85);
queue.Enqueue(92);
queue.Enqueue(58);
queue.Enqueue(80);
queue.Enqueue(90);
queue.Enqueue(100);
reverseQueue(ref queue);
printQueue(queue);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output:
100 90 80 58 92 85 45 30 27 56
Source
https://www.geeksforgeeks.org/reversing-queue-using-recursion/
827
Chapter 146
Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ......, an, bn} without using extra space
- GeeksforGeeks
Given an array of 2n elements in the following format { a1, a2, a3, a4, ….., an, b1, b2, b3,
b4, …., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, ……, an, bn } without
using extra space.
Examples:
Input : arr[] = { 1, 2, 9, 15 }
Output : 1 9 2 15
Input : arr[] = { 1, 2, 3, 4, 5, 6 }
Output : 1 4 2 5 3 6
828
Chapter 146. Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ……, an, bn} without
using extra space
#include <bits/stdc++.h>
using namespace std;
// function to shuffle an array of size 2n
void shuffleArray(int a[], int n)
{
// Rotate the element to the left
for (int i = 0, q = 1, k = n; i < n; i++, k++, q++)
for (int j = k; j > i + q; j--)
swap(a[j-1], a[j]);
}
// Driven Program
int main()
{
int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 };
int n = sizeof(a) / sizeof(a[0]);
shuffleArray(a, n/2);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
}
Java
829
Chapter 146. Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ……, an, bn} without
using extra space
Python3
Output:
1 2 3 4 5 6 7 8
830
Chapter 146. Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ……, an, bn} without
using extra space
arr1[] and arr2[]) and swap second half element of arr1[] with first half element of arr2[].
Recursively do this for arr1 and arr2.
Let us explain with the help of an example.
1. Let the array be a1, a2, a3, a4, b1, b2, b3, b4
2. Split the array into two halves: a1, a2, a3, a4 : b1, b2, b3, b4
3. Exchange element around the center: exchange a3, a4 with b1, b2 correspondingly.
you get: a1, a2, b1, b2, a3, a4, b3, b4
4. Recursively spilt a1, a2, b1, b2 into a1, a2 : b1, b2
then split a3, a4, b3, b4 into a3, a4 : b3, b4.
5. Exchange elements around the center for each subarray we get:
a1, b1, a2, b2 and a3, b3, a4, b4.
Note: This solution only handles the case when n = 2i where i = 0, 1, 2, …etc.
Below is implementation of this approach:
C++
831
Chapter 146. Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ……, an, bn} without
using extra space
// Driven Program
int main()
{
int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 };
int n = sizeof(a) / sizeof(a[0]);
shufleArray(a, 0, n - 1);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
}
Java
832
Chapter 146. Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ……, an, bn} without
using extra space
Python3
833
Chapter 146. Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ……, an, bn} without
using extra space
# Driver Code
a = [1, 3, 5, 7, 2, 4, 6, 8]
n = len(a)
shufleArray(a, 0, n - 1)
for i in range(0, n):
print(a[i], end = " ")
# This code is contributed by Smitha Dinesh Semwal
Output:
1 2 3 4 5 6 7 8
Source
https://www.geeksforgeeks.org/shuffle-2n-integers-format-a1-b1-a2-b2-a3-b3-bn-without-using-extra-space/
834
Chapter 147
Examples:
Input: N = 20
Output: 21
Explanation: 21 is the smallest element greater than 20.
835
Chapter 147. Smallest number in BST which is greater than or equal to N
Input: N = 18
Output: 19
Explanation: 19 is the smallest element greater than 18.
Approach:
The idea is to follow the recursive approach for solving the problem i.e. start searching for
the element from the root.
• If there is a leaf node having a value less than N, then element doesn’t exist and return
-1.
• Otherwise, if node’s value is greater than or equal to N and left child is NULL or less
than N then return the node value.
• Else if node’s value is less than N, then search for the element in the right subtree.
• Else search for the element in the left subtree by calling the function recursively ac-
cording to the left or right value.
836
Chapter 147. Smallest number in BST which is greater than or equal to N
837
Chapter 147. Smallest number in BST which is greater than or equal to N
Output:
19
Source
https://www.geeksforgeeks.org/smallest-number-in-bst-which-is-greater-than-or-equal-to-n/
838
Chapter 148
Input :
+++++++++-
-++++++++-
-------++-
-++++++++-
-++++++++-
-++++-----
------+++-
-++++++++-
+---------
++++++++++
Output :
+++++++++C
P++++++++H
HISTORY++E
Y++++++++M
S++++++++I
I++++MATHS
CIVICS+++T
S++++++++R
+GEOGRAPHY
839
Chapter 148. Solve the Crossword Puzzle
++++++++++
The approach behind this is to recursively check for each word in the vertical position and
in the horizontal position. Then fill the word in the matrix that can be the best fit in the
corresponding position of the grid, then update the crossword grid by filling the gap with
that word.
840
Chapter 148. Solve the Crossword Puzzle
return matrix;
}
// this function checks for the current word
// if it can be placed vertically or not
// x -> it represent index of row
// y -> it represent index of column
// currentWord -> it represent the
// current word in word array
vector<string> checkVertical(int x, int y,
vector<string> matrix,
string currentWord)
{
int n = currentWord.length();
for (int i = 0; i < n; i++) {
if (matrix[x + i][y] == '#' ||
matrix[x + i][y] == currentWord[i]) {
matrix[x + i][y] = currentWord[i];
}
else {
// this shows that word
// cannot be placed vertically
matrix[0][0] = '@';
return matrix;
}
}
return matrix;
}
// this function recursively checks for every
// word that can align vertically in one loop
// and in another loop it checks for those words
// that can align horizontally words -> it
// contains all the words to fill in a crossword
// puzzle matrix -> it contain the current
// state of crossword index -> it represent
// the index of current word n -> it represent
// the length of row or column of the square matrix
void solvePuzzle(vector<string>& words,
vector<string> matrix,
int index, int n)
{
if (index < words.size()) {
string currentWord = words[index];
int maxLen = n - currentWord.length();
841
Chapter 148. Solve the Crossword Puzzle
// loop to check the words that can align vertically.
for (int i = 0; i < n; i++) {
for (int j = 0; j <= maxLen; j++) {
vector<string> temp = checkVertical(j, i,
matrix, currentWord);
if (temp[0][0] != '@') {
solvePuzzle(words, temp, index + 1, n);
}
}
}
// loop to check the words that can align horizontally.
for (int i = 0; i < n; i++) {
for (int j = 0; j <= maxLen; j++) {
vector<string> temp = checkHorizontal(i, j,
matrix, currentWord);
if (temp[0][0] != '@') {
solvePuzzle(words, temp, index + 1, n);
}
}
}
}
else {
// calling of print function to
// print the crossword puzzle
cout << (ways + 1) << " way to solve the puzzle "
<< endl;
printMatrix(matrix, n);
cout << endl;
// increase the ways
ways++;
return;
}
}
// Driver Code
int main()
{
// length of grid
int n1 = 10;
// matrix to hold the grid of puzzle
vector<string> matrix;
842
Chapter 148. Solve the Crossword Puzzle
Output:
843
Chapter 148. Solve the Crossword Puzzle
*D********
***MIZORAM
Source
https://www.geeksforgeeks.org/solve-crossword-puzzle/
844
Chapter 149
Input : [3, 5, 1, 4, 2, 8]
Output : [1, 2, 3, 4, 5, 8]
845
Chapter 149. Sort a stack using a temporary stack
846
Chapter 149. Sort a stack using a temporary stack
C++
// C++ program to sort a stack using an
// auxiliary stack.
#include <bits/stdc++.h>
using namespace std;
// This function return the sorted stack
stack<int> sortStack(stack<int> &input)
{
stack<int> tmpStack;
while (!input.empty())
{
// pop out the first element
int tmp = input.top();
input.pop();
// while temporary stack is not empty and top
// of stack is greater than temp
while (!tmpStack.empty() && tmpStack.top() > tmp)
{
// pop from temporary stack and push
// it to the input stack
input.push(tmpStack.top());
tmpStack.pop();
}
// push temp in tempory of stack
tmpStack.push(tmp);
}
return tmpStack;
}
// main function
847
Chapter 149. Sort a stack using a temporary stack
int main()
{
stack<int> input;
input.push(34);
input.push(3);
input.push(31);
input.push(98);
input.push(92);
input.push(23);
// This is the temporary stack
stack<int> tmpStack = sortStack(input);
cout << "Sorted numbers are:\n";
while (!tmpStack.empty())
{
cout << tmpStack.top()<< " ";
tmpStack.pop();
}
}
Java
848
Chapter 149. Sort a stack using a temporary stack
// push temp in tempory of stack
tmpStack.push(tmp);
}
return tmpStack;
}
// Driver Code
public static void main(String args[])
{
Stack<Integer> input = new Stack<Integer>();
input.add(34);
input.add(3);
input.add(31);
input.add(98);
input.add(92);
input.add(23);
// This is the temporary stack
Stack<Integer> tmpStack=sortstack(input);
System.out.println("Sorted numbers are:");
while (!tmpStack.empty())
{
System.out.print(tmpStack.pop()+" ");
}
}
}
// This code is contributed by Danish Kaleem
Python3
849
Chapter 149. Sort a stack using a temporary stack
850
Chapter 149. Sort a stack using a temporary stack
return stack.pop()
# Function to print the stack
def prints(stack):
for i in range(len(stack)-1, -1, -1):
print(stack[i], end = ' ')
print()
# Driver Code
stack = createStack()
push( stack, str(34) )
push( stack, str(3) )
push( stack, str(31) )
push( stack, str(98) )
push( stack, str(92) )
push( stack, str(23) )
print("Sorted numbers are: ")
sortedst = sortStack ( stack )
prints(sortedst)
# This code is contributed by
# Prasad Kshirsagar
Output:
Microsoft
Improved By : programmer2k17, Prasad_Kshirsagar
Source
https://www.geeksforgeeks.org/sort-stack-using-temporary-stack/
851
Chapter 150
Example:
Input: -3
Algorithm
sortStack(stack S)
852
Chapter 150. Sort a stack using recursion
sortedInsert(Stack S, element)
if stack is empty OR element > top element
push(S, elem)
else
temp = pop(S)
sortedInsert(S, element)
push(S, temp)
Illustration:
Now stack is empty and ’insert_in_sorted_order()’ function is called and it inserts 30 (from
stack frame #5) at the bottom of the stack. Now stack looks like below:
30
Now next element i.e. -5 (from stack frame #4) is picked. Since -5 < 30, -5 is inserted at the b
30 -5
Next 18 (from stack frame #3) is picked. Since 18 < 30, 18 is inserted below 30. Now stack
becomes:
30 18
-5
853
Chapter 150. Sort a stack using recursion
Next 14 (from stack frame #2) is picked. Since 14 < 30 and 14 < 18, it is inserted below
18. Now stack becomes:
30 14
-5
Now -3 (from stack frame #1) is picked, as -3 < 30 and -3 < 18 and -3 < 14, it is inserted
below 14. Now stack becomes:
30 -3
-5
Implementation:
Below is C and Java implementation of above algorithm.
854
Chapter 150. Sort a stack using recursion
855
Chapter 150. Sort a stack using recursion
sortedInsert(s, x);
// Put back the top item removed earlier
push(s, temp);
}
// Function to sort stack
void sortStack(struct stack **s)
{
// If stack is not empty
if (!isEmpty(*s))
{
// Remove the top item
int x = pop(s);
// Sort remaining stack
sortStack(s);
// Push the top item back in sorted stack
sortedInsert(s, x);
}
}
// Utility function to print contents of stack
void printStack(struct stack *s)
{
while (s)
{
printf("%d ", s->data);
s = s->next;
}
printf("\n");
}
// Driver Program
int main(void)
{
struct stack *top;
initStack(&top);
push(&top, 30);
push(&top, -5);
push(&top, 18);
push(&top, 14);
push(&top, -3);
printf("Stack elements before sorting:\n");
printStack(top);
856
Chapter 150. Sort a stack using recursion
sortStack(&top);
printf("\n\n");
printf("Stack elements after sorting:\n");
printStack(top);
return 0;
}
Java
857
Chapter 150. Sort a stack using recursion
// Sort remaining stack
sortStack(s);
// Push the top item back in sorted stack
sortedInsert(s, x);
}
}
// Utility Method to print contents of stack
static void printStack(Stack<Integer> s)
{
ListIterator<Integer> lt = s.listIterator();
// forwarding
while(lt.hasNext())
lt.next();
// printing from top to bottom
while(lt.hasPrevious())
System.out.print(lt.previous()+" ");
}
// Driver method
public static void main(String[] args)
{
Stack<Integer> s = new Stack<>();
s.push(30);
s.push(-5);
s.push(18);
s.push(14);
s.push(-3);
System.out.println("Stack elements before sorting: ");
printStack(s);
sortStack(s);
System.out.println(" \n\nStack elements after sorting:");
printStack(s);
}
}
Output:
858
Chapter 150. Sort a stack using recursion
-3 14 18 -5 30
Source
https://www.geeksforgeeks.org/sort-a-stack-using-recursion/
859
Chapter 151
Input : s = “235813”
Output : true
2 + 3 = 5, 3 + 5 = 8, 5 + 8 = 13
Input : s = “199100199”
Output : true
1 + 99 = 100, 99 + 100 = 199
Input : s = “12345678”
Output : false
This problem can be solved recursively, note that number of digits in added value can’t be
smaller than digits in any of its operand that is why we will loop till (length of string)/2 for
first number and (length of string – first number’s length)/ 2 for second number to ignore
invalid result.
Next thing to note is, first and second number can’t start with 0, which is checked in below
code by isValid method. When we call recursively, we check that sum of first and second
number is exactly equal to rest of string. If yes then direct return the result else check that
sum string is prefix of rest of string or not, If yes then call recursively with second number,
sum string and rest of string after removing sum string from rest of string and if sum string
is not prefix of rest of string then no solution in available.
Below is C++ implementation.
860
Chapter 151. String with additive sequence
861
Chapter 151. String with additive sequence
862
Chapter 151. String with additive sequence
Output:
2 3 5 8 13
1 99 100 199
863
Chapter 151. String with additive sequence
Source
https://www.geeksforgeeks.org/string-with-additive-sequence/
864
Chapter 152
Example :
865
Chapter 152. Sum of all elements of N-ary Tree
Approach : The approach used is similar to Level Order traversal in a binary tree. Start
by pushing the root node in the queue. And for each node, while popping it from queue,
add the value of this node in the sum variable and push the children of the popped element
in the queue. In case of a generic tree store child nodes in a vector. Thus, put all elements
of the vector in the queue.
Below is the implementation of the above idea :
866
Chapter 152. Sum of all elements of N-ary Tree
// Dequeue an item from queue and
// add it to variable "sum"
Node* p = q.front();
q.pop();
sum += p->key;
// Enqueue all children of the dequeued item
for (int i = 0; i < p->child.size(); i++)
q.push(p->child[i]);
n--;
}
}
return sum;
}
// Driver program
int main()
{
// Creating a generic tree
Node* root = newNode(20);
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(34));
(root->child).push_back(newNode(50));
(root->child).push_back(newNode(60));
(root->child).push_back(newNode(70));
(root->child[0]->child).push_back(newNode(15));
(root->child[0]->child).push_back(newNode(20));
(root->child[1]->child).push_back(newNode(30));
(root->child[2]->child).push_back(newNode(40));
(root->child[2]->child).push_back(newNode(100));
(root->child[2]->child).push_back(newNode(20));
(root->child[0]->child[1]->child).push_back(newNode(25));
(root->child[0]->child[1]->child).push_back(newNode(50));
cout << sumNodes(root) << endl;
return 0;
}
Output:
536
867
Chapter 152. Sum of all elements of N-ary Tree
Source
https://www.geeksforgeeks.org/sum-elements-n-ary-tree/
868
Chapter 153
Input : 12345
Output : 15
Input : 45632
Output :20
Step by step process for better understanding of how the algorithm works.
Let number be 12345.
Step 1-> 12345 % 10 which is equal-too 5 + ( send 12345/10 to next step )
Step 2-> 1234 % 10 which is equal-too 4 + ( send 1234/10 to next step )
Step 3-> 123 % 10 which is equal-too 3 + ( send 123/10 to next step )
Step 4-> 12 % 10 which is equal-too 2 + ( send 12/10 to next step )
Step 5-> 1 % 10 which is equal-too 1 + ( send 1/10 to next step )
Step 6-> 0 algorithm stops
following diagram will illustrate the process of recursion
869
Chapter 153. Sum of digit of a number using recursion
870
Chapter 153. Sum of digit of a number using recursion
Java
871
Chapter 153. Sum of digit of a number using recursion
}
}
// This code is contributed by Anshika Goyal.
Python3
C#
872
Chapter 153. Sum of digit of a number using recursion
PHP
<?php
// Recursive PHP program
// to find sum of digits
// of a number
// Function to check sum of
// digit using recursion
function sum_of_digit($n)
{
if ($n == 0)
return 0;
return ($n % 10 +
sum_of_digit($n / 10));
}
// Driven Code
$num = 12345;
$result = sum_of_digit($num);
echo("Sum of digits in " . $num . " is " . $result);
// This code is contributed by Ajit.
?>
Output:
Improved By : jit_t
Source
https://www.geeksforgeeks.org/sum-digit-number-using-recursion/
873
Chapter 154
Sum of elements of all partitions of number such that no element is less than K - Geeks-
forGeeks
Given an integer N, the task is to find an aggregate sum of all integer partitions of this
number such that each partition does not contain any integer less than K.
Examples:
Input: N = 6 and K = 2
Output: 24
In this case, there are 4 valid partitions.
1) {6}
2) {4, 2}
3) {3, 3}
4) {2, 2, 2}
Therefore, aggregate sum would be
6 + 4 + 2 + 3 + 3 + 2 + 2 + 2 = 24
Input: N = 10 and K = 3
Output: 50
Here, 5 valid partitions are:
1) {10}
2) {7, 3}
3) {6, 4}
4) {5, 5}
5) {3, 3, 4}
Aggregate sum in this case would be
10 + 7 + 3 + 6 + 4 + 5 + 5 + 3 + 3 + 4 = 50
874
Chapter 154. Sum of elements of all partitions of number such that no element is less
than K
Approach: This problem has a simple recursive solution. First, we need to count the
total number of valid partitions of number N such that each partition contains integers
greater than or equal to K. So we will iteratively apply our recursive solution to find valid
partitions that have the minimum integer K, K+1, K+2, …, N.
Our final answer would be N * no of valid partitions because each valid partition has a
sum equal to N.
Following are some key ideas for designing recursive function to find total number of valid
partitions.
f(N,K):
if N < K
return 0
if N < 2K
return 1
Initialize answer = 1
FOR i from K to N
answer = answer + f(N-i,i)
return answer
C++
875
Chapter 154. Sum of elements of all partitions of number such that no element is less
than K
876
Chapter 154. Sum of elements of all partitions of number such that no element is less
than K
Java
// Java implementation of
// above approach
class GFG
{
// Function that returns
// total number of valid
// partitions of integer N
static long countPartitions(int n, int k)
{
// Global declaration of 2D
// dp array which will be
// later used for memoization
long[][] dp = new long[201][201];
// initializing 2D dp array
// with -1 we will use this
// 2D array for memoization
for (int i = 0; i < n + 1; i++)
{
for (int j = 0; j < n + 1; j++)
{
dp[i][j] = -1;
}
}
// if this subproblem is already
// previously calculated, then
// directly return that answer
if (dp[n][k] >= 0)
return dp[n][k];
// if N < K, then no valid
// partition is possible
if (n < k)
return 0;
// if N is between K to 2*K
// then there is only one
// partition and that is
877
Chapter 154. Sum of elements of all partitions of number such that no element is less
than K
Output:
878
Chapter 154. Sum of elements of all partitions of number such that no element is less
than K
Source
https://www.geeksforgeeks.org/sum-of-elements-of-all-partitions-of-number-such-that-no-element-is-less-than-k/
879
Chapter 155
Input : 3
Output : 6
Explanation : 1 + 2 + 3 = 6
Input : 5
Output : 15
Explanation : 1 + 2 + 3 + 4 + 5 = 15
C++
880
Chapter 155. Sum of natural numbers using recursion
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}
// Driver code
int main()
{
int n = 5;
cout << recurSum(n);
return 0;
}
Java
Python
881
Chapter 155. Sum of natural numbers using recursion
C#
PHP
<?php
// PHP program to find the
882
Chapter 155. Sum of natural numbers using recursion
Output :
15
Improved By : jit_t
Source
https://www.geeksforgeeks.org/sum-of-natural-numbers-using-recursion/
883
Chapter 156
Input : A = {1, 2, 3, 4, 5}
Output : [48]
[20, 28]
[8, 12, 16]
[3, 5, 7, 9]
[1, 2, 3, 4, 5]
Explanation :
Here, [48]
[20, 28] -->(20 + 28 = 48)
[8, 12, 16] -->(8 + 12 = 20, 12 + 16 = 28)
[3, 5, 7, 9] -->(3 + 5 = 8, 5 + 7 = 12, 7 + 9 = 16)
[1, 2, 3, 4, 5] -->(1 + 2 = 3, 2 + 3 = 5, 3 + 4 = 7, 4 + 5 = 9)
Approach :
1. Recursion is the key. At each iteration create a new array which contains the Sum of
consecutive elements in the array passes as parameter.
2. Make a recursive call and pass the newly created array in the previous step.
3. While back tracking print the array (for printing in reverse order).
Source
https://www.geeksforgeeks.org/sum-triangle-from-array/
884
Chapter 157
Tail Recursion
Why do we care?
The tail recursive functions considered better than non tail recursive functions as tail-
recursion can be optimized by compiler. The idea used by compilers to optimize tail-
recursive functions is simple, since the recursive call is the last statement, there is nothing
left to do in the current function, so saving the current function’s stack frame is of no use
(See this for more details).
Can a non-tail recursive function be written as tail-recursive to optimize it?
Consider the following function to calculate factorial of n. It is a non-tail-recursive function.
Although it looks like a tail recursive at first look. If we take a closer look, we can see that
the value returned by fact(n-1) is used in fact(n), so the call to fact(n-1) is not the last
thing done by fact(n)
C++
#include<iostream>
885
Chapter 157. Tail Recursion
Java
class GFG {
// A NON-tail-recursive function.
// The function is not tail
// recursive because the value
// returned by fact(n-1) is used
// in fact(n) and call to fact(n-1)
// is not the last thing done by
// fact(n)
static int fact(int n)
{
if (n == 0) return 1;
return n*fact(n-1);
}
// Driver program
public static void main(String[] args)
{
System.out.println(fact(5));
}
}
// This code is contributed by Smitha.
Python 3
886
Chapter 157. Tail Recursion
# A NON-tail-recursive function.
# The function is not tail
# recursive because the value
# returned by fact(n-1) is used
# in fact(n) and call to fact(n-1)
# is not the last thing done by
# fact(n)
def fact(n):
if (n == 0):
return 1
return n * fact(n-1)
# Driver program to test
# above function
print(fact(5))
# This code is contributed by Smitha.
C#
using System;
class GFG {
// A NON-tail-recursive function.
// The function is not tail
// recursive because the value
// returned by fact(n-1) is used
// in fact(n) and call to fact(n-1)
// is not the last thing done by
// fact(n)
static int fact(int n)
{
if (n == 0)
return 1;
return n * fact(n-1);
}
// Driver program to test
// above function
public static void Main()
{
Console.Write(fact(5));
}
}
887
Chapter 157. Tail Recursion
PHP
<?php
// A NON-tail-recursive function.
// The function is not tail
// recursive because the value
// returned by fact(n-1) is used in
// fact(n) and call to fact(n-1) is
// not the last thing done by fact(n)
function fact( $n)
{
if ($n == 0) return 1;
return $n * fact($n - 1);
}
// Driver Code
echo fact(5);
// This code is contributed by Ajit
?>
Output :
120
The above function can be written as a tail recursive function. The idea is to use one more
argument and accumulate the factorial value in second argument. When n reaches 0, return
the accumulated value.
C++
#include<iostream>
using namespace std;
// A tail recursive function to calculate factorial
unsigned factTR(unsigned int n, unsigned int a)
{
if (n == 0) return a;
return factTR(n-1, n*a);
}
888
Chapter 157. Tail Recursion
Java
Python 3
889
Chapter 157. Tail Recursion
# to calculate factorial
def factTR(n, a):
if (n == 0):
return a
return factTR(n - 1, n * a)
# A wrapper over factTR
def fact(n):
return factTR(n, 1)
# Driver program to test
# above function
print(fact(5))
# This code is contributed
# by Smitha
C#
890
Chapter 157. Tail Recursion
// This code is contributed by Ajit.
PHP
<?php
// A tail recursive function
// to calculate factorial
function factTR($n, $a)
{
if ($n == 0) return $a;
return factTR($n - 1, $n * $a);
}
// A wrapper over factTR
function fact($n)
{
return factTR($n, 1);
}
// Driver program to test
// above function
echo fact(5);
// This code is contributed
// by Smitha
?>
Output :
120
Source
https://www.geeksforgeeks.org/tail-recursion/
891
Chapter 158
#include <bits/stdc++.h>
using namespace std;
// Tail recursive function
int arrSum(int* array, int size, int sum = 0)
{
892
Chapter 158. Tail recursion to calculate sum of array elements.
Output:
65
Source
https://www.geeksforgeeks.org/tail-recursion-to-calculate-sum-of-array-elements/
893
Chapter 159
Example 2
Here is one possible way of filling a 3 x 8 board. You have to find all the possible ways to
do so.
Examples :
Input : 2
Output : 3
Input : 8
Output : 153
894
Chapter 159. Tiling with Dominoes
Input : 12
Output : 2131
Defining Subproblems:
At any point while filling the board, there are three possible states that the last column
can be in:
Finding Reccurences
Note: Even though Bn and Cn are different states, they will be equal for same ‘n’. i.e
Bn = Cn
Hence, we only need to calculate one of them.
Calculating An:
895
Chapter 159. Tiling with Dominoes
Calculating Bn:
Base Cases:
C++
896
Chapter 159. Tiling with Dominoes
Java
897
Chapter 159. Tiling with Dominoes
Python 3
C#
898
Chapter 159. Tiling with Dominoes
PHP
<?php
// PHP program to find no. of ways
// to fill a 3xn board with 2x1 dominoes.
function countWays($n)
{
$A = array();
$B = array();
$A[0] = 1; $A[1] = 0;
$B[0] = 0; $B[1] = 1;
for ( $i = 2; $i <= $n; $i++)
{
$A[$i] = $A[$i - 2] + 2 *
$B[$i - 1];
$B[$i] = $A[$i - 1] +
$B[$i - 2];
}
return $A[$n];
}
// Driver Code
$n = 8;
echo countWays($n);
// This code is contributed by anuj_67.
?>
Output :
153
899
Chapter 159. Tiling with Dominoes
Source
https://www.geeksforgeeks.org/tiling-with-dominoes/
900
Chapter 160
TOH(n, x, y, z)
{
if (n >= 1)
{
// put (n-1) disk to z by using y
TOH((n-1), x, z, y)
Analysis of Recursion
901
Chapter 160. Time Complexity Analysis | Tower Of Hanoi (Recursion)
Solving it by BackSubstitution :
———–equation-2
———–equation-3
Put value of T(n-2) in equation–2 with help of equation-3
——equation-4
Put value of T(n-1) in equation-1 with help of equation-4
After Generalization :
Source
https://www.geeksforgeeks.org/time-complexity-analysis-tower-hanoi-recursion/
902
Chapter 161
903
Chapter 161. Two Dimensional Segment Tree | Sub-Matrix Sum
Step 1 : We will first create the segment tree of each strip of y- axis.We repesent the
segment tree here as an array where child node is 2n and 2n+1 where n > 0.
Segment Tree for strip y=1
904
Chapter 161. Two Dimensional Segment Tree | Sub-Matrix Sum
Step 2: In this step, we create the segment tree for the rectangular matrix where the base
node are the strips of y-axis given above.The task is to merge above segment trees.
Sum Query :
905
Chapter 161. Two Dimensional Segment Tree | Sub-Matrix Sum
906
Chapter 161. Two Dimensional Segment Tree | Sub-Matrix Sum
*/
int finalSegment(int low, int high, int pos)
{
if (high == low) {
for (int i = 1; i < 2 * size; i++)
fin_seg[pos][i] = ini_seg[low][i];
}
else {
int mid = (low + high) / 2;
finalSegment(low, mid, 2 * pos);
finalSegment(mid + 1, high, 2 * pos + 1);
for (int i = 1; i < 2 * size; i++)
fin_seg[pos][i] = fin_seg[2 * pos][i] +
fin_seg[2 * pos + 1][i];
}
}
/*
* Return sum of elements in range from index
* x1 to x2 . It uses the final_seg[][] array
* created using finalsegment() function.
* 'pos' is index of current node in
* segment tree fin_seg[][].
*/
int finalQuery(int pos, int start, int end,
int x1, int x2, int node)
{
if (x2 < start || end < x1) {
return 0;
}
if (x1 <= start && end <= x2) {
return fin_seg[node][pos];
}
int mid = (start + end) / 2;
int p1 = finalQuery(2 * pos, start, mid,
x1, x2, node);
int p2 = finalQuery(2 * pos + 1, mid + 1,
end, x1, x2, node);
return (p1 + p2);
}
/*
907
Chapter 161. Two Dimensional Segment Tree | Sub-Matrix Sum
908
Chapter 161. Two Dimensional Segment Tree | Sub-Matrix Sum
909
Chapter 161. Two Dimensional Segment Tree | Sub-Matrix Sum
Output:
Time complexity :
Processing Query : O(logn*logm)
Modification Query: O(2*n*logn*logm)
Space Complexity : O(4*m*n)
Source
https://www.geeksforgeeks.org/two-dimensional-segment-tree-sub-matrix-sum/
910
Chapter 162
Input :
7
/ \
6 5
/ \ / \
4 3 2 1
Output : 5
Input :
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
Output : 6
911
Chapter 162. Vertical width of Binary tree | Set 2
In this image, the tree contains 6 vertical lines which is the required width of tree.
Approach : In this Approach, we use the approach for printing vertical View of binary
tree. Store the horizontal distances in a set and return 1 + highest horizontal distance
– lowest horizontal distance. 1 is added to consider horizontal distance 0 as well. While
going left, do hd – 1 and for right do hd + 1. We insert all possible distances in a hash
table and finally return size of the hash table.
912
Chapter 162. Vertical width of Binary tree | Set 2
int hd)
{
if (!root)
return;
fillSet(root->left, s, hd - 1);
s.insert(hd);
fillSet(root->right, s, hd + 1);
}
int verticalWidth(Node* root)
{
unordered_set<int> s;
// Third parameter is horizontal
// distance
fillSet(root, s, 0);
return s.size();
}
int main()
{
Node* root = NULL;
// Creating the above tree
root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
root->right->left->right = new Node(8);
root->right->right->right = new Node(9);
cout << verticalWidth(root) << "\n";
return 0;
}
Output:
913
Chapter 162. Vertical width of Binary tree | Set 2
Source
https://www.geeksforgeeks.org/vertical-width-binary-tree-set-2/
914
Chapter 163
Input: 4 3 2
Output: (0, 0) –> (4, 0) –> (4, 3) –> (0, 3) –> (3, 0) –> (3, 3) –> (4, 2) –>
(0, 2)
Input: 5 2 4
Output: (0, 0) –> (5, 0) –> (5, 2) –> (0, 2) –> (2, 0) –> (2, 2) –> (4, 0)
Approach: An approach using BFS has been discussed in the previous post. In this post
an approach using memoization and recursion has been discussed. At any point, there can
be a total of six possibilities:
Approach: Using Recursion, visit all the six possible moves one by one until one of them
returns True. Since there can be repetitions of same recursive calls, hence every return value
915
Chapter 163. Water Jug Problem using Memoization
is stored using memoizationto avoid calling the recursive function again and returning the
stored value.
Below is the implementation of the above approach:
916
Chapter 163. Water Jug Problem using Memoization
Output:
Steps:
0 0
4 0
4 3
0 3
3 0
3 3
4 2
0 2
Source
https://www.geeksforgeeks.org/water-jug-problem-using-memoization/
917
Chapter 164
Input: "ilikesamsungmobile"
Output: i like sam sung mobile
i like samsung mobile
Input: "ilikeicecreamandmango"
Output: i like ice cream and man go
i like ice cream and mango
i like icecream and man go
i like icecream and mango
918
Chapter 164. Word Break Problem using Backtracking
next word. And this process is recursive because to find out whether the right portion is
separable or not, we need the same logic. So we will use recursion and backtracking to
solve this problem. To keep track of the found words we will use a stack. Whenever the
right portion of the string does not make valid words, we pop the top string from stack and
continue finding.
919
Chapter 164. Word Break Problem using Backtracking
Output:
First Test:
i love ice cream and man go
i love ice cream and mango
i love icecream and man go
i love icecream and mango
Second Test:
i love sam sung mobile
i love samsung mobile
Source
https://www.geeksforgeeks.org/word-break-problem-using-backtracking/
920
Chapter 165
C/C++
921
Chapter 165. Write a program to print all permutations of a given string
#include <string.h>
/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
/* Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf("%s\n", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
/* Driver program to test above functions */
int main()
{
char str[] = "ABC";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
Java
922
Chapter 165. Write a program to print all permutations of a given string
{
String str = "ABC";
int n = str.length();
Permutation permutation = new Permutation();
permutation.permute(str, 0, n-1);
}
/**
* permutation function
* @param str string to calculate permutation for
* @param l starting index
* @param r end index
*/
private void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}
/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}
// This code is contributed by Mihir Joshi
923
Chapter 165. Write a program to print all permutations of a given string
Python
C#
924
Chapter 165. Write a program to print all permutations of a given string
{
if (l == r)
Console.WriteLine(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str, l, i);
permute(str, l + 1, r);
str = swap(str, l, i);
}
}
}
/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
public static String swap(String a,
int i, int j)
{
char temp;
char[] charArray = a.ToCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
string s = new string(charArray);
return s;
}
// Driver Code
public static void Main()
{
String str = "ABC";
int n = str.Length;
permute(str, 0, n-1);
}
}
// This code is contributed by mits
PHP
<?php
// PHP program to print all
925
Chapter 165. Write a program to print all permutations of a given string
926
Chapter 165. Write a program to print all permutations of a given string
?>
Output:
ABC
ACB
BAC
BCA
CBA
CAB
Source
https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
927
Chapter 166
Examples :
ITERATIVE WAY
Algorithm:
Input: num
(1) Initialize rev_num = 0
(2) Loop while num > 0
(a) Multiply rev_num by 10 and add remainder of num
divide by 10 to rev_num
rev_num = rev_num*10 + num%10;
(b) Divide num by 10
(3) Return rev_num
Example:
num = 4562
rev_num = 0
928
Chapter 166. Write a program to reverse digits of a number
#include <stdio.h>
/* Iterative function to reverse digits of num*/
int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}
/*Driver program to test reversDigits*/
int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));
getchar();
return 0;
}
Java
929
Chapter 166. Write a program to reverse digits of a number
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
// Driver code
public static void main (String[] args)
{
int num = 4562;
System.out.println("Reverse of no. is "
+ reversDigits(num));
}
}
// This code is contributed by Anant Agarwal.
Python
C#
930
Chapter 166. Write a program to reverse digits of a number
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num * 10 + num % 10;
num = num / 10;
}
return rev_num;
}
// Driver code
public static void Main()
{
int num = 4562;
Console.Write("Reverse of no. is "
+ reversDigits(num));
}
}
// This code is contributed by Sam007
PHP
<?php
// Iterative function to
// reverse digits of num
function reversDigits($num)
{
$rev_num = 0;
while($num > 1)
{
$rev_num = $rev_num * 10 +
$num % 10;
$num = (int)$num / 10;
}
return $rev_num;
}
// Driver Code
$num = 4562;
echo "Reverse of no. is ",
reversDigits($num);
// This code is contributed by aj_36
?>
931
Chapter 166. Write a program to reverse digits of a number
2654
RECURSIVE WAY
Thanks to Raj for adding this to the original post.
#include <stdio.h>;
/* Recursive function to reverse digits of num*/
int reversDigits(int num)
{
static int rev_num = 0;
static int base_pos = 1;
if(num > 0)
{
reversDigits(num/10);
rev_num += (num%10)*base_pos;
base_pos *= 10;
}
return rev_num;
}
/*Driver program to test reversDigits*/
int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));
getchar();
return 0;
}
932
Chapter 166. Write a program to reverse digits of a number
Source
https://www.geeksforgeeks.org/write-a-program-to-reverse-digits-of-a-number/
933
Chapter 167
The image above is the Calkin-Wilf Tree where all the rational numbers are listed. The
children of a node a/b is calculated as a/(a+b) and (a+b)/b.
The task is to find the nth rational number in breadth first traversal of this tree.
Examples:
Input : 13
Output : [5, 3]
934
Chapter 167. nth Rational number in Calkin-Wilf sequence
Input : 5
Output : [3, 2]
Explanation: This tree is a Perfect Binary Search tree and we need floor(log(n)) steps to
compute nth rational number. The concept is similar to searching in a binary search tree.
Given n we keep dividing it by 2 until we get 0. We return fraction at each stage in the
following manner:-
if n%2 == 0
update frac[1]+=frac[0]
else
update frac[0]+=frac[1]
Below is the program to find the nth number in Calkin Wilf sequence:
C++
935
Chapter 167. nth Rational number in Calkin-Wilf sequence
nthRational(n);
cout << "[" << frac[0] << ","
<< frac[1] << "]" << endl;
return 0;
}
// This code is contributed
// by Harshit Saini
Java
Python3
936
Chapter 167. nth Rational number in Calkin-Wilf sequence
frac = [0, 1]
# returns 1x2 int array
# which contains the nth
# rational number
def nthRational(n):
if n > 0:
nthRational(int(n / 2))
# ~n&1 is equivalent to
# !n%2?1:0 and n&1 is
# equivalent to n%2
frac[~n & 1] += frac[n & 1]
return frac
# Driver code
if __name__ == "__main__":
n = 13 # testing for n=13
# converting array
# to string format
print(nthRational(n))
# This code is contributed
# by Harshit Saini
Output:
[5, 3]
Explanation:
For n = 13,
937
Chapter 167. nth Rational number in Calkin-Wilf sequence
Source
https://www.geeksforgeeks.org/nth-rational-number-in-calkin-wilf-sequence/
938