Hashing
Hashing
4 Applications of Hashing 31
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1
Contents
18 Check if frequency of all characters can become same by one removal 100
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
19 Check if the first and last digit of the smallest number forms a prime 110
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
30 Construct a tree from Inorder and Level order traversals | Set 2 181
2
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
31 Convert a sentence into its equivalent mobile numeric keypad sequence 185
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
39 Count elements that are divisible by at-least one element in another array236
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
40 Count items common to both the lists but with different prices 239
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
46 Count of strings that can be formed from another string using each
character at-most once 273
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
3
Contents
48 Count pairs from two linked lists whose sum is equal to a given value 283
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
49 Count pairs from two sorted arrays whose sum is equal to a given value x296
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
50 Count pairs from two sorted matrices with given sum 316
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
53 Count quadruples from four sorted arrays whose sum is equal to a given
value x 352
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
54 Count subarrays having total distinct elements same as original array 361
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
63 Design a data structure that supports insert, delete, search and getRan-
dom in constant time 407
4
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
66 Different substrings in a string that start and end with given strings 422
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
70 Distributing items when a person cannot take more than two items of
same type 436
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
76 Equally divide into two sets such that one set has maximum distinct
elements 476
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
5
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
80 Find Sum of all unique sub-array sum for a given array. 493
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
81 Find a pair of elements swapping which makes sum of two arrays same 497
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
85 Find all pairs (a,b) and (c,d) in array which satisfy ab = cd 537
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
88 Find any one of the multiple repeating elements in read only array 549
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
91 Find duplicates in a given array when elements are not limited to a range564
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
92 Find elements which are present in first array and not in second 568
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
93 Find four elements a, b, c and d in an array such that a+b = c+d 574
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
95 Find four elements that sum to a given value | Set 3 (Hashmap) 585
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
6
Contents
96 Find if there is a pair in root to a leaf path with sum equals to root’s
data 588
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
104 Find number of pairs in an array such that their XOR is 0 641
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
106 Find pairs in array whose sums already exist in array 657
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
107 Find pairs with given sum such that elements of pair are in different
rows 664
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
109 Find subarray with given sum | Set 2 (Handles Negative Numbers) 677
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
7
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696
113 Find the character in first string that is present at minimum index in
second string 697
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704
114 Find the first non-repeating character from a stream of characters 705
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
117 Find the largest area rectangular sub-matrix whose sum is equal to k 720
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724
119 Find the longest substring with k unique characters in a given string 735
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
120 Find the most frequent digit without using array/string 741
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744
124 Find the smallest window in a string containing all characters of an-
other string 760
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
125 Find the starting indices of the substrings in string (S) which is made
by concatenating all words from a list(L) 767
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
126 Find three element from different three arrays such that that a + b +
c = sum 771
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
8
Contents
131 Find whether an array is subset of another array | Added Method 3 794
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
135 For each element in 1st array count elements less than or equal to it
in 2nd array | Set 2 820
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 823
139 Given a sequence of words, print all anagrams together using STL 840
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 842
140 Given a sequence of words, print all anagrams together | Set 1 843
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 851
141 Given a sequence of words, print all anagrams together | Set 2 852
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 858
142 Given an array A[] and a number x, check for pair in A[] with sum as x859
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 873
144 Given two unsorted arrays, find all pairs whose sum is x 878
9
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884
158 Implementing our Own Hash Table with Separate Chaining in Java 946
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 953
159 Implementing own Hash Table with Open Addressing Linear Probing
in C++ 954
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
160 Index Mapping (or Trivial Hashing) with negatives allowed 960
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 962
10
Contents
167 Largest subset whose all elements are Fibonacci numbers 995
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 998
170 Length of the largest subarray with contiguous elements | Set 2 1006
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1011
11
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1044
179 Longest subarray having count of 1s one more than count of 0s 1048
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1050
181 Longest subarray not having more than K distinct elements 1054
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1056
191 Maximum area rectangle by picking four sides from array 1096
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1102
192 Maximum array from two given arrays keeping order same 1103
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1105
12
Contents
199 Maximum length subsequence possible of the form R^N K^N 1129
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1132
206 Minimum Index Sum for Common Elements of Two Lists 1171
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1173
13
Contents
209 Minimum delete operations to make all elements of array same 1180
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1181
14
Contents
230 Numbers with sum of digits equal to the sum of digits of its all prime
factor 1280
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1289
231 Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap) 1290
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1292
232 Only integer with positive value in positive negative value in array 1293
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1299
233 Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) 1300
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1303
234 Pair with given product | Set 1 (Find if any pair exists) 1304
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1312
235 Pair with given sum and maximum shortest distance from end 1313
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1315
240 Postorder traversal of Binary Tree without recursion and without stack 1341
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1344
15
Contents
246 Print a Binary Tree in Vertical Order | Set 2 (Map based Method) 1376
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1383
247 Print a Binary Tree in Vertical Order | Set 3 (Using Level Order
Traversal) 1384
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1391
248 Print all Subsequences of String which Start with Vowel and End with
Consonant. 1392
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1394
253 Print array elements that are divisible by at-least one other 1429
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1434
254 Print n smallest elements from given array in their original order 1435
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1437
255 Print the last occurrence of elements in array in relative order 1438
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1441
258 Queries to find distance between two nodes of a Binary tree 1449
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1451
16
Contents
259 Queries to find distance between two nodes of a Binary tree – O(logn)
method 1452
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1460
260 Queries to insert, delete one occurrence of a number and print the
least and most frequent element 1461
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1466
261 Queue based approach for first non-repeating character in a stream 1467
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1470
269 Root to leaf paths having equal lengths in a Binary Tree 1515
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1517
272 Smallest element in an array that is repeated exactly ‘k’ times. 1526
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1539
273 Smallest element repeated exactly ‘k’ times (not limited to small range) 1540
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1543
274 Smallest subarray with all occurrences of a most frequent element 1544
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1548
17
Contents
276 Smallest window that contains all characters of string itself 1555
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1560
277 Sort an array according to absolute difference with given value 1561
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1563
278 Sort elements by frequency | Set 4 (Efficient approach using hash) 1564
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1566
280 Sort the linked list in the order of elements appearing in the array 1571
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1574
282 Split array to three subarrays such that sum of first and third subarray
is equal and maximum 1580
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1582
288 Sum of f(a[i], a[j]) over all pairs in an array of n integers 1608
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1611
289 Traversal of tree with k jumps allowed between nodes of same height 1612
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1617
291 Union and Intersection of two linked lists | Set-2 (Using Merge Sort) 1631
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1637
18
Contents
292 Union and Intersection of two linked lists | Set-3 (Hashing) 1638
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1642
293 Unique element in an array where all elements occur k times except one 1643
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1645
19
Chapter 1
1. We can get all keys in sorted order by just doing Inorder Traversal of BST. This is
not a natural operation in Hash Tables and requires extra efforts.
2. Doing order statistics, finding closest lower and greater elements, doing range queries
are easy to do with BSTs. Like sorting, these operations are not a natural operation
with Hash Tables.
3. BSTs are easy to implement compared to hashing, we can easily implement our own
customized BST. To implement Hashing, we generally rely on libraries provided by
programming languages.
4. With Self-Balancing BSTs, all operations are guaranteed to work in O(Logn) time.
But with Hashing, Θ(1) is average time and some particular operations may be costly,
especially when table resizing happens.
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
20
Chapter 1. Advantages of BST over Hash Table
Source
https://www.geeksforgeeks.org/advantages-of-bst-over-hash-table/
21
Chapter 2
Input : 1, 1, 1, 1, 1
Output : All Elements are Same
Method 1 (Hashing) We create an empty HashSet, insert all elements into it, then we
finally see if size of the HashSet is one or not.
22
Chapter 2. All elements in an array are Same or not?
Output:
23
Chapter 2. All elements in an array are Same or not?
else
System.out.println("Not all Elements are Same");
}
}
Output:
Source
https://www.geeksforgeeks.org/all-elements-in-an-array-are-same-or-not/
24
Chapter 3
In a previous post, Find a triplet that sum to a given value we have discussed whether the
triplets can be formed from the array or not.
Here we need to print all unique set of triplets that sum up to a given value
1. Sort the input array.
2. Find three indexes from the array i, j and k where A[i]+A[j]+A[k] = given sum value.
3. Fix the first element as A[i] and iterate i from 0 to array size – 2.
4. For each iteration of i, take j to be index of the first element in the remaining elements
and k to be index of the last element.
5. Check for the triplet combination A[i]+A[j]+A[k] = given sum value.
25
Chapter 3. All unique triplets that sum up to a given value
26
Chapter 3. All unique triplets that sum up to a given value
27
Chapter 3. All unique triplets that sum up to a given value
Java
28
Chapter 3. All unique triplets that sum up to a given value
29
Chapter 3. All unique triplets that sum up to a given value
Output:
Source
https://www.geeksforgeeks.org/unique-triplets-sum-given-value/
30
Chapter 4
Applications of Hashing
• Message Digest
• Password Verification
• Data Structures(Programming Languages)
• Compiler Operation
• Rabin-Karp Algotithm
• Linking File name and path together
Message Digest:
This is an application of cryptographic Hash Functions. Cryptographic hash functions are
the functions which produce an output from which reaching the input is close to impossible.
This property of hash functions is called irreversibility.
Lets take an Example:
Suppose you have to store your files on any of the cloud services available. You have to
be sure that the files that you store are not tampered by any third party. You do it by
computing “hash” of that file using a Cryptographic hash algorithm. One of the common
cryptographic hash algorithms is SHA 256. The hash thus computed has a maximum size
of 32 bytes. So a computing the
hash of large number of files will not be a problem. You save these hashes on your local
machine.
Now, when you download the files, you compute the hash again. Then you match it with
the previous hash computed. Therefore, you know whether your files were tampered or not.
31
Chapter 4. Applications of Hashing
If anybody tamper with the file, the hash value of the file will definitely change. Tampering
the file without changing the hash is nearly impossible.
Password Verification
Cryptographic hash functions are very commonly used in password verification. Let’s un-
derstand this using an Example:
When you use any online website which requires a user login, you enter your E-mail and
password to authenticate that the account you are trying to use belongs to you. When the
password is entered, a hash of the password is computed which is then sent to the server
for verification of the password. The passwords stored on the server are actually computed
hash values of the original passwords. This is done to ensure that when the password is sent
from client to server, no sniffing is there.
Data Structures(Programming Languages):
Various programming languages have hash table based Data Structures. The basic idea is
to create a key-value pair where key is supposed to be a unique value, whereas value can be
same for different keys. This implementation is seen in unordered_set & unordered_map
in C++, HashSet & HashMap in java, dict in python etc.
Compiler Operation:
The keywords of a programming language are processed differently than other identifiers.
To differentiate between the keywords of a programming language(if, else, for, return etc.)
and other identifiers and to successfully compile the program, the compiler stores all these
keywords in a set which is implemented using a hash table.
Rabin-Karp Algorithm:
One of the most famous applications of hashing is the Rabin-Karp algorithm. This is
basically a string-searching algorithm which uses hashing to find any one set of patterns in
a string. A practical application of this algorithm is detecting plagiarism. To know more
about Rabin-Karp algo go through Searching for Patterns | Set 3 (Rabin-Karp Algorithm).
Linking File name and path together:
When moving through files on our local system, we observe two very crucial components of
a file i.e. file_name and file_path. In order to store the correspondence between file_name
and file_path the system uses a map(file_name, file_path)which is implemented using a
hash table.
Related articles:
Hashing vs BST
Hashing vs Trie
Source
https://www.geeksforgeeks.org/applications-of-hashing/
32
Chapter 5
The idea is to use Hashing to solve this in O(n) time on average. We store elements and
their counts in a hash table. After storing counts, we traverse input array again and print
those elements whose counts are more than once. To make sure that every output element
is printed only once, we set count as 0 after printing the element.
C++
33
Chapter 5. Array elements that appear more than once
{
// Store elements and their counts in
// hash table
unordered_map<int, int> mp;
for (int i = 0; i < n; i++)
mp[arr[i]]++;
// Since we want elements in same order,
// we traverse array again and print
// those elements that appear more than
// once.
for (int i = 0; i < n; i++)
{
if (mp[arr[i]] > 1)
{
cout << arr[i] << " ";
// This is tricky, this is done
// to make sure that the current
// element is not printed again
mp[arr[i]] = 0;
}
}
}
// Driver code
int main()
{
int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = sizeof(arr) / sizeof(arr[0]);
printRepeating(arr, n);
return 0;
}
Python3
34
Chapter 5. Array elements that appear more than once
Output :
10 45
Time Complexity : O(n) under the assumption that hash insert and search functions
work in O(1) time.
Improved By : Smitha Dinesh Semwal
Source
https://www.geeksforgeeks.org/array-elements-that-appear-more-than-once/
35
Chapter 6
36
Chapter 6. C++ program for hashing with chaining
37
Chapter 6. C++ program for hashing with chaining
int hashFunction(int x) {
return (x % BUCKET);
}
void displayHash();
};
Hash::Hash(int b)
{
this->BUCKET = b;
table = new list<int>[BUCKET];
}
void Hash::insertItem(int key)
{
int index = hashFunction(key);
table[index].push_back(key);
}
void Hash::deleteItem(int key)
{
// get the hash index of key
int index = hashFunction(key);
// find the key in (inex)th list
list <int> :: iterator i;
for (i = table[index].begin();
i != table[index].end(); i++) {
if (*i == key)
break;
}
// if key is found in hash table, remove it
if (i != table[index].end())
table[index].erase(i);
}
// function to display hash table
void Hash::displayHash() {
for (int i = 0; i < BUCKET; i++) {
cout << i;
for (auto x : table[i])
cout << " --> " << x;
cout << endl;
}
}
// Driver program
38
Chapter 6. C++ program for hashing with chaining
int main()
{
// array that contains keys to be mapped
int a[] = {15, 11, 27, 8, 12};
int n = sizeof(a)/sizeof(a[0]);
// insert the keys into the hash table
Hash h(7); // 7 is count of buckets in
// hash table
for (int i = 0; i < n; i++)
h.insertItem(a[i]);
// delete 12 from hash table
h.deleteItem(12);
// display the Hash table
h.displayHash();
return 0;
}
Output:
0
1 --> 15 --> 8
2
3
4 --> 11
5
6 --> 27
Source
https://www.geeksforgeeks.org/c-program-hashing-chaining/
39
Chapter 7
Input : "egrt"
Output : code
Idea behind conversion of new character set is to use hashing. Perform hashing of new
character set where element of set is index and its position will be new alphabet value.
Approach1:
Given New character set = “qwertyuiopasdfghjklzxcvbnm”
1. First character is q, during hashing we will place ‘a’ (for position ) at index q i.e.
(17th ).
2. After hashing our new character set is “kvmcnophqrszyijadlegwbuft”.
3. For input “egrt” =
hash[e -‘a’] = c
hash[g -‘a’] = o
40
Chapter 7. Change string to a new character set
hash[r -‘a’] = d
hash[t -‘a’] = e
For “egrt” is equivalent to “code”.
C++
Output:
code
Approach2:
1.Initialize two strings, one with actual set of alphabets and another with modified one.
2.Get the string to be converted from the user.
3.Retrive the first element of the string, find its index in the modified set of alphabets(eg:0
for ‘q’).
4.Find the element of same index in the actual set of alphabets and concatenate it with
41
Chapter 7. Change string to a new character set
Python3
Output:
code
Improved By : PradeepEswar
Source
https://www.geeksforgeeks.org/change-string-to-a-new-character-set/
42
Chapter 8
Approach:Observe that we don’t need to change the numbers which are in the range [1,
n] and which are distinct(has only one occurrence). So, we use a greedy approach. If we
meet the number we have never met before and this number is between 1 and n, we leave
this number unchanged. And remove the duplicate elements and add the missing elements
in the range [1, n]. Also replace the numbers, not in the range.
43
Chapter 8. Change the array into a permutation of numbers from 1 to n
C++
Python3
44
Chapter 8. Change the array into a permutation of numbers from 1 to n
# minimum changes.
def makePermutation (a, n):
# Store counts of all elements.
count = dict()
for i in range(n):
if count.get(a[i]):
count[a[i]] += 1
else:
count[a[i]] = 1;
next_missing = 1
for i in range(n):
if count[a[i]] != 1 or a[i] > n or a[i] < 1:
count[a[i]] -= 1
# Find next missing element to put
# in place of current element.
while count.get(next_missing):
next_missing+=1
# Replace with next missing and
# insert the missing element in hash.
a[i] = next_missing
count[next_missing] = 1
# Driver Code
A = [ 2, 2, 3, 3 ]
n = len(A)
makePermutation(A, n)
for i in range(n):
print(A[i], end = " ")
# This code is contributed by "Sharad_Bhardwaj".
Output:
1 2 4 3
Source
https://www.geeksforgeeks.org/change-array-permutation-numbers-1-n/
45
Chapter 9
Examples:
Input : geeks
Output : sesg
Explanation : minimized string = geks
length of original string = 5
ascii value of g = 103
IND for g = (103*103) % 5 = 4
replacement character for g = s
character 's' present at index 4 of original string
Similarly,
replacement character for e = e
replacement character for k = s
replacement character for s = g
46
Chapter 9. Character replacement after removing duplicates from a string
Input : helloworld
Output : oeoeeoh
Approach:
Below is the step by step algorithm for string minimization:
47
Chapter 9. Character replacement after removing duplicates from a string
Output:
48
Chapter 9. Character replacement after removing duplicates from a string
Source
https://www.geeksforgeeks.org/character-replacement-string-minimization/
49
Chapter 10
50
Chapter 10. Check for Palindrome after every character replacement Query
query 3: i1 = 3, i2 = 7 ch = ‘a’
Output :
query 1: “NO”
query 2: “NO”
query 3: “YES”
A Simple solution is that for each query , we replace character at indexes (i1 & i2) with
a new character ‘ch’ and then check if string is palindrome or not.
Below is C++ implementation of above idea
51
Chapter 10. Check for Palindrome after every character replacement Query
}
// Driver program
int main()
{
char str[] = "geeks";
int Q = 2;
Query(str, Q);
return 0;
}
Input:
3 0 e
0 2 s
Output:
"NO"
"YES"
52
Chapter 10. Check for Palindrome after every character replacement Query
53
Chapter 10. Check for Palindrome after every character replacement Query
Input:
3 0 e
0 2 s
Output:
"NO"
"YES"
Time Complexity : O(Q + n) under the assumption that set insert, delete and find operations
take O(1) time.
54
Chapter 10. Check for Palindrome after every character replacement Query
Source
https://www.geeksforgeeks.org/check-for-palindrome-after-every-character-replacement-query/
55
Chapter 11
Check if a given array contains duplicate elements within k distance from each other -
GeeksforGeeks
Given an unsorted array that may contain duplicates. Also given a number k which is
smaller than size of array. Write a function that returns true if array contains duplicates
within k distance.
Examples:
A Simple Solution is to run two loops. The outer loop picks every element ‘arr[i]’ as a
starting element, the inner loop compares all elements which are within k distance of ‘arr[i]’.
The time complexity of this solution is O(kn).
56
Chapter 11. Check if a given array contains duplicate elements within k distance from
each other
We can solve this problem in Θ(n) time using Hashing. The idea is to one by add
elements to hash. We also remove elements which are at more than k distance from current
element. Following is detailed algorithm.
1) Create an empty hashtable.
2) Traverse all elements from left from right. Let the current element be ‘arr[i]’
….a) If current element ‘arr[i]’ is present in hashtable, then return true.
….b) Else add arr[i] to hash and remove arr[i-k] from hash if i is greater than or equal to k
C/C++
#include<bits/stdc++.h>
using namespace std;
/* C++ program to Check if a given array contains duplicate
elements within k distance from each other */
bool checkDuplicatesWithinK(int arr[], int n, int k)
{
// Creates an empty hashset
set<int> myset;
// Traverse the input array
for (int i = 0; i < n; i++)
{
// If already present n hash, then we found
// a duplicate within k distance
if (myset.find(arr[i]) != myset.end())
return true;
// Add this item to hashset
myset.insert(arr[i]);
// Remove the k+1 distant item
if (i >= k)
myset.erase(arr[i-k]);
}
return false;
}
// Driver method to test above method
int main ()
{
int arr[] = {10, 5, 3, 4, 3, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
if (checkDuplicatesWithinK(arr, n, 3))
cout << "Yes";
else
cout << "No";
}
57
Chapter 11. Check if a given array contains duplicate elements within k distance from
each other
//This article is contributed by Chhavi
JAVA
Output:
Yes
58
Chapter 11. Check if a given array contains duplicate elements within k distance from
each other
This article is contributed by Anuj. 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/check-given-array-contains-duplicate-elements-within-k-distance/
59
Chapter 12
Input : Machine
Output : True
"Machine" does not have any character repeating,
it is an Isogram
Input : Geek
Output : False
"Geek" has 'e' as repeating character,
it is not an Isogram
C++
60
Chapter 12. Check if a string is Isogram or not
// Convert the string in lower case letters
for (int i = 0; i < len; i++)
str[i] = tolower(str[i]);
sort(str.begin(), str.end());
for (int i = 0; i < len; i++) {
if (str[i] == str[i + 1])
return "False";
}
return "True";
}
// driver program
int main()
{
string str1 = "Machine";
cout << is_isogram(str1) << endl;
string str2 = "isogram";
cout << is_isogram(str2) << endl;
string str3 = "GeeksforGeeks";
cout << is_isogram(str3) << endl;
string str4 = "Alphabet";
cout << is_isogram(str4) << endl;
return 0;
}
// Contributed by nuclode
Java
61
Chapter 12. Check if a string is Isogram or not
Python
62
Chapter 12. Check if a string is Isogram or not
return False
letter_list.append(letter)
return True
if __name__ == '__main__':
print(is_isogram("Machine"))
print(is_isogram("isogram"))
print(is_isogram("GeeksforGeeks"))
print(is_isogram("Alphabet "))
C#
63
Chapter 12. Check if a string is Isogram or not
string str4 = "Alphabet";
Console.WriteLine(is_isogram(str4));
}
}
// This code is contributed by Sam007
Output:
True
True
False
False
Another approach : In this, count of characters of string are stored in hashmap, and
wherever it is found to be greater than 1 for any char, return false else return true.
64
Chapter 12. Check if a string is Isogram or not
Output :
False
True
Source
https://www.geeksforgeeks.org/check-string-isogram-not/
65
Chapter 13
Input : 1, 3, 2, 4
Output : Yes
One simple solution is to use two nested loops. For every element, check if it repeats or
not. If any element repeats, return false. If no element repeats, return false.
An efficient solution is to Hashing. We put all array elements in a HashSet. If size of
HashSet remains same as array size, then we return true.
C++
66
Chapter 13. Check if all array elements are distinct
int n = arr.size();
// Put all array elements in a map
map<int, bool> s ;
for(int i=0; i<n; i++){
s.insert(pair<int, int>(arr[i],true));
}
// If all elements are distinct, size of
// map should be same array.
return (s.size() == arr.size());
}
// Driver code
int main(){
std::vector<int>arr = {1, 2, 3, 2};
if(areDistinct(arr)){
cout<<"All Elements are Distinct";
}
else{
cout<<"Not all Elements are Distinct";
}
return 0;
}
Java
67
Chapter 13. Check if all array elements are distinct
Output:
Source
https://www.geeksforgeeks.org/check-if-all-array-elements-are-distinct/
68
Chapter 14
Check if an array can be divided into pairs whose sum is divisible by k - GeeksforGeeks
Given an array of integers and a number k, write a function that returns true if given array
can be divided into pairs such that sum of every pair is divisible by k.
Examples:
A Simple Solution is to iterate through every element arr[i]. Find if there is another
not yet visited element that has remainder as (k – arr[i]%k). If there is no such element,
69
Chapter 14. Check if an array can be divided into pairs whose sum is divisible by k
return false. If a pair is found, then mark both elements as visited. Time complexity of this
solution is O(n2 and it requires O(n) extra space.
An Efficient Solution is to use Hashing.
70
Chapter 14. Check if an array can be divided into pairs whose sum is divisible by k
Java
71
Chapter 14. Check if an array can be divided into pairs whose sum is divisible by k
import java.util.HashMap;
public class Divisiblepair
{
// Returns true if arr[0..n-1] can be divided into pairs
// with sum divisible by k.
static boolean canPairs(int ar[], int k)
{
// An odd length array cannot be divided into pairs
if (ar.length % 2 == 1)
return false;
// Create a frequency array to count occurrences
// of all remainders when divided by k.
HashMap<Integer, Integer> hm = new HashMap<>();
// Count occurrences of all remainders
for (int i = 0; i < ar.length; i++)
{
int rem = ar[i] % k;
if (!hm.containsKey(rem))
{
hm.put(rem, 0);
}
hm.put(rem, hm.get(rem) + 1);
}
// Traverse input array and use freq[] to decide
// if given array can be divided in pairs
for (int i = 0; i < ar.length; i++)
{
// Remainder of current element
int rem = ar[i] % k;
// If remainder with current element divides
// k into two halves.
if (2 * rem == k)
{
// Then there must be even occurrences of
// such remainder
if (hm.get(rem) % 2 == 1)
return false;
}
// If remainder is 0, then there must be two
// elements with 0 remainder
else if (rem == 0)
72
Chapter 14. Check if an array can be divided into pairs whose sum is divisible by k
{
// Then there must be even occurrences of
// such remainder
if (hm.get(rem) % 2 == 1)
return false;
}
// Else number of occurrences of remainder
// must be equal to number of occurrences of
// k - remainder
else
{
if (hm.get(k - rem) != hm.get(rem))
return false;
}
}
return true;
}
// Driver program to test above functions
public static void main(String[] args)
{
int arr[] = { 92, 75, 65, 48, 45, 35 };
int k = 10;
boolean ans = canPairs(arr, k);
if (ans)
System.out.println("True");
else
System.out.println("False");
}
}
// This code is contributed by Rishabh Mahrsee
Output:
True
This article is contributed by Priyanka. 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/check-if-an-array-can-be-divided-into-pairs-whose-sum-is-divisible-by-k/
73
Chapter 15
Input : geeksforgeeks
Output : No
There is no palindrome anagram of
given string
Input : geeksgeeks
Output : Yes
There are palindrome anagrams of
given string. For example kgeeseegk
This problem is basically same as Check if characters of a given string can be rearranged to
form a palindrome. We can do it in O(n) time using a count array. Following are detailed
steps.
1) Create a count array of alphabet size which is typically 256. Initialize all values of count
array as 0.
2) Traverse the given string and increment count of every character.
3) Traverse the count array and if the count array has more than one odd values, return
false. Otherwise return true.
C++
74
Chapter 15. Check if any anagram of a string is palindrome or not
#include <iostream>
using namespace std;
#define NO_OF_CHARS 256
/* function to check whether characters of a string
can form a palindrome */
bool canFormPalindrome(string str)
{
// Create a count array and initialize all
// values as 0
int count[NO_OF_CHARS] = { 0 };
// For each character in input strings,
// increment count in the corresponding
// count array
for (int i = 0; str[i]; i++)
count[str[i]]++;
// Count odd occurring characters
int odd = 0;
for (int i = 0; i < NO_OF_CHARS; i++) {
if (count[i] & 1)
odd++;
if (odd > 1)
return false;
}
// Return true if odd count is 0 or 1,
return true;
}
/* Driver program to test to print printDups*/
int main()
{
canFormPalindrome("geeksforgeeks") ? cout << "Yes\n" : cout << "No\n";
canFormPalindrome("geeksogeeks") ? cout << "Yes\n" : cout << "No\n";
return 0;
}
Java
75
Chapter 15. Check if any anagram of a string is palindrome or not
Python
NO_OF_CHARS = 256
""" function to check whether characters of a string
can form a palindrome """
def canFormPalindrome(string):
76
Chapter 15. Check if any anagram of a string is palindrome or not
C#
77
Chapter 15. Check if any anagram of a string is palindrome or not
{
// Create a count array and
// initialize all values as 0
int[] count = new int[NO_OF_CHARS];
// For each character in input
// strings, increment count in
// the corresponding count array
for (int i = 0; i < str.Length; i++)
count[str[i]]++;
// Count odd occurring characters
int odd = 0;
for (int i = 0; i < NO_OF_CHARS; i++) {
if ((count[i] & 1) != 0)
odd++;
if (odd > 1)
return false;
}
// Return true if odd count
// is 0 or 1,
return true;
}
// Driver program
public static void Main()
{
Console.WriteLine(
canFormPalindrome("geeksforgeeks")
? "Yes" : "No");
Console.WriteLine(
canFormPalindrome("geeksogeeks")
? "Yes" : "No");
}
}
// This code is contributed by vt_m.
Output:
No
Yes
Improved By : vt_m
78
Chapter 15. Check if any anagram of a string is palindrome or not
Source
https://www.geeksforgeeks.org/check-anagram-string-palindrome-not/
79
Chapter 16
80
Chapter 16. Check if array contains contiguous integers with duplicates allowed
Java
81
Chapter 16. Check if array contains contiguous integers with duplicates allowed
class GFG {
// function to check whether
// the array contains a set
// of contiguous integers
static boolean areElementsContiguous(int arr[],
int n)
{
// Sort the array
Arrays.sort(arr);
// After sorting, check if
// current element is either
// same as previous or is
// one more.
for (int i = 1; i < n; i++)
if (arr[i] - arr[i-1] > 1)
return false;
return true;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = arr.length;
if (areElementsContiguous(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
82
Chapter 16. Check if array contains contiguous integers with duplicates allowed
C#
83
Chapter 16. Check if array contains contiguous integers with duplicates allowed
}
// Driver program
public static void Main()
{
int []arr = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = arr.Length;
if (areElementsContiguous(arr, n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by Vt_m.
Output:
Yes
84
Chapter 16. Check if array contains contiguous integers with duplicates allowed
{
// Find maximum and
// minimum elements.
int max = *max_element(arr, arr + n);
int min = *min_element(arr, arr + n);
int m = max - min + 1;
// There should be at least
// m elements in array to
// make them contiguous.
if (m > n)
return false;
// Create a visited array
// and initialize false.
bool visited[m];
memset(visited, false, sizeof(visited));
// Mark elements as true.
for (int i=0; i<n; i++)
visited[arr[i] - min] = true;
// If any element is not
// marked, all elements
// are not contiguous.
for (int i=0; i<m; i++)
if (visited[i] == false)
return false;
return true;
}
// Driver program
int main()
{
int arr[] = { 5, 2, 3, 6,
4, 4, 6, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
if (areElementsContiguous(arr, n))
cout << "Yes";
else
cout << "No";
return 0;
}
85
Chapter 16. Check if array contains contiguous integers with duplicates allowed
Java
86
Chapter 16. Check if array contains contiguous integers with duplicates allowed
Python3
# Python3 implementation to
# check whether the array
# contains a set of
# contiguous integers
# function to check
# whether the array
# contains a set of
# contiguous integers
def areElementsContiguous(arr, n):
# Find maximum and
# minimum elements.
max1 = max(arr)
min1 = min(arr)
m = max1 - min1 + 1
# There should be at least
# m elements in array to
# make them contiguous.
if (m > n):
87
Chapter 16. Check if array contains contiguous integers with duplicates allowed
return False
# Create a visited array
# and initialize fals
visited = [0] * m
# Mark elements as true.
for i in range(0,n) :
visited[arr[i] - min1] = True
# If any element is not
# marked, all elements
# are not contiguous.
for i in range(0, m):
if (visited[i] == False):
return False
return True
# Driver program
arr = [5, 2, 3, 6, 4, 4, 6, 6 ]
n = len(arr)
if (areElementsContiguous(arr, n)):
print("Yes")
else:
print("No")
# This code is contributed by Smitha Dinesh Semwal
C#
88
Chapter 16. Check if array contains contiguous integers with duplicates allowed
89
Chapter 16. Check if array contains contiguous integers with duplicates allowed
Console.Write("No");
}
}
// This code is contributed by nitin mittal.
Output:
Yes
90
Chapter 16. Check if array contains contiguous integers with duplicates allowed
count++;
// update 'curr_ele"
curr_ele--;
}
// starting with next greater element
// of arr[0]
curr_ele = arr[0] + 1;
// if 'curr_ele' is present in 'us'
while (us.find(curr_ele) != us.end()) {
// increment count
count++;
// update 'curr_ele"
curr_ele++;
}
// returns true if array contains a set of
// contiguous integers else returns false
return (count == (int)(us.size()));
}
// Driver program to test above
int main()
{
int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
if (areElementsContiguous(arr, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
91
Chapter 16. Check if array contains contiguous integers with duplicates allowed
92
Chapter 16. Check if array contains contiguous integers with duplicates allowed
int arr[] = { 5, 2, 3, 6, 4, 4, 6, 6 };
int n = arr.length;
if (areElementsContiguous(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by 'Gitanjali'.
Python
93
Chapter 16. Check if array contains contiguous integers with duplicates allowed
Output :
Yes
Source
https://www.geeksforgeeks.org/check-array-contains-contiguous-integers-duplicates-allowed/
94
Chapter 17
C++
95
Chapter 17. Check if characters of a given string can be rearranged to form a palindrome
Java
96
Chapter 17. Check if characters of a given string can be rearranged to form a palindrome
import java.util.*;
import java.math.*;
class GFG {
static int NO_OF_CHARS = 256;
/* function to check whether characters
of a string can form a palindrome */
static boolean canFormPalindrome(String str) {
// Create a count array and initialize all
// values as 0
int count[] = new int[NO_OF_CHARS];
Arrays.fill(count, 0);
// For each character in input strings,
// increment count in the corresponding
// count array
for (int i = 0; i < str.length(); i++)
count[(int)(str.charAt(i))]++;
// Count odd occurring characters
int odd = 0;
for (int i = 0; i < NO_OF_CHARS; i++)
{
if ((count[i] & 1) == 1)
odd++;
if (odd > 1)
return false;
}
// Return true if odd count is 0 or 1,
return true;
}
// Driver program
public static void main(String args[])
{
if (canFormPalindrome("geeksforgeeks"))
System.out.println("Yes");
else
System.out.println("No");
if (canFormPalindrome("geeksogeeks"))
System.out.println("Yes");
else
97
Chapter 17. Check if characters of a given string can be rearranged to form a palindrome
System.out.println("No");
}
}
// This code is contributed by Nikita Tiwari.
Python3
98
Chapter 17. Check if characters of a given string can be rearranged to form a palindrome
print("Yes")
else :
print("No")
# This code is contributed by Nikita Tiwari.
Output:
No
Yes
This article is contributed by Abhishek. 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/check-characters-given-string-can-rearranged-form-palindrome/
99
Chapter 18
Check if frequency of all characters can become same by one removal - GeeksforGeeks
Given a string which contains lower alphabetic characters, we need to remove at most one
character from this string in such a way that frequency of each distinct character becomes
same in the string.
Examples:
Main thing to observe in this problem is that position of characters does not matter here
so we will count the frequency of characters, if all of them are same then we are done and
100
Chapter 18. Check if frequency of all characters can become same by one removal
there is no need to remove any character to make frequency of characters same Otherwise
we can iterate over all characters one by one and decrease their frequency by one, if all
frequencies become same then we will flag that it is possible to make character frequency
same by at most one removal and if frequencies doesn’t match then we will increase that
frequency again and loop for other characters.
C++
101
Chapter 18. Check if frequency of all characters can become same by one removal
Java
102
Chapter 18. Check if frequency of all characters can become same by one removal
103
Chapter 18. Check if frequency of all characters can become same by one removal
// if all frequencies are same, then return true
if (allSame(freq, M))
return true;
/* Try decreasing frequency of all character
by one and then check all equality of all
non-zero frequencies */
for (char c = 'a'; c <= 'z'; c++)
{
int i = getIdx(c);
// Check character only if it occurs in str
if (freq[i] > 0)
{
freq[i]--;
if (allSame(freq, M))
return true;
freq[i]++;
}
}
return false;
}
// Driver code to test above methods
public static void main(String args[])
{
String str = "xyyzz";
if (possibleSameCharFreqByOneRemoval(str))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Sumit Ghosh
C#
104
Chapter 18. Check if frequency of all characters can become same by one removal
// Utility method to get
// index of character ch
// in lower alphabet characters
static int getIdx(char ch)
{
return (ch - 'a');
}
// Returns true if all
// non-zero elements
// values are same
static bool allSame(int[] freq,
int N)
{
int same = 0;
// get first non-zero element
int i;
for (i = 0; i < N; i++)
{
if (freq[i] > 0)
{
same = freq[i];
break;
}
}
// check equality of
// each element with
// variable same
for (int j = i + 1; j < N; j++)
if (freq[j] > 0 &&
freq[j] != same)
return false;
return true;
}
// Returns true if we
// can make all character
// frequencies same
static bool possibleSameCharFreqByOneRemoval(string str)
{
int l = str.Length;
// fill frequency array
int[] freq = new int[M];
105
Chapter 18. Check if frequency of all characters can become same by one removal
for (int i = 0; i < l; i++)
freq[getIdx(str[i])]++;
// if all frequencies are same,
// then return true
if (allSame(freq, M))
return true;
/* Try decreasing frequency of all
character by one and then check
all equality of all non-zero
frequencies */
for (char c = 'a'; c <= 'z'; c++)
{
int i = getIdx(c);
// Check character only if
// it occurs in str
if (freq[i] > 0)
{
freq[i]--;
if (allSame(freq, M))
return true;
freq[i]++;
}
}
return false;
}
// Driver code
public static void Main()
{
string str = "xyyzz";
if (possibleSameCharFreqByOneRemoval(str))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed
// by ChitraNayal
PHP
106
Chapter 18. Check if frequency of all characters can become same by one removal
<?php
// PHP program to get same frequency
// character string by removal of at
// most one char
$M = 26;
// Utility method to get index
// of character ch in lower
// alphabet characters
function getIdx($ch)
{
return ($ch - 'a');
}
// Returns true if all
// non-zero elements
// values are same
function allSame(&$freq, $N)
{
// get first non-zero element
for ($i = 0; $i < $N; $i++)
{
if ($freq[$i] > 0)
{
$same = $freq[$i];
break;
}
}
// check equality of each
// element with variable same
for ($j = $i + 1; $j < $N; $j++)
if ($freq[$j] > 0 &&
$freq[$j] != $same)
return false;
return true;
}
// Returns true if we
// can make all character
// frequencies same
function possibleSameCharFreqByOneRemoval($str)
{
global $M;
$l = strlen($str);
// fill frequency array
107
Chapter 18. Check if frequency of all characters can become same by one removal
Output:
Yes
108
Chapter 18. Check if frequency of all characters can become same by one removal
Source
https://www.geeksforgeeks.org/check-if-frequency-of-all-characters-can-become-same-by-one-removal/
109
Chapter 19
Check if the first and last digit of the smallest number forms a prime - GeeksforGeeks
Given an array arr[] containing numbers from 0 to 9 only, the task is to form the minimum
possible number from the given digits and then check if the first and last digit of the number
thus created can be rearranged to form a prime number or not.
Examples:
Input: arr[]={2, 6, 4, 9}
Output: Minimum number: 2469
Prime number combinations: 29
The first and last digits are 2 and 9 respectively. The combinations are 29 and
92. Only 29 is prime.
Input: arr[]={2, 6, 4, 3, 1, 7}
Output: Minimum number: 123467
Prime number combinations: 17 71
The first and last digits are 1 and 7 respectively. The combinations are 17 and
71, and both are primes
Approach:
1. Create a hash of size 10 to store the number of occurrences of the digits in the given
array into the hash table.
2. Print the digits the number of times they occur in descending order starting from the
digit 0. It is similar to Smallest number by rearranging digits of a given number.
3. For the prime checking, check if the number formed using the first and last digits is
prime or not. Do the same for its reverse.
110
Chapter 19. Check if the first and last digit of the smallest number forms a prime
C++
111
Chapter 19. Check if the first and last digit of the smallest number forms a prime
// extracting the first digit
for (i = 0; i <= 9; i++) {
if (hash[i] != 0) {
first = i;
break;
}
}
// extracting the last digit
for (i = 9; i >= 0; i--) {
if (hash[i] != 0) {
last = i;
break;
}
}
num = first * 10 + last;
rev = last * 10 + first;
// printing the prime combinations
cout << "Prime combinations: ";
if (isPrime(num) && isPrime(rev))
cout << num << " " << rev;
else if (isPrime(num))
cout << num;
else if (isPrime(rev))
cout << rev;
else
cout << "No combinations exist";
}
// Driver code
int main()
{
int arr[] = { 1, 2, 4, 7, 8};
findMinNum(arr, 5);
return 0;
}
Java
// Java implementation of above approach
112
Chapter 19. Check if the first and last digit of the smallest number forms a prime
import java.io.*;
class SmallPrime
{
// function to check prime
static boolean isPrime(int n)
{
int i, c = 0;
for (i = 1; i < n / 2; i++)
{
if (n % i == 0)
c++;
}
if (c == 1)
{
return true;
}
else
{
return false;
}
}
// Function to generate smallest possible
// number with given digits
static void findMinNum(int arr[], int n)
{
// Declare a hash array of size 10
// and initialize all the elements to zero
int first = 0, last = 0, num, rev, i;
int hash[] = new int[10];
// store the number of occurrences of the digits
// in the given array into the hash table
for ( i = 0; i < n; i++)
{
hash[arr[i]]++;
}
// Traverse the hash in ascending order
// to print the required number
System.out.print("Minimum number: ");
for ( i = 0; i <= 9; i++)
{
// Print the number of times a digits occurs
for (int j = 0; j < hash[i]; j++)
113
Chapter 19. Check if the first and last digit of the smallest number forms a prime
System.out.print(i);
}
System.out.println();
System.out.println();
// extracting the first digit
for (i = 0; i <= 9; i++)
{
if (hash[i] != 0)
{
first = i;
break;
}
}
// extracting the last digit
for (i = 9; i >= 0; i--)
{
if (hash[i] != 0)
{
last = i;
break;
}
}
num = first * 10 + last;
rev = last * 10 + first;
// printing the prime combinations
System.out.print( "Prime combinations: ");
if (isPrime(num) && isPrime(rev))
{
System.out.println(num + " " + rev);
}
else if (isPrime(num))
{
System.out.println(num);
}
else if (isPrime(rev))
{
System.out.println(rev);
}
else
{
System.out.println("No combinations exist");
}
}
114
Chapter 19. Check if the first and last digit of the smallest number forms a prime
// Driver code
public static void main (String[] args)
{
SmallPrime smallprime = new SmallPrime();
int arr[] = {1, 2, 4, 7, 8};
smallprime.findMinNum(arr, 5);
}
}
// This code has been contributed by inder_verma.
Output:
Improved By : inderDuMCA
Source
https://www.geeksforgeeks.org/check-if-the-first-and-last-digit-of-the-smallest-number-forms-a-prime/
115
Chapter 20
Input : N = 3, M = 2
Edges are:
1) 1-2
2) 2-3
P = {1, 2, 3}
Output : YES
Explanation :
Since there are edges between
1-2 and 2-3, therefore we can
have DFS in the order 1-2-3
Input : N = 3, M = 2
Edges are:
1) 1-2
2) 2-3
P = {1, 3, 2}
Output : NO
Explanation :
Since there is no edge between 1 and 3,
the DFS traversal is not possible
116
Chapter 20. Check if the given permutation is a valid DFS of graph
1. Store the indexes of each number in the given permutation in a Hash map.
2. Sort every adjacency list according to the indexes of permutation since there is need
to maintain the order.
3. Perform the Depth First Traversal Search with source node as 1st number of given
permutation.
4. Keep a counter variable and at every recursive call, check if the counter has reached
the number of nodes, i.e. N and set the flag as 1. If the flag is 0 after complete DFS,
answer is ‘NO’ otherwise ‘YES’
117
Chapter 20. Check if the given permutation is a valid DFS of graph
118
Chapter 20. Check if the given permutation is a valid DFS of graph
119
Chapter 20. Check if the given permutation is a valid DFS of graph
Output:
YES
Source
https://www.geeksforgeeks.org/check-given-permutation-valid-dfs-graph/
120
Chapter 21
Examples :
A simple solution is to sort both array and then linearly compare elements.
C/C++
121
Chapter 21. Check if two arrays are equal or not
Java
122
Chapter 21. Check if two arrays are equal or not
class GFG
{
// Returns true if arr1[0..n-1] and arr2[0..m-1]
// contain same elements.
public static boolean areEqual(int arr1[], int arr2[])
{
int n = arr1.length;
int m = arr2.length;
// If lengths of array are not equal means
// array are not equal
if (n != m)
return false;
// Sort both arrays
Arrays.sort(arr1);
Arrays.sort(arr2);
// Linearly compare elements
for (int i=0; i<n; i++)
if (arr1[i] != arr2[i])
return false;
// If all elements were same.
return true;
}
//Driver code
public static void main (String[] args)
{
int arr1[] = { 3, 5, 2, 5, 2};
int arr2[] = { 2, 3, 5, 5, 2};
if (areEqual(arr1, arr2))
System.out.println("Yes");
else
System.out.println("No");
}
}
C#
123
Chapter 21. Check if two arrays are equal or not
// Returns true if arr1[0..n-1] and
// arr2[0..m-1] contain same elements.
public static bool areEqual(int []arr1,
int []arr2)
{
int n = arr1.Length;
int m = arr2.Length;
// If lengths of array are not
// equal means array are not equal
if (n != m)
return false;
// Sort both arrays
Array.Sort(arr1);
Array.Sort(arr2);
// Linearly compare elements
for (int i = 0; i < n; i++)
if (arr1[i] != arr2[i])
return false;
// If all elements were same.
return true;
}
// Driver code
public static void Main ()
{
int []arr1 = { 3, 5, 2, 5, 2};
int []arr2 = { 2, 3, 5, 5, 2};
if (areEqual(arr1, arr2))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find given
// two array are equal or not
124
Chapter 21. Check if two arrays are equal or not
Output :
Yes
An Efficient solution of this approach is to use hashing. We store all elements of arr1[]
and their counts in a hash table. Then we traverse arr2[] and check if count of every element
in arr2[] matches with count in arr1[].
125
Chapter 21. Check if two arrays are equal or not
C/C++
126
Chapter 21. Check if two arrays are equal or not
Java
127
Chapter 21. Check if two arrays are equal or not
Output :
Yes
128
Chapter 21. Check if two arrays are equal or not
Source
https://www.geeksforgeeks.org/check-if-two-arrays-are-equal-or-not/
129
Chapter 22
Examples :
Below is a solution to check if two strings are k-anagrams of each other or not.
130
Chapter 22. Check if two strings are k-anagrams or not
2. Count number of different characters in both strings (in this if a strings has 4 a and
second has 3 ‘a’ then it will be also count.
3. If count of different characters is less than or equal to k, then return true else false.
C++
131
Chapter 22. Check if two strings are k-anagrams or not
Java
132
Chapter 22. Check if two strings are k-anagrams or not
}
// Driver code
public static void main(String args[])
{
String str1 = "anagram";
String str2 = "grammar";
int k = 2;
if (arekAnagrams(str1, str2, k))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Sumit Ghosh
C#
133
Chapter 22. Check if two strings are k-anagrams or not
count2[str2[i] - 'a']++;
// Count number of characters that are
// different in both strings
for (int i = 0; i < MAX_CHAR; i++)
if (count1[i] > count2[i])
count = count + Math.Abs(count1[i] -
count2[i]);
// Return true if count is
// less than or equal to k
return (count <= k);
}
// Driver code
public static void Main()
{
string str1 = "anagram";
string str2 = "grammar";
int k = 2;
if (arekAnagrams(str1, str2, k))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to check
// if two strings are
// k anagram or not.
$MAX_CHAR = 26;
// Function to check that
// string is k-anagram or not
function arekAnagrams($str1, $str2, $k)
{
global $MAX_CHAR;
// If both strings are not of
// equal length then return false
$n = strlen($str1);
if (strlen($str2) != $n)
return false;
$count1 = (0);
134
Chapter 22. Check if two strings are k-anagrams or not
$count2 = (0);
// Store the occurrence of all
// characters in a hash_array
$count = 0;
// Count number of characters that
// are different in both strings
for ($i = 0; $i < $MAX_CHAR; $i++)
if ($count1[$i] > $count2[$i])
$count = $count + abs($count1[$i] -
$count2[$i]);
// Return true if count is
// less than or equal to k
return ($count <= $k);
}
// Driver Code
$str1 = "anagram";
$str2 = "grammar";
$k = 2;
if (arekAnagrams($str1, $str2, $k))
echo "Yes";
else
echo "No";
// This code is contributed by m_kit
?>
Output :
Yes
We can optimize above solution. Here we use only one count array to store counts of
characters in str1. We traverse str2 and decrement occurrence of every character in count
array that is present in str2. If we find a character that is not there in str1, we increment
count of different characters. If count of different character become more than k, we return
false.
C++
135
Chapter 22. Check if two strings are k-anagrams or not
136
Chapter 22. Check if two strings are k-anagrams or not
return 0;
}
Java
137
Chapter 22. Check if two strings are k-anagrams or not
C#
138
Chapter 22. Check if two strings are k-anagrams or not
hash_str1[str2[i]-'a']--;
else
count++;
if (count > k)
return false;
}
// Return true if count is less than or
// equal to k
return true;
}
// Driver code
static void Main()
{
String str1 = "fodr";
String str2 = "gork";
int k = 2;
if (areKAnagrams(str1, str2, k) == true)
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Anuj_67
PHP
<?php
// Optimized PHP program
// to check if two strings
// are k anagram or not.
$MAX_CHAR = 26;
// Function to check if str1
// and str2 are k-anagram or not
function areKAnagrams($str1,
$str2, $k)
{
global $MAX_CHAR;
// If both strings are
// not of equal length
// then return false
$n = strlen($str1);
if (strlen($str2) != $n)
139
Chapter 22. Check if two strings are k-anagrams or not
return false;
$hash_str1 = array(0);
// Store the occurrence of
// all characters in a hash_array
for ($i = 0; $i < $n ; $i++)
$hash_str1[$str1[$i] - 'a']++;
// Store the occurrence of all
// characters in a hash_array
$count = 0;
for ($i = 0; $i < $n ; $i++)
{
if ($hash_str1[$str2[$i] - 'a'] > 0)
$hash_str1[$str2[$i] - 'a']--;
else
$count++;
if ($count > $k)
return false;
}
// Return true if count is
// less than or equal to k
return true;
}
// Driver code
$str1 = "fodr";
$str2 = "gork";
$k = 2;
if (areKAnagrams($str1, $str2, $k) == true)
echo "Yes";
else
echo "No";
// This code is contributed by ajit
?>
Output:
Yes
140
Chapter 22. Check if two strings are k-anagrams or not
Source
https://www.geeksforgeeks.org/check-two-strings-k-anagrams-not/
141
Chapter 23
Check whether Arithmetic Progression can be formed from the given array - GeeksforGeeks
Given an array of n integers. The task is to check whether an arithmetic progression can
be formed using all the given elements. If possible print “Yes”, else print “No”.
Examples:
Method 1 (Simple)
A simple solution is to first find the smallest element, then find second smallest element and
find the difference between these two. Let this difference be d. After finding the difference,
find third smallest, fourth smallest and so on. After finding every i-th smallest smallest (from
third onward), find the difference between value of current element and value of previous
element. If difference is not same as d, return false. If all elements have same difference,
return true. Time complexity of this solution is O(n2 )
Method 2(Use Sorting)
The idea is to sort the given array. After sorting, check if differences between consecutive
elements are same or not. If all differences are same, Arithmetic Progression is possible.
142
Chapter 23. Check whether Arithmetic Progression can be formed from the given array
C++
Java
143
Chapter 23. Check whether Arithmetic Progression can be formed from the given array
class GFG {
// Returns true if a permutation of
// arr[0..n-1] can form arithmetic
// progression
static boolean checkIsAP(int arr[], int n)
{
if (n == 1)
return true;
// Sort array
Arrays.sort(arr);
// After sorting, difference between
// consecutive elements must be same.
int d = arr[1] - arr[0];
for (int i = 2; i < n; i++)
if (arr[i] - arr[i-1] != d)
return false;
return true;
}
//driver code
public static void main (String[] args)
{
int arr[] = { 20, 15, 5, 0, 10 };
int n = arr.length;
if(checkIsAP(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Anant Agarwal.
Python3
144
Chapter 23. Check whether Arithmetic Progression can be formed from the given array
C#
145
Chapter 23. Check whether Arithmetic Progression can be formed from the given array
//Driver Code
public static void Main ()
{
int []arr = {20, 15, 5, 0, 10};
int n = arr.Length;
if(checkIsAP(arr, n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to check if
// a given array can form
// arithmetic progression
// Returns true if a permutation
// of arr[0..n-1] can form
// arithmetic progression
function checkIsAP($arr, $n)
{
if ($n == 1)
return true;
// Sort array
sort($arr);
// After sorting, difference
// between consecutive elements
// must be same.
$d = $arr[1] - $arr[0];
for ($i = 2; $i < $n; $i++)
if ($arr[$i] -
$arr[$i - 1] != $d)
return false;
return true;
}
// Driver Code
$arr = array(20, 15, 5, 0, 10);
$n = count($arr);
146
Chapter 23. Check whether Arithmetic Progression can be formed from the given array
if(checkIsAP($arr, $n))
echo "Yes";
else
echo "No";
// This code is contributed
// by Sam007
?>
Output:
Yes
147
Chapter 23. Check whether Arithmetic Progression can be formed from the given array
Source
https://www.geeksforgeeks.org/check-whether-arithmetic-progression-can-formed-given-array/
148
Chapter 24
Input : 8
/ \
5 9
/ \
2 7
/
1
Output : Yes
Explanation : Node "1" is the dead End because
after that we cant insert any element.
Input : 8
/ \
7 10
/ / \
2 9 13
Output : Yes
Explanation : We can't insert any element at
node 9.
149
Chapter 24. Check whether BST contains Dead End or not
If we take a closer look at problem, we can notice that we basically need to check if there is
leaf node with value x such that x+1 and x-1 exist in BST with exception of x = 1. For x
= 1, we can’t insert 0 as problem statement says BST contains positive integers only.
To implement above idea we first traverse whole BST and store all nodes in a hash_map.
We also store all leaves in a separate hash to avoid re-traversal of BST. Finally we check for
every leaf node x, if x-1 and x+1 are present in hash_map or not.
Below is C++ implementation of above idea .
150
Chapter 24. Check whether BST contains Dead End or not
151
Chapter 24. Check whether BST contains Dead End or not
Output:
Yes
Source
https://www.geeksforgeeks.org/check-whether-bst-contains-dead-end-not/
152
Chapter 25
struct node {
int key;
struct node *left,*right,*random;
}
The random pointer points to any random node of the binary tree and can even point to
NULL, clone the given binary tree.
Method 1 (Use Hashing)
The idea is to store mapping from given tree nodes to clone tre node in hashtable. Following
are detailed steps.
1) Recursively traverse the given Binary and copy key value, left pointer and right pointer
to clone tree. While copying, store the mapping from given tree node to clone tree node
in a hashtable. In the following pseudo code, ‘cloneNode’ is currently visited node of clone
tree and ‘treeNode’ is currently visited node of given tree.
cloneNode->key = treeNode->key
cloneNode->left = treeNode->left
cloneNode->right = treeNode->right
map[treeNode] = cloneNode
2) Recursively traverse both trees and set random pointers using entries from hash table.
153
Chapter 25. Clone a Binary Tree with Random Pointers
cloneNode->random = map[treeNode->random]
// A hashmap based C++ program to clone a binary tree with random pointers
#include<iostream>
#include<map>
using namespace std;
/* A binary tree node has data, pointer to left child, a pointer to right
child and a pointer to random node*/
struct Node
{
int key;
struct Node* left, *right, *random;
};
/* Helper function that allocates a new Node with the
given data and NULL left, right and random pointers. */
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->random = temp->right = temp->left = NULL;
return (temp);
}
/* Given a binary tree, print its Nodes in inorder*/
void printInorder(Node* node)
{
if (node == NULL)
return;
/* First recur on left sutree */
printInorder(node->left);
/* then print data of Node and its random */
cout << "[" << node->key << " ";
if (node->random == NULL)
cout << "NULL], ";
else
cout << node->random->key << "], ";
/* now recur on right subtree */
printInorder(node->right);
154
Chapter 25. Clone a Binary Tree with Random Pointers
}
// This function creates clone by copying key and left and right pointers
// This function also stores mapping from given tree node to clone.
Node* copyLeftRightNode(Node* treeNode, map<Node *, Node *> *mymap)
{
if (treeNode == NULL)
return NULL;
Node* cloneNode = newNode(treeNode->key);
(*mymap)[treeNode] = cloneNode;
cloneNode->left = copyLeftRightNode(treeNode->left, mymap);
cloneNode->right = copyLeftRightNode(treeNode->right, mymap);
return cloneNode;
}
// This function copies random node by using the hashmap built by
// copyLeftRightNode()
void copyRandom(Node* treeNode, Node* cloneNode, map<Node *, Node *> *mymap)
{
if (cloneNode == NULL)
return;
cloneNode->random = (*mymap)[treeNode->random];
copyRandom(treeNode->left, cloneNode->left, mymap);
copyRandom(treeNode->right, cloneNode->right, mymap);
}
// This function makes the clone of given tree. It mainly uses
// copyLeftRightNode() and copyRandom()
Node* cloneTree(Node* tree)
{
if (tree == NULL)
return NULL;
map<Node *, Node *> *mymap = new map<Node *, Node *>;
Node* newTree = copyLeftRightNode(tree, mymap);
copyRandom(tree, newTree, mymap);
return newTree;
}
/* Driver program to test above functions*/
int main()
{
//Test No 1
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->left->left = newNode(4);
tree->left->right = newNode(5);
tree->random = tree->left->right;
155
Chapter 25. Clone a Binary Tree with Random Pointers
tree->left->left->random = tree;
tree->left->right->random = tree->right;
// Test No 2
// tree = NULL;
// Test No 3
// tree = newNode(1);
// Test No 4
/* tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->random = tree->right;
tree->left->random = tree;
*/
cout << "Inorder traversal of original binary tree is: \n";
printInorder(tree);
Node *clone = cloneTree(tree);
cout << "\n\nInorder traversal of cloned binary tree is: \n";
printInorder(clone);
return 0;
}
Output:
156
Chapter 25. Clone a Binary Tree with Random Pointers
#include <iostream>
using namespace std;
/* A binary tree node has data, pointer to left child, a pointer to right
child and a pointer to random node*/
struct Node
{
int key;
struct Node* left, *right, *random;
};
/* Helper function that allocates a new Node with the
given data and NULL left, right and random pointers. */
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->random = temp->right = temp->left = NULL;
return (temp);
}
/* Given a binary tree, print its Nodes in inorder*/
void printInorder(Node* node)
{
if (node == NULL)
return;
/* First recur on left sutree */
printInorder(node->left);
157
Chapter 25. Clone a Binary Tree with Random Pointers
/* then print data of Node and its random */
cout << "[" << node->key << " ";
if (node->random == NULL)
cout << "NULL], ";
else
cout << node->random->key << "], ";
/* now recur on right subtree */
printInorder(node->right);
}
// This function creates new nodes cloned tree and puts new cloned node
// in between current node and it's left child
// i.e. if current node is A and it's left child is B ( A --- >> B ),
// then new cloned node with key A wil be created (say cA) and
// it will be put as
// A --- >> cA --- >> B
// Here B can be a NULL or a non-NULL left child
// Right child pointer will be set correctly
// i.e. if for current node A, right child is C in original tree
// (A --- >> C) then corresponding cloned nodes cA and cC will like
// cA ---- >> cC
Node* copyLeftRightNode(Node* treeNode)
{
if (treeNode == NULL)
return NULL;
Node* left = treeNode->left;
treeNode->left = newNode(treeNode->key);
treeNode->left->left = left;
if(left != NULL)
left->left = copyLeftRightNode(left);
treeNode->left->right = copyLeftRightNode(treeNode->right);
return treeNode->left;
}
// This function sets random pointer in cloned tree as per original tree
// i.e. if node A's random pointer points to node B, then
// in cloned tree, cA wil point to cB (cA and cB are new node in cloned
// tree corresponding to node A and B in original tree)
void copyRandomNode(Node* treeNode, Node* cloneNode)
{
if (treeNode == NULL)
return;
if(treeNode->random != NULL)
cloneNode->random = treeNode->random->left;
158
Chapter 25. Clone a Binary Tree with Random Pointers
else
cloneNode->random = NULL;
if(treeNode->left != NULL && cloneNode->left != NULL)
copyRandomNode(treeNode->left->left, cloneNode->left->left);
copyRandomNode(treeNode->right, cloneNode->right);
}
// This function will restore left pointers correctly in
// both original and cloned tree
void restoreTreeLeftNode(Node* treeNode, Node* cloneNode)
{
if (treeNode == NULL)
return;
if (cloneNode->left != NULL)
{
Node* cloneLeft = cloneNode->left->left;
treeNode->left = treeNode->left->left;
cloneNode->left = cloneLeft;
}
else
treeNode->left = NULL;
restoreTreeLeftNode(treeNode->left, cloneNode->left);
restoreTreeLeftNode(treeNode->right, cloneNode->right);
}
//This function makes the clone of given tree
Node* cloneTree(Node* treeNode)
{
if (treeNode == NULL)
return NULL;
Node* cloneNode = copyLeftRightNode(treeNode);
copyRandomNode(treeNode, cloneNode);
restoreTreeLeftNode(treeNode, cloneNode);
return cloneNode;
}
/* Driver program to test above functions*/
int main()
{
/* //Test No 1
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->left->left = newNode(4);
tree->left->right = newNode(5);
159
Chapter 25. Clone a Binary Tree with Random Pointers
tree->random = tree->left->right;
tree->left->left->random = tree;
tree->left->right->random = tree->right;
// Test No 2
// Node *tree = NULL;
/*
// Test No 3
Node *tree = newNode(1);
// Test No 4
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->random = tree->right;
tree->left->random = tree;
Test No 5
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->left->left = newNode(4);
tree->left->right = newNode(5);
tree->right->left = newNode(6);
tree->right->right = newNode(7);
tree->random = tree->left;
*/
// Test No 6
Node *tree = newNode(10);
Node *n2 = newNode(6);
Node *n3 = newNode(12);
Node *n4 = newNode(5);
Node *n5 = newNode(8);
Node *n6 = newNode(11);
Node *n7 = newNode(13);
Node *n8 = newNode(7);
Node *n9 = newNode(9);
tree->left = n2;
tree->right = n3;
tree->random = n2;
n2->left = n4;
n2->right = n5;
n2->random = n8;
n3->left = n6;
n3->right = n7;
n3->random = n5;
n4->random = n9;
n5->left = n8;
160
Chapter 25. Clone a Binary Tree with Random Pointers
n5->right = n9;
n5->random = tree;
n6->random = n9;
n9->random = n8;
/* Test No 7
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->left->random = tree;
tree->right->random = tree->left;
*/
cout << "Inorder traversal of original binary tree is: \n";
printInorder(tree);
Node *clone = cloneTree(tree);
cout << "\n\nInorder traversal of cloned binary tree is: \n";
printInorder(clone);
return 0;
}
Output:
This article is contributed by Anurag Singh. 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/clone-binary-tree-random-pointers/
161
Chapter 26
Coalesced hashing
1. INSERT(key): The insert Operation inserts the key according to the hash value of
that key if that hash value in the table is empty otherwise the key is inserted in first
empty place from the bottom of the hash table and the address of this empty place
is mapped in NEXT field of the previous pointing node of the chain.(Explained in
example below).
2. DELETE(Key): The key if present is deleted.Also if the node to be deleted contains
the address of another node in hash table then this address is mapped in the NEXT
field of the node pointing to the node which is to be deleted
3. SEARCH(key): Returns True if key is present, otherwise return False.
The best case complexity of all these operations is O(1) and the worst case complexity is
O(n) where n is the total number of keys.It is better than separate chaining because it
inserts the colliding element in the memory of hash table only instead of creating a new
linked list as in separate chaining.
Illustration:
Example:
162
Chapter 26. Coalesced hashing
n = 10
Input : {20, 35, 16, 40, 45, 25, 32, 37, 22, 55}
Hash function
h(key) = key%10
Steps:
1. Initially empty hash table is created with all NEXT field initialised with NULL and
h(key) values ranging from 0-9.
2. Let’s start with inserting 20, as h(20)=0 and 0 index is empty so we insert 20 at 0
index.
3. Next element to be inserted is 35, h(35)=5 and 5th index empty so we insert 35 there.
4. Next we have 16, h(16)=6 which is empty so 16 is inserted at 6 index value.
5. Now we have to insert 40, h(40)=0 which is already occupied so we search for the first
empty block from the bottom and insert it there i.e 9 index value.Also the address
of this newly inserted node(from address we mean index value of a node) i.e(9 )is
initialised in the next field of 0th index value node.
6. To insert 45, h(45)=5 which is occupied so again we search for the empty block from
the bottom i.e 8 index value and map the address of this newly inserted node i.e(8) to
the Next field of 5th index value node i.e in the next field of key=35.
7. Next to insert 25, h(25)=5 is occupied so search for the first empty block from bottom
i.e 7th index value and insert 25 there. Now it is important to note that the address
of this new node cant be mapped on 5th index value node which is already pointing to
some other node. To insert the address of new node we have to follow the link chain
from the 5th index node until we get NULL in next field and map the address of new
node to next field of that node i.e from 5th index node we go to 8th index node which
contains NULL in next field so we insert address of new node i.e(7) in next field of
8th index node.
8. To insert 32, h(32)=2, which is empty so insert 32 at 2nd index value.
9. To insert 37, h(37)=7 which is occupied so search for the first free block from bottom
which is 4th index value. So insert 37 at 4th index value and copy the address of this
node in next field of 7th index value node.
10. To insert 22, h(22)=2 which is occupied so insert it at 3rd index value and map the
address of this node in next field of 2nd index value node.
11. Finally, to insert 55 h(55)=5 which is occupied and the only empty space is 1st index
value so insert 55 there. Now again to map the address of this new node we have to
follow the chain starting from 5th index value node until we get NULL in next field
i.e from 5th index->8th index->7th index->4th index which contains NULL in Next
fied, and we insert the address of newly inserted node at 4th index value node.
163
Chapter 26. Coalesced hashing
Case 2: If key to be deleted is 35 which is not pointed by any other node then we have to
pull the chain attached to the node to be deleted i.e 35 one step back and mark last value
of chain to NULL again.
164
Chapter 26. Coalesced hashing
Source
https://www.geeksforgeeks.org/coalesced-hashing/
165
Chapter 27
Input:
mat[4][5] = {{1, 2, 1, 4, 8},
{3, 7, 8, 5, 1},
{8, 7, 7, 3, 1},
{8, 1, 2, 7, 9},
};
Output:
1 8 or 8 1
8 and 1 are present in all rows.
A simple solution is to consider every element and check if it is present in all rows. If
present, then print it.
A better solution is to sort all rows in the matrix and use similar approach as discussed
here. Sorting will take O(mnlogn) time and finding common elements will take O(mn) time.
So overall time complexity of this solution is O(mnlogn)
Can we do better than O(mnlogn)?
The idea is to use maps. We initially insert all elements of the first row in an map. For
every other element in remaining rows, we check if it is present in the map. If it is present
166
Chapter 27. Common elements in all rows of a given matrix
in the map and is not duplicated in current row, we increment count of the element in map
by 1, else we ignore the element. If the currently traversed row is the last row, we print the
element if it has appeared m-1 times before.
Below is C++ implementation of the idea.
167
Chapter 27. Common elements in all rows of a given matrix
int mat[M][N] =
{
{1, 2, 1, 4, 8},
{3, 7, 8, 5, 1},
{8, 7, 7, 3, 1},
{8, 1, 2, 7, 9},
};
printCommonElements(mat);
return 0;
}
Output:
8 1
The time complexity of this solution is O(m * n) and we are doing only one traversal of the
matrix.
Source
https://www.geeksforgeeks.org/common-elements-in-all-rows-of-a-given-matrix/
168
Chapter 28
Input : S1 = "aacdb"
S2 = "gafd"
Output : "cbgf"
Input : S1 = "abcs";
S2 = "cxzca";
Output : "bsxz"
The idea is to use hash map where key is character and value is number of strings in which
character is present. If a character is present in one string, then count is 1, else if character
is present in both strings, count is 2.
169
Chapter 28. Concatenated string with uncommon characters of two strings
Output:
bsxz
Asked In : Microsoft
170
Chapter 28. Concatenated string with uncommon characters of two strings
Source
https://www.geeksforgeeks.org/concatenated-string-uncommon-characters-two-strings/
171
Chapter 29
Input :
in[] = {2, 1, 3}
post[] = {2, 3, 1}
Input :
in[] = {4, 8, 2, 5, 1, 6, 3, 7}
post[] = {8, 4, 5, 2, 6, 7, 3, 1}
172
Chapter 29. Construct a Binary Tree from Postorder and Inorder
We have already discussed construction of tree from iven Inorder and Preorder traversals.
The idea is similar.
Let us see the process of constructing tree from in[] = {4, 8, 2, 5, 1, 6, 3, 7} and post[] =
{8, 4, 5, 2, 6, 7, 3, 1}
1) We first find the last node in post[]. The last node is “1”, we know this value is root as
root always appear in the end of postorder traversal.
2) We search “1” in in[] to find left and right subtrees of root. Everything on left of “1” in
in[] is in left subtree and everything on right is in right subtree.
1
/ \
[4, 8, 2, 5] [6, 3, 7]
C++
173
Chapter 29. Construct a Binary Tree from Postorder and Inorder
174
Chapter 29. Construct a Binary Tree from Postorder and Inorder
}
return i;
}
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
/* This funtcion is here just to test */
void preOrder(Node* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
// Driver code
int main()
{
int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
int n = sizeof(in) / sizeof(in[0]);
Node* root = buildTree(in, post, n);
cout << "Preorder of the constructed tree : \n";
preOrder(root);
return 0;
}
Java
175
Chapter 29. Construct a Binary Tree from Postorder and Inorder
public Node(int data)
{
this.data = data;
left = right = null;
}
}
// Class Index created to implement pass by reference of Index
class Index {
int index;
}
class BinaryTree {
/* Recursive function to construct binary of size n
from Inorder traversal in[] and Postrder traversal
post[]. Initial values of inStrt and inEnd should
be 0 and n -1. The function doesn't do any error
checking for cases where inorder and postorder
do not form a tree */
Node buildUtil(int in[], int post[], int inStrt,
int inEnd, Index pIndex)
{
// Base case
if (inStrt > inEnd)
return null;
/* Pick current node from Postrder traversal using
postIndex and decrement postIndex */
Node node = new Node(post[pIndex.index]);
(pIndex.index)--;
/* If this node has no children then return */
if (inStrt == inEnd)
return node;
/* Else find the index of this node in Inorder
traversal */
int iIndex = search(in, inStrt, inEnd, node.data);
/* Using index in Inorder traversal, construct left and
right subtress */
node.right = buildUtil(in, post, iIndex + 1, inEnd, pIndex);
node.left = buildUtil(in, post, inStrt, iIndex - 1, pIndex);
return node;
}
176
Chapter 29. Construct a Binary Tree from Postorder and Inorder
Output :
177
Chapter 29. Construct a Binary Tree from Postorder and Inorder
178
Chapter 29. Construct a Binary Tree from Postorder and Inorder
traversal */
int iIndex = mp[curr];
/* Using index in Inorder traversal, construct
left and right subtress */
node->right = buildUtil(in, post, iIndex + 1,
inEnd, pIndex, mp);
node->left = buildUtil(in, post, inStrt,
iIndex - 1, pIndex, mp);
return node;
}
// This function mainly creates an unordered_map, then
// calls buildTreeUtil()
struct Node* buildTree(int in[], int post[], int len)
{
// Store indexes of all items so that we
// we can quickly find later
unordered_map<int, int> mp;
for (int i = 0; i < len; i++)
mp[in[i]] = i;
int index = len - 1; // Index in postorder
return buildUtil(in, post, 0, len - 1,
&index, mp);
}
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
/* This funtcion is here just to test */
void preOrder(Node* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
// Driver code
179
Chapter 29. Construct a Binary Tree from Postorder and Inorder
int main()
{
int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
int n = sizeof(in) / sizeof(in[0]);
Node* root = buildTree(in, post, n);
cout << "Preorder of the constructed tree : \n";
preOrder(root);
return 0;
}
Source
https://www.geeksforgeeks.org/construct-a-binary-tree-from-postorder-and-inorder/
Time Complexity : O(n)
This article is contributed by Rishi. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
180
Chapter 30
Construct a tree from Inorder and Level order traversals | Set 2 - GeeksforGeeks
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Fol-
lowing is an example to illustrate the problem.
Examples:
181
Chapter 30. Construct a tree from Inorder and Level order traversals | Set 2
If it is the part of left subtree then add in one lLevel arrray for left other wise add it to
rLevel array for right subtree.
Below is the c++ implementation with the above idea
182
Chapter 30. Construct a tree from Inorder and Level order traversals | Set 2
// Separate level order traversals
// of left and right subtrees.
int lLevel[s.size()]; // Left
int rLevel[iEnd-iStart-s.size()]; // Right
int li = 0, ri = 0;
for (int i=1;i<n;i++) {
if (s.find(levelOrder[i]) != s.end())
lLevel[li++] = levelOrder[i];
else
rLevel[ri++] = levelOrder[i];
}
// Recursively build left and right
// subtrees and return root.
root->left = buildTree(inorder, lLevel,
iStart, index-1, index-iStart);
root->right = buildTree(inorder, rLevel,
index+1, iEnd, iEnd-index);
return root;
}
/* Utility function to print inorder
traversal of binary tree */
void printInorder(Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->key << " ";
printInorder(node->right);
}
// Driver Code
int main()
{
int in[] = {4, 8, 10, 12, 14, 20, 22};
int level[] = {20, 8, 22, 4, 12, 10, 14};
int n = sizeof(in)/sizeof(in[0]);
Node *root = buildTree(in, level, 0,
n - 1, n);
/* Let us test the built tree by
printing Insorder traversal */
cout << "Inorder traversal of the "
"constructed tree is \n";
printInorder(root);
183
Chapter 30. Construct a tree from Inorder and Level order traversals | Set 2
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/construct-tree-inorder-level-order-traversals-set-2/
184
Chapter 31
Convert a sentence into its equivalent mobile numeric keypad sequence - GeeksforGeeks
Given a sentence in the form of a string, convert it into its equivalent mobile numeric keypad
sequence.
Examples :
185
Chapter 31. Convert a sentence into its equivalent mobile numeric keypad sequence
Input : GEEKSFORGEEKS
Output : 4333355777733366677743333557777
For obtaining a number, we need to press a
number corresponding to that character for
number of times equal to position of the
character. For example, for character C,
we press number 2 three times and accordingly.
Follow the steps given below to convert a sentence into its equivalent mobile numeric keypad
sequence.
• For each character, store the sequence which should be obtained at its respective
position in an array, i.e. for Z, store 9999. For Y, store 999. For K, store 55 and so
on.
• For each character, subtract ASCII value of ‘A’ and obtain the position in the array
pointed
by that character and add the sequence stored in that array to a string.
• If the character is a space, store 0
• Print the overall sequence.
C++
186
Chapter 31. Convert a sentence into its equivalent mobile numeric keypad sequence
else
{
// Calculating index for each
// character
int position = input[i]-'A';
output = output + arr[position];
}
}
// Output sequence
return output;
}
// Driver function
int main()
{
// storing the sequence in array
string str[] = {"2","22","222",
"3","33","333",
"4","44","444",
"5","55","555",
"6","66","666",
"7","77","777","7777",
"8","88","888",
"9","99","999","9999"
};
string input = "GEEKSFORGEEKS";
cout << printSequence(str, input);
return 0;
}
Java
187
Chapter 31. Convert a sentence into its equivalent mobile numeric keypad sequence
// length of input string
int n = input.length();
for (int i = 0; i < n; i++)
{
// Checking for space
if (input.charAt(i) == ' ')
output = output + "0";
else
{
// Calculating index for each
// character
int position = input.charAt(i) - 'A';
output = output + arr[position];
}
}
// Output sequence
return output;
}
// Driver Function
public static void main(String[] args)
{
// storing the sequence in array
String str[] = {"2","22","222",
"3","33","333",
"4","44","444",
"5","55","555",
"6","66","666",
"7","77","777","7777",
"8","88","888",
"9","99","999","9999"
};
String input = "GEEKSFORGEEKS";
System.out.println(printSequence(str, input));
}
}
// This code is contributed by Gitanjali.
Python3
188
Chapter 31. Convert a sentence into its equivalent mobile numeric keypad sequence
# Function which computes the
# sequence
def printSequence(arr, input):
# length of input string
n = len(input)
output = ""
for i in range(n):
# checking for space
if(input[i] == ' '):
output = output + "0"
else:
# calculating index for each
# character
position = ord(input[i]) - ord('A')
output = output + arr[position]
# output sequence
return output
# Driver code
str = ["2", "22", "222",
"3", "33", "333",
"4", "44", "444",
"5", "55", "555",
"6", "66", "666",
"7", "77", "777", "7777",
"8", "88", "888",
"9", "99", "999", "9999" ]
input = "GEEKSFORGEEKS";
print( printSequence(str, input))
# This code is contributed by upendra bartwal
C#
// C# implementation to convert a
// sentence into its equivalent
// mobile numeric keypad sequence
using System;
class GFG
{
// Function which computes the sequence
189
Chapter 31. Convert a sentence into its equivalent mobile numeric keypad sequence
Output :
190
Chapter 31. Convert a sentence into its equivalent mobile numeric keypad sequence
4333355777733366677743333557777
Source
https://www.geeksforgeeks.org/convert-sentence-equivalent-mobile-numeric-keypad-sequence/
191
Chapter 32
192
Chapter 32. Convert an array to reduced form | Set 1 (Simple and Hashing)
5) Traverse given array and change elements to their positions using hash table. This takes
O(n) time on average.
Overall time complexity of this solution is O(n Log n).
Below are implementations of above idea.
C++
193
Chapter 32. Convert an array to reduced form | Set 1 (Simple and Hashing)
{
int arr[] = {10, 20, 15, 12, 11, 50};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Given Array is \n";
printArr(arr, n);
convert(arr , n);
cout << "\n\nConverted Array is \n";
printArr(arr, n);
return 0;
}
Java
194
Chapter 32. Convert an array to reduced form | Set 1 (Simple and Hashing)
Python3
195
Chapter 32. Convert an array to reduced form | Set 1 (Simple and Hashing)
val += 1
# Convert array by taking positions from umap
for i in range (n):
arr[i] = umap[arr[i]]
def printArr(arr, n):
for i in range(n):
print(arr[i], end = " ")
# Driver Code
if __name__ == "__main__":
arr = [10, 20, 15, 12, 11, 50]
n = len(arr)
print("Given Array is ")
printArr(arr, n)
convert(arr , n)
print("\n\nConverted Array is ")
printArr(arr, n)
# This code is contributed by Abhishek Gupta
Output :
Given Array is
10 20 15 12 11 50
Converted Array is
0 4 3 2 1 5
Source
https://www.geeksforgeeks.org/convert-an-array-to-reduced-form-set-1-simple-and-hashing/
196
Chapter 33
197
Chapter 33. Convert to a string that is repetition of a substring of k length
This can be used in compression. If we have a string where complete string is repetition
except one substring, then we can use this algorithm to compress the string.
One observation is, length of string must be a multiple of k as we can replace only one
substring.
The idea is declare a map mp which maps strings of length k to an integer denoting its
count. So, if there are only two different sub-strings of length k in the map container and
count of one of the sub-string is 1 then answer is true. Otherwise answer is false.
198
Chapter 33. Convert to a string that is repetition of a substring of k length
// Driver code
int main()
{
checkString("abababcd", 2)? cout << "Yes" :
cout << "No";
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/convert-string-repetition-substring-k-length/
199
Chapter 34
A simple solution is to iterate through all substring of str and checking whether they
contain equal 0,1 and 2 or not. Total number of substring of str is O(n2 ) checking each
substring for count takes O(n) times, So total time taken to solve this problem is O(n3 )
time with brute-force approach.
An efficient solution is to keep track of counts of 0, 1 and 2.
200
Chapter 34. Count Substrings with equal number of 0s, 1s and 2s
The above relations can be tracked while looping in string, at each index i we’ll calculate this
difference pair and we’ll check how many time this difference pair has previously occurred
and we’ll add that count to our result, for keeping track of previous difference pair we have
used map in below code. Total time complexity of this solution is O(n log n) considering
the fact that map operations, like search and insert take O(Log n) time.
201
Chapter 34. Count Substrings with equal number of 0s, 1s and 2s
Output:
Source
https://www.geeksforgeeks.org/substring-equal-number-0-1-2/
202
Chapter 35
Method 1 (Simple)
A simple solution is to consider all pairs one by one and check difference between every pair.
Following program implements the simple solution. We run two loops: the outer loop picks
the first element of pair, the inner loop looks for the other element. This solution doesn’t
work if there are duplicates in array as the requirement is to count only distinct pairs.
C++
203
Chapter 35. Count all distinct pairs with difference equal to k
{
int count = 0;
// Pick all elements one by one
for (int i = 0; i < n; i++)
{
// See if there is a pair of this picked element
for (int j = i+1; j < n; j++)
if (arr[i] - arr[j] == k || arr[j] - arr[i] == k )
count++;
}
return count;
}
// Driver program to test above function
int main()
{
int arr[] = {1, 5, 3, 4, 2};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
cout << "Count of pairs with given diff is "
<< countPairsWithDiffK(arr, n, k);
return 0;
}
Java
204
Chapter 35. Count all distinct pairs with difference equal to k
}
return count;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 5, 3, 4, 2 };
int n = arr.length;
int k = 3;
System.out.println("Count of pairs with given diff is "
+ countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed
// by Sahil_Bansall
Python3
C#
205
Chapter 35. Count all distinct pairs with difference equal to k
// difference k
using System;
class GFG {
static int countPairsWithDiffK(int []arr,
int n, int k)
{
int count = 0;
// Pick all elements one by one
for (int i = 0; i < n; i++)
{
// See if there is a pair
// of this picked element
for (int j = i + 1; j < n; j++)
if (arr[i] - arr[j] == k ||
arr[j] - arr[i] == k)
count++;
}
return count;
}
// Driver code
public static void Main()
{
int []arr = { 1, 5, 3, 4, 2 };
int n = arr.Length;
int k = 3;
Console.WriteLine("Count of pairs with "
+ " given diff is "
+ countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed by Sam007.
PHP
<?php
// A simple PHP program to count
// pairs with difference k
function countPairsWithDiffK($arr, $n,
$k)
206
Chapter 35. Count all distinct pairs with difference equal to k
{
$count = 0;
// Pick all elements one by one
for($i = 0; $i < $n; $i++)
{
// See if there is a pair of
// this picked element
for($j = $i + 1; $j < $n; $j++)
if ($arr[$i] - $arr[$j] == $k or
$arr[$j] - $arr[$i] == $k)
$count++;
}
return $count;
}
// Driver Code
$arr = array(1, 5, 3, 4, 2);
$n = count($arr);
$k = 3;
echo "Count of pairs with given diff is "
, countPairsWithDiffK($arr, $n, $k);
// This code is contributed by anuj_67.
?>
Output :
1) Initialize count as 0
2) Sort all numbers in increasing order.
3) Remove duplicates from array.
4) Do following for each element arr[i]
a) Binary Search for arr[i] + k in subarray from i+1 to n-1.
b) If arr[i] + k found, increment count.
5) Return count.
207
Chapter 35. Count all distinct pairs with difference equal to k
C++
208
Chapter 35. Count all distinct pairs with difference equal to k
Java
209
Chapter 35. Count all distinct pairs with difference equal to k
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 5, 3, 4, 2 };
int n = arr.length;
int k = 3;
System.out.println("Count of pairs with given diff is "
+ countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed by Sahil_Bansall
Python
210
Chapter 35. Count all distinct pairs with difference equal to k
C#
211
Chapter 35. Count all distinct pairs with difference equal to k
int n, int k)
{
int count = 0, i;
// Sort array elements
Array.Sort(arr);
// code to remove duplicates from arr[]
// Pick a first element point
for (i = 0; i < n - 1; i++)
if (binarySearch(arr, i + 1, n - 1,
arr[i] + k) != -1)
count++;
return count;
}
// Driver code
public static void Main()
{
int []arr = { 1, 5, 3, 4, 2 };
int n = arr.Length;
int k = 3;
Console.WriteLine("Count of pairs with"
+ " given diff is "
+ countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed by Sam007.
PHP
<?php
// A sorting based PHP program to
// count pairs with difference k
// Standard binary search function
function binarySearch($arr, $low,
$high, $x)
{
if ($high >= $low)
{
$mid = $low + ($high - $low)/2;
if ($x == $arr[$mid])
212
Chapter 35. Count all distinct pairs with difference equal to k
return $mid;
if ($x > $arr[$mid])
return binarySearch($arr, ($mid + 1),
$high, $x);
else
return binarySearch($arr, $low,
($mid -1), $x);
}
return -1;
}
/* Returns count of pairs with
difference k in arr[] of size n. */
function countPairsWithDiffK($arr, $n, $k)
{
$count = 0;
$i;
// Sort array elements
sort($arr);
// Code to remove duplicates
// from arr[]
// Pick a first element point
for ($i = 0; $i < $n - 1; $i++)
if (binarySearch($arr, $i + 1, $n - 1,
$arr[$i] + $k) != -1)
$count++;
return $count;
}
// Driver Code
$arr = array(1, 5, 3, 4, 2);
$n = count($arr);
$k = 3;
echo "Count of pairs with given diff is "
, countPairsWithDiffK($arr, $n, $k);
// This code is contributed by anuj-67.
?>
Output:
213
Chapter 35. Count all distinct pairs with difference equal to k
Time complexity: The first step (sorting) takes O(nLogn) time. The second step runs binary
search n times, so the time complexity of second step is also O(nLogn). Therefore, overall
time complexity is O(nLogn). The second step can be optimized to O(n), see this.
Method 3 (Use Self-balancing BST)
We can also a self-balancing BST like AVL tree or Red Black tree to solve this problem.
Following is detailed algorithm.
1) Initialize count as 0.
2) Insert all elements of arr[] in an AVL tree. While inserting,
ignore an element if already present in AVL tree.
3) Do following for each element arr[i].
a) Search for arr[i] + k in AVL tree, if found then increment count.
b) Search for arr[i] - k in AVL tree, if found then increment count.
c) Remove arr[i] from AVL tree.
Time complexity of above solution is also O(nLogn) as search and delete operations take
O(Logn) time for a self-balancing binary search tree.
Method 4 (Use Hashing)
We can also use hashing to achieve the average time complexity as O(n) for many cases.
1) Initialize count as 0.
2) Insert all distinct elements of arr[] in a hash map. While inserting,
ignore an element if already present in the hash map.
3) Do following for each element arr[i].
a) Look for arr[i] + k in the hash map, if found then increment count.
b) Look for arr[i] - k in the hash map, if found then increment count.
c) Remove arr[i] from hash table.
A very simple case where hashing works in O(n) time is the case where range of values is
very small. For example, in the following implementation, range of numbers is assumed to
be 0 to 99999. A simple hashing technique to use values as index can be used.
214
Chapter 35. Count all distinct pairs with difference equal to k
• If value diff is K, increment count and move both pointers to next element
• if value diff > k, move l to next element
• if value diff < k, move r to next element
return count
C++
215
Chapter 35. Count all distinct pairs with difference equal to k
Java
216
Chapter 35. Count all distinct pairs with difference equal to k
r++;
}
return count;
}
// Driver program to test above function
public static void main(String[] args)
{
int arr[] = {1, 5, 3, 4, 2};
int n = arr.length;
int k = 3;
System.out.println("Count of pairs with given diff is " +
countPairsWithDiffK(arr, n, k));
}
}
// This code is contributed by Prerna Saini
C#
217
Chapter 35. Count all distinct pairs with difference equal to k
PHP
<?php
// A sorting based program to count
// pairs with difference k
// Returns count of pairs with
// difference k in arr[] of size n.
function countPairsWithDiffK( $arr, $n, $k)
{
$count = 0;
// Sort array elements
sort($arr);
$l = 0;
$r = 0;
while($r < $n)
{
if($arr[$r] - $arr[$l] == $k)
{
$count++;
$l++;
$r++;
}
else if($arr[$r] - $arr[$l] > $k)
$l++;
218
Chapter 35. Count all distinct pairs with difference equal to k
Output:
Source
https://www.geeksforgeeks.org/count-pairs-difference-equal-k/
219
Chapter 36
A Simple solution is to traverse each element and check if there’s another number whose
XOR with it is equal to x. This solution takes O(n2 ) time.
An efficient solution of this problem take O(n) time. The idea is based on the fact that
arr[i] ^ arr[j] is equal to x if and only if arr[i] ^ x is equal to arr[j].
1) Initialize result as 0.
2) Create an empty hash set "s".
3) Do following for each element arr[i] in arr[]
(a) If x ^ arr[i] is in "s", then increment result by 1.
(b) Insert arr[i] into the hash set "s".
3) return result.
C++
220
Chapter 36. Count all pairs with given XOR
Python3
221
Chapter 36. Count all pairs with given XOR
Output:
C++
222
Chapter 36. Count all pairs with given XOR
// value x
#include<bits/stdc++.h>
using namespace std;
// Returns count of pairs in arr[0..n-1] with XOR
// value equals to x.
int xorPairCount(int arr[], int n, int x)
{
int result = 0; // Initialize result
// create empty map that stores counts of
// individual elements of array.
unordered_map<int, int> m;
for (int i=0; i<n ; i++)
{
int curr_xor = x^arr[i];
// If there exist an element in map m
// with XOR equals to x^arr[i], that means
// there exist an element such that the
// XOR of element with arr[i] is equal to
// x, then increment count.
if (m.find(curr_xor) != m.end())
result += m[curr_xor];
// Increment count of current element
m[arr[i]]++;
}
// return total count of pairs with XOR equal to x
return result;
}
// driver program
int main()
{
int arr[] = {2, 5, 2};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 0;
cout << "Count of pairs with given XOR = "
<< xorPairCount(arr, n, x);
return 0;
}
Output:
223
Chapter 36. Count all pairs with given XOR
Source
https://www.geeksforgeeks.org/count-pairs-given-xor/
224
Chapter 37
Explanation:
First window is {1, 2, 1, 3}, count of distinct numbers is 3
Second window is {2, 1, 3, 4} count of distinct numbers is 4
Third window is {1, 3, 4, 2} count of distinct numbers is 4
Fourth window is {3, 4, 2, 3} count of distinct numbers is 3
C++
225
Chapter 37. Count distinct elements in every window of size k
#include <iostream>
using namespace std;
// Counts distinct elements in window of size k
int countWindowDistinct(int win[], int k)
{
int dist_count = 0;
// Traverse the window
for (int i=0; i<k; i++)
{
// Check if element arr[i] exists in arr[0..i-1]
int j;
for (j=0; j<i; j++)
if (win[i] == win[j])
break;
if (j==i)
dist_count++;
}
return dist_count;
}
// Counts distinct elements in all windows of size k
void countDistinct(int arr[], int n, int k)
{
// Traverse through every window
for (int i=0; i<=n-k; i++)
cout << countWindowDistinct(arr+i, k) << endl;
}
// Driver program
int main()
{
int arr[] = {1, 2, 1, 3, 4, 2, 3}, k = 4;
int n = sizeof(arr)/sizeof(arr[0]);
countDistinct(arr, n, k);
return 0;
}
Java
226
Chapter 37. Count distinct elements in every window of size k
Output:
3
4
4
3
Time complexity of the above solution is O(nk2 ). We can improve time complexity to
O(nkLok) by modifying countWindowDistinct() to use sorting. The function can further
be optimized to use hashing to find distinct elements in a window. With hashing the time
complexity becomes O(nk). Below is a different approach that works in O(n) time.
227
Chapter 37. Count distinct elements in every window of size k
An Efficient Solution is to use the count of the previous window while sliding the window.
The idea is to create a hash map that stores elements of the current window. When we slide
the window, we remove an element from the hash and add an element. We also keep track
of distinct elements. Below is the algorithm.
1) Create an empty hash map. Let hash map be hM
2) Initialize distinct element count ‘dist_count’ as 0.
3) Traverse through the first window and insert elements of the first window to hM. The ele-
ments are used as key and their counts as the value in hM. Also, keep updating ‘dist_count’
4) Print ‘dist_count’ for the first window.
3) Traverse through the remaining array (or other windows).
….a) Remove the first element of the previous window.
…….If the removed element appeared only once
…………..remove it from hM and do “dist_count–”
…….Else (appeared multiple times in hM)
…………..decrement its count in hM
….a) Add the current element (last element of the new window)
…….If the added element is not present in hM
…………..add it to hM and do “dist_count++”
…….Else (the added element appeared multiple times)
…………..increment its count in hM
Below is an implementation of above approach.
Java
228
Chapter 37. Count distinct elements in every window of size k
{
hM.put(arr[i], 1);
dist_count++;
}
else
{
int count = hM.get(arr[i]);
hM.put(arr[i], count+1);
}
}
// Print count of first window
System.out.println(dist_count);
// Traverse through the remaining array
for (int i = k; i < arr.length; i++)
{
// Remove first element of previous window
// If there was only one occurrence, then
// reduce distinct count.
if (hM.get(arr[i-k]) == 1)
{
hM.remove(arr[i-k]);
dist_count--;
}
else // reduce count of the removed element
{
int count = hM.get(arr[i-k]);
hM.put(arr[i-k], count-1);
}
// Add new element of current window
// If this element appears first time,
// increment distinct element count
if (hM.get(arr[i]) == null)
{
hM.put(arr[i], 1);
dist_count++;
}
else // Increment distinct element count
{
int count = hM.get(arr[i]);
hM.put(arr[i], count+1);
}
// Print count of current window
System.out.println(dist_count);
229
Chapter 37. Count distinct elements in every window of size k
}
}
// Driver method
public static void main(String arg[])
{
int arr[] = {1, 2, 1, 3, 4, 2, 3};
int k = 4;
countDistinct(arr, k);
}
}
C++
#include <iostream>
#include <map>
using namespace std;
void countDistinct(int arr[], int k, int n)
{
// Creates an empty hashmap hm
map<int, int> hm;
// initialize distinct element count for current window
int dist_count = 0;
// Traverse the first window and store count
// of every element in hash map
for (int i = 0; i < k; i++)
{
if (hm[arr[i]] == 0)
{
dist_count++;
}
hm[arr[i]] += 1;
}
// Print count of first window
cout << dist_count << endl;
// Traverse through the remaining array
for (int i = k; i < n; i++)
{
// Remove first element of previous window
// If there was only one occurrence, then reduce distinct count.
if (hm[arr[i-k]] == 1)
{
dist_count--;
230
Chapter 37. Count distinct elements in every window of size k
}
// reduce count of the removed element
hm[arr[i-k]] -= 1;
// Add new element of current window
// If this element appears first time,
// increment distinct element count
if (hm[arr[i]] == 0)
{
dist_count++;
}
hm[arr[i]] += 1;
// Print count of current window
cout << dist_count << endl;
}
}
int main()
{
int arr[] = {1, 2, 1, 3, 4, 2, 3};
int size = sizeof(arr)/sizeof(arr[0]);
int k = 4;
countDistinct(arr, k, size);
return 0;
}
//This solution is contributed by Aditya Goel
Output:
3
4
4
3
Source
https://www.geeksforgeeks.org/count-distinct-elements-in-every-window-of-size-k/
231
Chapter 38
C++
232
Chapter 38. Count divisible pairs in an array
res++;
return res;
}
int main()
{
int a[] = {1, 2, 3, 9};
int n = sizeof(a) / sizeof(a[0]);
cout << countDivisibles(a, n);
return 0;
}
Java
233
Chapter 38. Count divisible pairs in an array
// This code is contributed by Smitha.
C#
PHP
<?php
// PHP program to count divisible pairs.
function countDivisibles($arr, $n)
234
Chapter 38. Count divisible pairs in an array
{
$res = 0;
// Iterate through all pairs
for ($i = 0; $i < $n; $i++)
for ($j = $i + 1; $j < $n; $j++)
// Increment count if one divides
// other
if ($arr[$i] % $arr[$j] == 0 ||
$arr[$j] % $arr[$i] == 0)
$res++;
return $res;
}
$a = array(1, 2, 3, 9);
$n = count($a);
echo (countDivisibles($a, $n));
?>
Output:
Source
https://www.geeksforgeeks.org/count-divisible-pairs-array/
235
Chapter 39
Count elements that are divisible by at-least one element in another array - GeeksforGeeks
Given two arrays arr1[] and arr2[]. The task is to find the count of such elements in the first
array whose at-least one factor is present in the second array.
Examples:
The idea is to insert all elements of the second array into a hash such that the lookup for
factors can be done in constant time. Now, traverse the first array and for every element
generate all of the factors starting from 1 and check if any of the factors is present in the
hash or not.
Below is the implementation of the above approach:
236
Chapter 39. Count elements that are divisible by at-least one element in another array
// in second array.
#include <bits/stdc++.h>
using namespace std;
// Util function to count the elements
// in first array whose atleast
// one factor is present in second array
int elementCount(int arr1[], int n1, int arr2[], int n2)
{
// counter to count number of elements
int count = 0;
// Hash of second array elements
unordered_set<int> hash;
for (int i = 0; i < n2; i++)
hash.insert(arr2[i]);
// loop to traverse through array elements
// and check for its factors
for (int i = 0; i < n1; i++) {
// generate factors of elements
// of first array
for (int j = 1; j * j <= arr1[i]; j++) {
// Check if j is a factor
if (arr1[i] % j == 0) {
// check if the factor is present in
// second array using the hash
if ((hash.find(j) != hash.end()) ||
(hash.find(arr1[i] / j) != hash.end())) {
count++;
break;
}
}
}
}
return count;
}
// Driver code
int main()
{
int arr1[] = { 10, 2, 13, 4, 15 };
int arr2[] = { 2, 4, 5, 6 };
237
Chapter 39. Count elements that are divisible by at-least one element in another array
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);
cout << elementCount(arr1, n1, arr2, n2);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/count-elements-that-are-divisible-by-at-least-one-element-in-another-array/
238
Chapter 40
Count items common to both the lists but with different prices - GeeksforGeeks
Given two lists list1 and list2 containing m and n items respectively. Each item is associ-
ated with two fields: name and price. The problem is to count items which are in both the
lists but with different prices.
Examples:
239
Chapter 40. Count items common to both the lists but with different prices
Python3
240
Chapter 40. Count items common to both the lists but with different prices
# Python implementation to
# count items common to both
# the lists but with different
# prices
# function to count items
# common to both
# the lists but with different prices
def countItems(list1, list2):
count = 0
# for each item of 'list1'
# check if it is in 'list2'
# but with a different price
for i in list1:
for j in list2:
if i[0] == j[0] and i[1] != j[1]:
count += 1
# required count of items
return count
# Driver program to test above
list1 = [("apple", 60), ("bread", 20),
("wheat", 50), ("oil", 30)]
list2 = [("milk", 20), ("bread", 15),
("wheat", 40), ("apple", 60)]
print("Count = ", countItems(list1, list2))
# This code is contributed by Ansu Kumari.
Output:
Count = 2
241
Chapter 40. Count items common to both the lists but with different prices
using namespace std;
// details of an item
struct item
{
string name;
int price;
};
// comparator function used for sorting
bool compare(struct item a, struct item b)
{
return (a.name.compare(b.name) <= 0);
}
// function to search 'str' in 'list2[]'. If it exists then
// price associated with 'str' in 'list2[]' is being
// returned else -1 is returned. Here binary serach
// trechnique is being applied for searching
int binary_search(item list2[], int low, int high, string str)
{
while (low <= high)
{
int mid = (low + high) / 2;
// if true the item 'str' is in 'list2'
if (list2[mid].name.compare(str) == 0)
return list2[mid].price;
else if (list2[mid].name.compare(str) < 0)
low = mid + 1;
else
high = mid - 1;
}
// item 'str' is not in 'list2'
return -1;
}
// function to count items common to both
// the lists but with different prices
int countItems(item list1[], int m,
item list2[], int n)
{
// sort 'list2' in alphabetcal order of
// items name
242
Chapter 40. Count items common to both the lists but with different prices
Output:
Count = 2
243
Chapter 40. Count items common to both the lists but with different prices
Method 3 (Efficient Approach): Create a hash table with (key, value) tuple as (item
name, price). Insert the elements of list1 in the hash table. Now, for each element of
list2 check if it is the hash table or not. If it is present, then check if its price is different
then the value from the hash table. If so then increment the count.
244
Chapter 40. Count items common to both the lists but with different prices
Output:
Count = 2
Source
https://www.geeksforgeeks.org/count-items-common-lists-different-prices/
245
Chapter 41
We can solve above problem by following approach – For each point p, calculate its slope
with other points and use a map to record how many points have same slope, by which we
can find out how many points are on same line with p as their one point. For each point
keep doing the same thing and update the maximum number of point count found so far.
Some things to note in implementation are:
1) if two point are (x1, y1) and (x2, y2) then their slope will be (y2 – y1) / (x2 – x1)
which can be a double value and can cause precision problems. To get rid of the precision
problems, we treat slope as pair ((y2 – y1), (x2 – x1)) instead of ratio and reduce pair by
their gcd before inserting into map. In below code points which are vertical or repeated are
treated separately.
2) If we use unordered_map in c++ or HashMap in Java for storing the slope pair, then
total time complexity of solution will be O(n^2)
246
Chapter 41. Count maximum points on same line
247
Chapter 41. Count maximum points on same line
yDif /= g;
xDif /= g;
// increasing the frequency of current slope
// in map
slopeMap[make_pair(yDif, xDif)]++;
curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]);
}
curMax = max(curMax, verticalPoints);
}
// updating global maximum by current point's maximum
maxPoint = max(maxPoint, curMax + overlapPoints + 1);
// printf("maximum colinear point
// which contains current point
// are : %d\n", curMax + overlapPoints + 1);
slopeMap.clear();
}
return maxPoint;
}
// Driver code
int main()
{
const int N = 6;
int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2},
{3, 3}, {3, 4}};
vector< pair<int, int> > points;
for (int i = 0; i < N; i++)
points.push_back(make_pair(arr[i][0], arr[i][1]));
cout << maxPointOnSameLine(points) << endl;
return 0;
}
Output:
Improved By : PortgasDAce
248
Chapter 41. Count maximum points on same line
Source
https://www.geeksforgeeks.org/count-maximum-points-on-same-line/
249
Chapter 42
Input : abcd
Output : abcd abc ab a bcd bc b cd c d
All Elements are Distinct
Input : aaa
Output : aaa aa a aa a a
All elements are not Distinct
250
Chapter 42. Count number of Distinct Substring in a String
// List All Substrings
for (int i = 0; i <= str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
// Add each substring in Set
result.add(str.substring(i, j));
}
}
// Return size of the HashSet
return result.size();
}
// Driver Code
public static void main(String[] args)
{
String str = "aaaa";
System.out.println(distinctSubstring(str));
}
}
Output:
251
Chapter 42. Count number of Distinct Substring in a String
result.add(str.substring(i, j));
}
}
// Return the HashSet
return result;
}
// Driver Code
public static void main(String[] args)
{
String str = "aaaa";
Set<String> subs = distinctSubstring(str);
System.out.println("Distinct Substrings are: ");
for (String s : subs) {
System.out.println(s);
}
}
}
Output:
Source
https://www.geeksforgeeks.org/count-number-of-distinct-substring-in-a-string/
252
Chapter 43
Input : arr[] = {3 5 7 6 4 9 12 4 8}
num1 = 5
num2 = 4
Output : 5
Number of elements between leftmost occurrence
of 5 and rightmost occurrence of 4 is five.
253
Chapter 43. Count number of elements between two given elements in array
The solution should traverse array only once in all cases (when single or both elements are
not present)
The idea is to traverse array from left and find first occurrence of num1. If we reach end,
we return 0. Then we traverse from rightmost element and find num2. We traverse only till
the point which is greater than index of num1. If we reach end, we return 0. If we found
both elements, we return count using indexes of found elements.
CPP
254
Chapter 43. Count number of elements between two given elements in array
Java
255
Chapter 43. Count number of elements between two given elements in array
Python3
256
Chapter 43. Count number of elements between two given elements in array
C#
257
Chapter 43. Count number of elements between two given elements in array
}
}
// This article is contributed by vt_m.
PHP
<?php
// Program to count number
// of elements between
// two given elements.
// Function to count
// number of elements
// occurs between the
// elements.
function getCount($arr, $n,
$num1, $num2)
{
// Find num1
$i = 0;
for ($i = 0; $i < $n; $i++)
if ($arr[$i] == $num1)
break;
// If num1 is not present
// or present at end
if ($i >= $n - 1)
return 0;
// Find num2
$j;
for ($j = $n - 1; $j >= $i + 1; $j--)
if ($arr[$j] == $num2)
break;
// If num2 is not present
if ($j == $i)
return 0;
// return number of elements
// betweenthe two elements.
return ($j - $i - 1);
}
// Driver Code
$arr = array(3, 5, 7, 6, 4, 9, 12, 4, 8);
258
Chapter 43. Count number of elements between two given elements in array
$n = sizeof($arr);
$num1 = 5; $num2 = 4;
echo(getCount($arr, $n, $num1, $num2));
// This code is contributed by Ajit.
?>
Output:
Source
https://www.geeksforgeeks.org/count-number-elements-two-given-elements-array/
259
Chapter 44
Input : arr[] = { 1, 4, 6, 2, 3, 8}
m = 24
Output : 3
{1, 4, 6} {1, 3, 8} {4, 2, 3}
Input : arr[] = { 0, 4, 6, 2, 3, 8}
m = 18
Output : 0
Asked in : Microsoft
A Naive approach is to consider each and every triplet one by one and count if their
product is equal to m.
C/C++
260
Chapter 44. Count number of triplets with product equal to given number
Java
261
Chapter 44. Count number of triplets with product equal to given number
// Driver method
public static void main(String[] args)
{
int arr[] = { 1, 4, 6, 2, 3, 8 };
int m = 24;
System.out.println(countTriplets(arr, arr.length, m));
}
}
C#
PHP
262
Chapter 44. Count number of triplets with product equal to given number
<?php
// PHP program to count triplets
// with given product m
// Function to count such triplets
function countTriplets($arr, $n, $m)
{
$count = 0;
// Consider all triplets and count if
// their product is equal to m
for ( $i = 0; $i < $n - 2; $i++)
for ( $j = $i + 1; $j < $n - 1; $j++)
for ($k = $j + 1; $k < $n; $k++)
if ($arr[$i] * $arr[$j] * $arr[$k] == $m)
$count++;
return $count;
}
// Driver code
$arr = array(1, 4, 6, 2, 3, 8);
$n = sizeof($arr);
$m = 24;
echo countTriplets($arr, $n, $m);
// This code is contributed by jit_t.
?>
Output:
263
Chapter 44. Count number of triplets with product equal to given number
3. Return count.
C++
264
Chapter 44. Count number of triplets with product equal to given number
{
int arr[] = { 1, 4, 6, 2, 3, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
int m = 24;
cout << countTriplets(arr, n, m);
return 0;
}
Java
265
Chapter 44. Count number of triplets with product equal to given number
}
}
}
// Return number of triplets
return count;
}
// Driver method
public static void main(String[] args)
{
int arr[] = { 1, 4, 6, 2, 3, 8 };
int m = 24;
System.out.println(countTriplets(arr, arr.length, m));
}
}
Output:
Source
https://www.geeksforgeeks.org/count-number-triplets-product-equal-given-number/
266
Chapter 45
C++
267
Chapter 45. Count of index pairs with equal elements in an array
Java
268
Chapter 45. Count of index pairs with equal elements in an array
return ans;
}
//driver code
public static void main (String[] args)
{
int arr[] = { 1, 1, 2 };
int n = arr.length;
System.out.println(countPairs(arr, n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 program to
# count of pairs with equal
# elements in an array.
# Return the number of
# pairs with equal values.
def countPairs(arr, n):
ans = 0
# for each index i and j
for i in range(0 , n):
for j in range(i + 1, n):
# finding the index
# with same value but
# different index.
if (arr[i] == arr[j]):
ans += 1
return ans
# Driven Code
arr = [1, 1, 2 ]
n = len(arr)
print(countPairs(arr, n))
# This code is contributed
# by Smitha
C#
269
Chapter 45. Count of index pairs with equal elements in an array
PHP
<?php
// PHP program to count of
// pairs with equal elements
// in an array.
// Return the number of pairs
// with equal values.
function countPairs( $arr, $n)
{
$ans = 0;
270
Chapter 45. Count of index pairs with equal elements in an array
Output :
C++
271
Chapter 45. Count of index pairs with equal elements in an array
Output :
Source
https://www.geeksforgeeks.org/count-index-pairs-equal-elements-array/
272
Chapter 46
Count of strings that can be formed from another string using each character at-most once
- GeeksforGeeks
Given two strings str1 and str2, the task is to print the number of times str2 can be formed
using characters of str1. However, a character at any index of str1 can only be used once in
the formation of str2.
Examples:
Approach: Since the problem has a restriction on using characters of str1 only once to
form str2. If one character has been used to form one str2, it cannot be used in forming
another str2. Every character of str2 must be present in str1 at least for the formation of
one str1. If all the characters of str2 are already present in str1, then the character which
has the minimum occurrence in str1 will be the number of str2’s that can be formed using
the characters of str1 once. Below are the steps:
• Create an hash-array which stores the number of occurrences of each character of str.
• Iterate for all the characters of str2, and find the minimum most occurrences of every
character in str1.
273
Chapter 46. Count of strings that can be formed from another string using each character
at-most once
Output:
274
Chapter 46. Count of strings that can be formed from another string using each character
at-most once
Time Complexity: O(max(l1,l2)), where l1 and l2 are length of str1 and str2 respectively.
Source
https://www.geeksforgeeks.org/count-of-strings-that-can-be-formed-from-another-string-using-each-character-at-m
275
Chapter 47
Input : s = “10010”
K = 1
Output : 9
The 9 substrings containing one 1 are,
“1”, “10”, “100”, “001”, “01”, “1”,
“10”, “0010” and “010”
In this problem we need to find count of substrings which contains exactly K ones or in
other words sum of digits in those substring is K. We first create a prefix sum array and
loop over that and stop when sum value is greater than or equal to K. Now if sum at current
index is (K + a) then we know that substring sum, from all those indices where sum is (a),
till current index will be K, so count of indices having sum (a), will be added to result. This
procedure is explained with an example below,
string s = “100101”
K = 2
prefix sum array = [1, 1, 1, 2, 2, 3]
276
Chapter 47. Count of substrings of a binary string containing K ones
so result = 1
So we need to track two things, prefix sum and frequency of particular sum. In below code,
instead of storing complete prefix sum, only prefix sum at current index is stored using one
variable and frequency of sums in stored in an array. Total time complexity of solution is
O(N).
C++
277
Chapter 47. Count of substrings of a binary string containing K ones
// add frequency of indices, having
// sum (current sum - K), to the result
res += freq[countOfOne - K];
}
// update freqency of one's count
freq[countOfOne]++;
}
return res;
}
// Driver code to test above methods
int main()
{
string s = "10010";
int K = 1;
cout << countOfSubstringWithKOnes(s, K) << endl;
return 0;
}
Java
278
Chapter 47. Count of substrings of a binary string containing K ones
C#
279
Chapter 47. Count of substrings of a binary string containing K ones
int countOfOne = 0;
int []freq = new int[N+1];
// initialize index having zero
// sum as 1
freq[0] = 1;
// loop over binary characters
// of string
for (int i = 0; i < N; i++) {
// update countOfOne variable
// with value of ith character
countOfOne += (s[i] - '0');
// if value reaches more than
// K, then update result
if (countOfOne >= K) {
// add frequency of indices,
// having sum (current sum - K),
// to the result
res += freq[countOfOne - K];
}
// update freqency of one's count
freq[countOfOne]++;
}
return res;
}
// Driver code to test above methods
static public void Main ()
{
string s = "10010";
int K = 1;
Console.WriteLine(
countOfSubstringWithKOnes(s, K));
}
}
// This code is contributed by vt_m.
PHP
<?php
280
Chapter 47. Count of substrings of a binary string containing K ones
281
Chapter 47. Count of substrings of a binary string containing K ones
// Driver code
$s = "10010";
$K = 1;
echo countOfSubstringWithKOnes($s, $K) ,"\n";
// This code is contributed by m_kit
?>
Output:
Source
https://www.geeksforgeeks.org/count-substrings-binary-string-containing-k-ones/
282
Chapter 48
Count pairs from two linked lists whose sum is equal to a given value - GeeksforGeeks
Given two linked lists(can be sorted or unsorted) of size n1 and n2 of distinct elements.
Given a value x. The problem is to count all pairs from both lists whose sum is equal to
the given value x.
Note: The pair has an element from each linked list.
Examples:
Method 1 (Naive Approach): Using two loops pick elements from both the linked lists
and check whether the sum of the pair is equal to x or not.
C/C++
283
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
284
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
Java
285
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
Output:
Count = 2
286
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
Method 2 (Sorting): Sort the 1st linked list in ascending order and the 2nd linked list in
descending order using merge sort technique. Now traverse both the lists from left to right
in the following way:
Algorithm:
countPairs(list1, list2, x)
Initialize count = 0
while list != NULL and list2 != NULL
if (list1->data + list2->data) == x
list1 = list1->next
list2 = list2->next
count++
else if (list1->data + list2->data) > x
list2 = list2->next
else
list1 = list1->next
return count
For simplicity, the implementation given below assumes that list1 is sorted in ascending
order and list2 is sorted in descending order.
C/C++
287
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
288
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
return count;
}
// Driver program to test above
int main()
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
// create linked list1 1->3->5->7
// assumed to be in ascending order
push(&head1, 7);
push(&head1, 5);
push(&head1, 3);
push(&head1, 1);
// create linked list2 8->5->3->2
// assumed to be in descending order
push(&head2, 2);
push(&head2, 3);
push(&head2, 5);
push(&head2, 8);
int x = 10;
cout << "Count = "
<< countPairs(head1, head2, x);
return 0;
}
Java
289
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
{
int count = 0;
// sort head1 in ascending order and
// head2 in descending order
Collections.sort(head1);
Collections.sort(head2,Collections.reverseOrder());
// traverse both the lists from left to right
Iterator<Integer> itr1 = head1.iterator();
Iterator<Integer> itr2 = head2.iterator();
Integer num1 = itr1.hasNext() ? itr1.next() : null;
Integer num2 = itr2.hasNext() ? itr2.next() : null;
while(num1 != null && num2 != null)
{
// if this sum is equal to 'x', then move both
// the lists to next nodes and increment 'count'
if ((num1 + num2) == x)
{
num1 = itr1.hasNext() ? itr1.next() : null;
num2 = itr2.hasNext() ? itr2.next() : null;
count++;
}
// if this sum is greater than x, then
// move itr2 to next node
else if ((num1 + num2) > x)
num2 = itr2.hasNext() ? itr2.next() : null;
// else move itr1 to next node
else
num1 = itr1.hasNext() ? itr1.next() : null;
}
// required count of pairs
return count;
}
// Driver method
public static void main(String[] args)
{
Integer arr1[] = {3, 1, 5, 7};
290
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
Output:
Count = 2
291
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
292
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
{
struct Node* head1 = NULL;
struct Node* head2 = NULL;
// create linked list1 3->1->5->7
push(&head1, 7);
push(&head1, 5);
push(&head1, 1);
push(&head1, 3);
// create linked list2 8->2->5->3
push(&head2, 3);
push(&head2, 5);
push(&head2, 2);
push(&head2, 8);
int x = 10;
cout << "Count = "
<< countPairs(head1, head2, x);
return 0;
}
Java
293
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
Output:
Count = 2
294
Chapter 48. Count pairs from two linked lists whose sum is equal to a given value
Source
https://www.geeksforgeeks.org/count-pairs-two-linked-lists-whose-sum-equal-given-value/
295
Chapter 49
Count pairs from two sorted arrays whose sum is equal to a given value x - GeeksforGeeks
Given two sorted arrays of size m and n of distinct elements. Given a value x. The problem
is to count all pairs from both arrays whose sum is equal to x.
Note: The pair has an element from each array.
Examples :
Output : 2
The pairs are:
(5, 5) and (7, 3)
Output : 5
Method 1 (Naive Approach): Using two loops pick elements from both the arrays and
check whether the sum of the pair is equal to x or not.
C++
296
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
Java
297
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
import java.io.*;
class GFG {
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
static int countPairs(int []arr1,
int []arr2, int m, int n, int x)
{
int count = 0;
// generating pairs from
// both the arrays
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
// if sum of pair is equal
// to 'x' increment count
if ((arr1[i] + arr2[j]) == x)
count++;
// required count of pairs
return count;
}
// Driver Code
public static void main (String[] args)
{
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 3, 5, 8};
int m = arr1.length;
int n = arr2.length;
int x = 10;
System.out.println( "Count = "
+ countPairs(arr1, arr2, m, n, x));
}
}
// This code is contributed by anuj_67.
Python3
298
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
C#
299
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
{
int count = 0;
// generating pairs from
// both the arrays
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
// if sum of pair is equal
// to 'x' increment count
if ((arr1[i] + arr2[j]) == x)
count++;
// required count of pairs
return count;
}
// Driver Code
public static void Main ()
{
int []arr1 = {1, 3, 5, 7};
int []arr2 = {2, 3, 5, 8};
int m = arr1.Length;
int n = arr2.Length;
int x = 10;
Console.WriteLine( "Count = "
+ countPairs(arr1, arr2, m, n, x));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP implementation to count
// pairs from both sorted arrays
// whose sum is equal to a given
// value
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
function countPairs( $arr1, $arr2,
300
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
Output :
Count = 2
301
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
302
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
// required count of pairs
return count;
}
// Driver Code
int main()
{
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 3, 5, 8};
int m = sizeof(arr1) / sizeof(arr1[0]);
int n = sizeof(arr2) / sizeof(arr2[0]);
int x = 10;
cout << "Count = "
<< countPairs(arr1, arr2, m, n, x);
return 0;
}
Java
303
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
C#
304
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
using System;
class GFG {
// function to search 'value' in the given
// array 'arr[]' it uses binary search
// technique as 'arr[]' is sorted
static bool isPresent(int []arr, int low,
int high, int value)
{
while (low <= high)
{
int mid = (low + high) / 2;
// value found
if (arr[mid] == value)
return true;
else if (arr[mid] > value)
high = mid - 1;
else
low = mid + 1;
}
// value not found
return false;
}
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
static int countPairs(int []arr1, int []arr2,
int m, int n, int x)
{
int count = 0;
for (int i = 0; i < m; i++)
{
// for each arr1[i]
int value = x - arr1[i];
// check if the 'value'
// is present in 'arr2[]'
if (isPresent(arr2, 0, n - 1, value))
count++;
}
305
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
// required count of pairs
return count;
}
// Driver Code
public static void Main ()
{
int []arr1 = {1, 3, 5, 7};
int []arr2 = {2, 3, 5, 8};
int m = arr1.Length;
int n = arr2.Length;
int x = 10;
Console.WriteLine("Count = "
+ countPairs(arr1, arr2, m, n, x));
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP implementation to count
// pairs from both sorted arrays
// whose sum is equal to a given
// value
// function to search 'value'
// in the given array 'arr[]'
// it uses binary search technique
// as 'arr[]' is sorted
function isPresent($arr, $low,
$high, $value)
{
while ($low <= $high)
{
$mid = ($low + $high) / 2;
// value found
if ($arr[$mid] == $value)
return true;
else if ($arr[$mid] > $value)
$high = $mid - 1;
else
$low = $mid + 1;
}
306
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
// value not found
return false;
}
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
function countPairs($arr1, $arr2,
$m, $n, $x)
{
$count = 0;
for ($i = 0; $i < $m; $i++)
{
// for each arr1[i]
$value = $x - $arr1[$i];
// check if the 'value'
// is present in 'arr2[]'
if (isPresent($arr2, 0,
$n - 1, $value))
$count++;
}
// required count of pairs
return $count;
}
// Driver Code
$arr1 = array(1, 3, 5, 7);
$arr2 = array(2, 3, 5, 8);
$m = count($arr1);
$n = count($arr2);
$x = 10;
echo "Count = "
, countPairs($arr1, $arr2, $m, $n, $x);
// This code is contributed by anuj_67.
?>
Output :
Count = 2
Time Complexity : O(mlogn), searching should be applied on the array which is of greater
307
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
308
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
Output :
Count = 2
countPairs(arr1, arr2, m, n, x)
Initialize l = 0, r = n - 1
Initialize count = 0
loop while l = 0
if (arr1[l] + arr2[r]) == x
l++, r--
count++
else if (arr1[l] + arr2[r]) < x
l++
else
r--
return count
C++
309
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
#include <bits/stdc++.h>
using namespace std;
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
int countPairs(int arr1[], int arr2[],
int m, int n, int x)
{
int count = 0;
int l = 0, r = n - 1;
// traverse 'arr1[]' from
// left to right
// traverse 'arr2[]' from
// right to left
while (l < m && r >= 0)
{
// if this sum is equal
// to 'x', then increment 'l',
// decrement 'r' and
// increment 'count'
if ((arr1[l] + arr2[r]) == x)
{
l++; r--;
count++;
}
// if this sum is less
// than x, then increment l
else if ((arr1[l] + arr2[r]) < x)
l++;
// else decrement 'r'
else
r--;
}
// required count of pairs
return count;
}
// Driver Code
int main()
{
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 3, 5, 8};
310
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
Java
311
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
l++;
// else decrement 'r'
else
r--;
}
// required count of pairs
return count;
}
// Driver Code
public static void main (String[] args)
{
int arr1[] = {1, 3, 5, 7};
int arr2[] = {2, 3, 5, 8};
int m = arr1.length;
int n = arr2.length;
int x = 10;
System.out.println( "Count = "
+ countPairs(arr1, arr2, m, n, x));
}
}
// This code is contributed by anuj_67.
C#
// C# implementation to count
// pairs from both sorted arrays
// whose sum is equal to a given
// value
using System;
class GFG {
// function to count all pairs
// from both the sorted arrays
// whose sum is equal to a given
// value
static int countPairs(int []arr1,
int []arr2, int m, int n, int x)
{
int count = 0;
int l = 0, r = n - 1;
// traverse 'arr1[]' from
// left to right
312
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
PHP
<?php
// PHP implementation to count
313
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
314
Chapter 49. Count pairs from two sorted arrays whose sum is equal to a given value x
$m = count($arr1);
$n = count($arr2);
$x = 10;
echo "Count = "
, countPairs($arr1, $arr2, $m, $n, $x);
// This code is contributed by anuj_67
?>
Output :
Count = 2
Source
https://www.geeksforgeeks.org/count-pairs-two-sorted-arrays-whose-sum-equal-given-value-x/
315
Chapter 50
Count pairs from two sorted matrices with given sum - GeeksforGeeks
Given two sorted matrices mat1 and mat2 of size n x n of distinct elements. Given a value
x. The problem is to count all pairs from both matrices whose sum is equal to x.
Note: The pair has an element from each matrix. Matrices are strictly sorted which means
that matrices are sorted in a way such that all elements in a row are sorted in increasing
order and for row ‘i’, where 1 <= i <= n-1, first element of row ’i’ is greater than the last
element of row ’i-1’.
Examples:
Method 1 (Naive Approach): For each element ele of mat1[][] linearly search (x – ele)
in mat2[][].
C++
316
Chapter 50. Count pairs from two sorted matrices with given sum
317
Chapter 50. Count pairs from two sorted matrices with given sum
int mat2[][SIZE] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
cout << "Count = "
<< countPairs(mat1, mat2, n, x);
return 0;
}
Java
318
Chapter 50. Count pairs from two sorted matrices with given sum
int count = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
// if value (x-mat1[i][j]) is
// found in mat2[][]
if (valuePresent(mat2, n, x - mat1[i][j]))
count++;
}
// required count of pairs
return count;
}
// Driver program
public static void main (String[] args)
{
int mat1[][] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
System.out.println ("Count = " +
countPairs(mat1, mat2, n, x));
}
}
// This article is contributed by vt_m
Python3
319
Chapter 50. Count pairs from two sorted matrices with given sum
C#
320
Chapter 50. Count pairs from two sorted matrices with given sum
321
Chapter 50. Count pairs from two sorted matrices with given sum
int [,]mat1 = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int [,]mat2 = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
Console.WriteLine("Count = " +
countPairs(mat1, mat2, n, x));
}
}
// This article is contributed by vt_m
Output:
Count = 4
322
Chapter 50. Count pairs from two sorted matrices with given sum
323
Chapter 50. Count pairs from two sorted matrices with given sum
// else false
bool searchValue(int mat[][SIZE],
int n, int val)
{
// to get the row index number of the largest element
// smaller than equal to 'val' in mat[][]
int row_no = binarySearchOnRow(mat, 0, n - 1, val);
// if no such row exists, then
// 'val' is not present
if (row_no == -1)
return false;
// to search 'val' in mat[row_no][]
return binarySearchOnCol(mat, 0, n - 1, val, row_no);
}
// function to count pairs from two sorted matrices
// whose sum is equal to a given value x
int countPairs(int mat1[][SIZE], int mat2[][SIZE],
int n, int x)
{
int count = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// if value (x-mat1[i][j]) is found in mat2[][]
if (searchValue(mat2, n, x - mat1[i][j]))
count++;
// required count of pairs
return count;
}
// Driver program to test above
int main()
{
int mat1[][SIZE] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][SIZE] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
324
Chapter 50. Count pairs from two sorted matrices with given sum
Java
325
Chapter 50. Count pairs from two sorted matrices with given sum
{
int mid = (l + h) / 2;
// 'val' found
if (mat[row][mid] == val)
return true;
// search in mat[row][mid+1...h]
else if (mat[row][mid] < val)
l = mid + 1;
// search in mat[row][l...mid-1]
else
h = mid - 1;
}
// 'val' not found
return false;
}
// function to search 'val' in mat[][]
// returns true if 'val' is present
// else false
static boolean searchValue(int mat[][],
int n, int val)
{
// to get the row index number
// of the largest element smaller
// than equal to 'val' in mat[][]
int row_no = binarySearchOnRow(mat, 0, n - 1, val);
// if no such row exists, then
// 'val' is not present
if (row_no == -1)
return false;
// to search 'val' in mat[row_no][]
return binarySearchOnCol(mat, 0, n - 1, val, row_no);
}
// function to count pairs from
// two sorted matrices whose sum
// is equal to a given value x
static int countPairs(int mat1[][], int mat2[][],
int n, int x)
{
int count = 0;
326
Chapter 50. Count pairs from two sorted matrices with given sum
C#
// C# implementation to count
// pairs from two sorted matrices
// whose sum is equal to a given
// value x
using System;
class GFG
{
//int SIZE= 10;
// function returns the row index no of largest
// element smaller than equal to 'x' in first
// column of mat[][]. If no such element exists
327
Chapter 50. Count pairs from two sorted matrices with given sum
328
Chapter 50. Count pairs from two sorted matrices with given sum
329
Chapter 50. Count pairs from two sorted matrices with given sum
Output:
Count = 4
330
Chapter 50. Count pairs from two sorted matrices with given sum
Output:
Count = 4
331
Chapter 50. Count pairs from two sorted matrices with given sum
this process until either of the two matrices gets completely traversed.
C++
332
Chapter 50. Count pairs from two sorted matrices with given sum
else
c2--;
// if 'c1' crosses right boundary
if (c1 == n) {
// reset 'c1'
c1 = 0;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left boundary
if (c2 == -1) {
// reset 'c2'
c2 = n - 1;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return count;
}
// Driver program to test above
int main()
{
int mat1[][SIZE] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][SIZE] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
cout << "Count = "
<< countPairs(mat1, mat2, n, x);
return 0;
}
333
Chapter 50. Count pairs from two sorted matrices with given sum
Java
334
Chapter 50. Count pairs from two sorted matrices with given sum
// else move mat2[][] column
// 'c2' to left
else
c2--;
// if 'c1' crosses right boundary
if (c1 == n) {
// reset 'c1'
c1 = 0;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left boundary
if (c2 == -1) {
// reset 'c2'
c2 = n - 1;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return count;
}
// Driver code
public static void main (String[] args)
{
int mat1[][] = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int mat2[][] = { { 2, 4, 7 },
{ 9, 10, 12 },
{ 13, 16, 20 } };
int n = 3;
int x = 21;
System.out.println ( "Count = " +
countPairs(mat1, mat2, n, x));
335
Chapter 50. Count pairs from two sorted matrices with given sum
}
}
// This article is contributed by vt_m
C#
336
Chapter 50. Count pairs from two sorted matrices with given sum
}
// if true, move mat1[][]
// column 'c1' to right
else if (val < x)
c1++;
// else move mat2[][] column
// 'c2' to left
else
c2--;
// if 'c1' crosses right
// boundary
if (c1 == n) {
// reset 'c1'
c1 = 0;
// increment row 'r1'
r1++;
}
// if 'c2' crosses left
// boundary
if (c2 == -1) {
// reset 'c2'
c2 = n - 1;
// decrement row 'r2'
r2--;
}
}
// required count of pairs
return count;
}
// Driver code
public static void Main ()
{
int [,]mat1 = { { 1, 5, 6 },
{ 8, 10, 11 },
{ 15, 16, 18 } };
int [,]mat2 = { { 2, 4, 7 },
{ 9, 10, 12 },
337
Chapter 50. Count pairs from two sorted matrices with given sum
Output:
Count = 4
Source
https://www.geeksforgeeks.org/count-pairs-two-sorted-matrices-given-sum/
338
Chapter 51
A Simple solution is to generate all pairs of given array and check if product exists in the
array. If exists, then increment count. Finally return count.
Below is implementation of above idea
C++
339
Chapter 51. Count pairs whose products exist in array
Java
340
Chapter 51. Count pairs whose products exist in array
{
for (int j = i + 1 ; j < n ; j++)
{
int product = arr[i] * arr[j] ;
// find product
// in an array
for (int k = 0; k < n; k++)
{
// if product found
// increment counter
if (arr[k] == product)
{
result++;
break;
}
}
}
}
// return Count of all pair
// whose product exist in array
return result;
}
// Driver Code
public static void main (String[] args)
{
int arr[] = {6, 2, 4, 12, 5, 3} ;
int n = arr.length;
System.out.println(countPairs(arr, n));
}
}
// This code is contributed by anuj_67.
Output:
341
Chapter 51. Count pairs whose products exist in array
Output:
342
Chapter 51. Count pairs whose products exist in array
Time complexity : O(n2 ) ‘Under the assumption insert, find operation take O(1) Time ‘
Improved By : vt_m
Source
https://www.geeksforgeeks.org/count-pairs-whose-products-exist-in-array/
343
Chapter 52
Examples:
Input : arr[] = {1, 5, 7, -1},
sum = 6
Output : 2
Pairs with sum 6 are (1, 5) and (7, -1)
344
Chapter 52. Count pairs with given sum
C++
Java
345
Chapter 52. Count pairs with given sum
// to 'sum'
public static void getPairsCount(int[] arr, int sum)
{
int count = 0;// Initialize result
// Consider all possible pairs and check their sums
for (int i = 0; i < arr.length; i++)
for (int j = i + 1; j < arr.length; j++)
if ((arr[i] + arr[j]) == sum)
count++;
System.out.printf("Count of pairs is %d",count);
}
}
// This program is contributed by Jyotsna
Python3
PHP
346
Chapter 52. Count pairs with given sum
<?php
// PHP implementation of simple
// method to find count of
// pairs with given sum.
// Returns number of pairs in
// arr[0..n-1] with sum equal
// to 'sum'
function getPairsCount($arr, $n, $sum)
{
// Initialize result
$count = 0;
// Consider all possible pairs
// and check their sums
for ($i = 0; $i < $n; $i++)
for ($j = $i + 1; $j < $n; $j++)
if ($arr[$i] + $arr[$j] == $sum)
$count++;
return $count;
}
// Driver Code
$arr = array(1, 5, 7, -1, 5) ;
$n = sizeof($arr);
$sum = 6;
echo "Count of pairs is "
, getPairsCount($arr, $n, $sum);
// This code is contributed by nitin mittal.
?>
Output :
Count of pairs is 3
1. Create a map to store frequency of each number in the array. (Single traversal is
required)
2. In the next traversal, for every element check if it can be combined with any other
element (other than itself!) to give the desired sum. Increment the counter accordingly.
347
Chapter 52. Count pairs with given sum
3. After completion of second traversal, we’d have twice the required value stored in
counter because every pair is counted two times. Hence divide count by 2 and return.
C++
348
Chapter 52. Count pairs with given sum
int sum = 6;
cout << "Count of pairs is "
<< getPairsCount(arr, n, sum);
return 0;
}
Java
349
Chapter 52. Count pairs with given sum
// return the half of twice_count
return twice_count/2;
}
// Driver method to test the above function
public static void main(String[] args) {
int sum = 6;
System.out.println("Count of pairs is " +
getPairsCount(arr.length,sum));
}
}
// This code is contributed by Gaurav Miglani
Python3
350
Chapter 52. Count pairs with given sum
twice_count -= 1
# return the half of twice_count
return int(twice_count / 2)
# Driver function
arr = [1, 5, 7, -1, 5]
n = len(arr)
sum = 6
print("Count of pairs is", getPairsCount(arr,
n, sum))
# This code is contributed by
# Smitha Dinesh Semwal
Output :
Count of pairs is 3
This article is contributed by Ashutosh Kumar. 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/count-pairs-with-given-sum/
351
Chapter 53
Count quadruples from four sorted arrays whose sum is equal to a given value x - Geeks-
forGeeks
Given four sorted arrays each of size n of distinct elements. Given a value x. The problem
is to count all quadruples(group of four numbers) from all the four arrays whose sum is
equal to x.
Note: The quadruple has an element from each of the four arrays.
Examples:
Output : 4
The quadruples are:
(4, 8, 10, 8), (5, 7, 10, 8),
(5, 8, 10, 7), (6, 7, 10, 7)
Method 1 (Naive Approach): Using four nested loops generate all quadruples and check
whether elements in the quadruple sum up to x or not.
352
Chapter 53. Count quadruples from four sorted arrays whose sum is equal to a given value
x
C++
// C++ implementation to count quadruples from four sorted arrays
// whose sum is equal to a given value x
#include <bits/stdc++.h>
using namespace std;
// function to count all quadruples from
// four sorted arrays whose sum is equal
// to a given value x
int countQuadruples(int arr1[], int arr2[],
int arr3[], int arr4[], int n, int x)
{
int count = 0;
// generate all possible quadruples from
// the four sorted arrays
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int k = 0; k < n; k++)
for (int l = 0; l < n; l++)
// check whether elements of
// quadruple sum up to x or not
if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x)
count++;
// required count of quadruples
return count;
}
// Driver program to test above
int main()
{
// four sorted arrays each of size 'n'
int arr1[] = { 1, 4, 5, 6 };
int arr2[] = { 2, 3, 7, 8 };
int arr3[] = { 1, 4, 6, 10 };
int arr4[] = { 2, 4, 7, 8 };
int n = sizeof(arr1) / sizeof(arr1[0]);
int x = 30;
cout << "Count = "
<< countQuadruples(arr1, arr2, arr3,
arr4, n, x);
return 0;
}
353
Chapter 53. Count quadruples from four sorted arrays whose sum is equal to a given value
x
Python3
Output:
Count = 4
354
Chapter 53. Count quadruples from four sorted arrays whose sum is equal to a given value
x
355
Chapter 53. Count quadruples from four sorted arrays whose sum is equal to a given value
x
Output:
Count = 4
356
Chapter 53. Count quadruples from four sorted arrays whose sum is equal to a given value
x
357
Chapter 53. Count quadruples from four sorted arrays whose sum is equal to a given value
x
Output:
Count = 4
358
Chapter 53. Count quadruples from four sorted arrays whose sum is equal to a given value
x
#include <bits/stdc++.h>
using namespace std;
// function to count all quadruples from four sorted
// arrays whose sum is equal to a given value x
int countQuadruples(int arr1[], int arr2[], int arr3[],
int arr4[], int n, int x)
{
int count = 0;
// unordered_map 'um' implemented as hash table
// for <sum, frequency> tuples
unordered_map<int, int> um;
// count frequency of each sum obtained from the
// pairs of arr1[] and arr2[] and store them in 'um'
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
um[arr1[i] + arr2[j]]++;
// generate pair from arr3[] and arr4[]
for (int k = 0; k < n; k++)
for (int l = 0; l < n; l++) {
// calculate the sum of elements in
// the pair so generated
int p_sum = arr3[k] + arr4[l];
// if 'x-p_sum' is present in 'um' then
// add frequency of 'x-p_sum' to 'count'
if (um.find(x - p_sum) != um.end())
count += um[x - p_sum];
}
// required count of quadruples
return count;
}
// Driver program to test above
int main()
{
// four sorted arrays each of size 'n'
int arr1[] = { 1, 4, 5, 6 };
int arr2[] = { 2, 3, 7, 8 };
int arr3[] = { 1, 4, 6, 10 };
int arr4[] = { 2, 4, 7, 8 };
359
Chapter 53. Count quadruples from four sorted arrays whose sum is equal to a given value
x
Output:
Count = 4
Source
https://www.geeksforgeeks.org/count-quadruples-four-sorted-arrays-whose-sum-equal-given-value-x/
360
Chapter 54
Count subarrays having total distinct elements same as original array - GeeksforGeeks
Given an array of n integers. Count total number of sub-array having total distinct elements
same as that of total distinct elements of original array.
A Naive approach is to run a loop one inside another and consider all sub-arrays and
for every sub-array count all distinct elements by using hashing and compare it with total
distinct elements of original array. This approach takes O(n2 ) time.
An efficient approach is to use sliding window to count all distinct elements in one itera-
tion.
361
Chapter 54. Count subarrays having total distinct elements same as original array
1. Find the number of distinct elements in the entire array. Let this number be k <=
N. Initialize Left = 0, Right = 0 and window = 0.
2. Increment right until the number of distinct elements in range [Left=0, Right] equal
to k(or window size would not equal to k), let this right be R1 . Now since the sub-
array [Left = 0, R1 ] has k distinct elements, so all the sub-arrays starting at Left
= 0 and ending after R1 will also have k distinct elements. Thus add N-R1 +1 to
the answer because [Left.. R1 ], [Left.. R1 +1], [Left.. R1 +2] … [Left.. N-1]
contains all the distinct numbers.
3. Now keeping R1 same, increment left. Decrease the frequency of the previous element
i.e., arr[0], and if its frequency becomes 0, decrease the window size. Now, the sub-
array is [Left = 1, Right = R1 ].
4. Repeat the same process from step 2 for other values of Left and Right till Left < N.
C++
362
Chapter 54. Count subarrays having total distinct elements same as original array
// If window size equals to array distinct
// element size, then update answer
if (window == k)
ans += (n - right + 1);
// Decrease the frequency of previous element
// for next sliding window
--vis[ arr[left] ];
// If frequency is zero then decrease the
// window size
if (vis[ arr[left] ] == 0)
--window;
}
return ans;
}
// Driver code
int main()
{
int arr[] = {2, 1, 3, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
cout << countDistictSubarray(arr, n) <<"n";
return 0;
}
Java
363
Chapter 54. Count subarrays having total distinct elements same as original array
}
};
for (int i = 0; i < n; ++i)
vis.put(arr[i], 1);
int k = vis.size();
// Reset the container by removing all elements
vis.clear();
// Use sliding window concept to find
// count of subarrays having k distinct
// elements.
int ans = 0, right = 0, window = 0;
for (int left = 0; left < n; ++left)
{
while (right < n && window < k)
{
vis.put(arr[right], vis.get(arr[right]) + 1);
if (vis.get(arr[right])== 1)
++window;
++right;
}
// If window size equals to array distinct
// element size, then update answer
if (window == k)
ans += (n - right + 1);
// Decrease the frequency of previous element
// for next sliding window
vis.put(arr[left], vis.get(arr[left]) - 1);
// If frequency is zero then decrease the
// window size
if (vis.get(arr[left]) == 0)
--window;
}
return ans;
}
// Driver method
public static void main(String args[])
{
int arr[] = {2, 1, 3, 2, 3};
364
Chapter 54. Count subarrays having total distinct elements same as original array
System.out.println(countDistictSubarray(arr, arr.length));
}
}
Output:
5
Source
https://www.geeksforgeeks.org/count-subarrays-total-distinct-elements-original-array/
365
Chapter 55
The problem is closely related to Largest subarray with equal number of 0’s and 1’s.
Approach: Following are the steps:
366
Chapter 55. Count subarrays with equal number of 1’s and 0’s
5. Also add freq of the sum 0 in the hash table to the final result.
Explanation:
Considering all 0’s as -1, if sum[i] == sum[j], where sum[i] = sum(arr[0]+..+arr[i]) and
sum[j] = sum(arr[0]+..+arr[j]) and ‘i’ is less than ‘j’, then sum(arr[i+1]+..+arr[j]) must be
0. It can only be 0 if arr(i+1, .., j) contains equal number of 1’s and 0’s.
C++
367
Chapter 55. Count subarrays with equal number of 1’s and 0’s
Python3
368
Chapter 55. Count subarrays with equal number of 1’s and 0’s
Output:
Count = 8
Source
https://www.geeksforgeeks.org/count-subarrays-equal-number-1s-0s/
369
Chapter 56
This problem is mainly a variation of count subarrays with equal number of 0s and 1s.
A naive approach would be to check for all possible subarrays using two loops, whether
they are even-odd subarrays or not. This approach will take time.
An Efficient approach solves the problem in O(N) time and it is based on following ideas:
370
Chapter 56. Count subarrays with same even and odd elements
• Maintaining track of the difference between the frequency of even and odd integers.
• Hashing of this difference of frequencies is useful in finding number of even-odd sub-
arrays.
The basic idea is to use the difference between the frequency of odd and even numbers to
obtain an optimal solution. We will maintain two integer hash arrays for the positive and
negative value of the difference.
-> Example to understand in better way :
-> Consider difference = freq(odd) – freq(even)
-> To calculate this difference, increment the value of ‘difference’ when there is
an odd integer and decrement it when there is an even integer. (initially, difference = 0)
arr[] = {3, 4, 6, 8, 1, 10}
index 0 1 2 3 4 5 6
array 3 4 6 8 1 10
difference 0 1 0 -1 -2 -1 -2
-> Observe that whenever a value ‘k’ repeats in the ‘difference’ array, there exists an
even-odd subarray for each previous occurrence of that value i.e. subarray exists from
index i + 1 to j where difference[i] = k and difference[j] = k.
-> Value ‘0’ is repeated in ‘difference’ array at index 2 and hence subarray exists for
(0, 2] indexes. Similarly, for repetition of values ‘-1’ (at indexes 3 and 5) and ‘-2’ (at
indexes 4 and 6), subarray exists for (3, 5] and (4, 6] indexes.
Below is the implementation of the O(N) solution described above.
C++
371
Chapter 56. Count subarrays with same even and odd elements
// initialize these auxiliary arrays with 0
fill_n(hash_positive, n + 1, 0);
fill_n(hash_negative, n + 1, 0);
// since the difference is initially 0, we have to
// initialize hash_positive[0] with 1
hash_positive[0] = 1;
// for loop to iterate through whole
// array (zero-based indexing is used)
for (int i = 0; i < n ; i++)
{
// incrementing or decrementing difference based on
// arr[i] being even or odd, check if arr[i] is odd
if (arr[i] & 1 == 1)
difference++;
else
difference--;
// adding hash value of 'difference' to our answer
// as all the previous occurrences of the same
// difference value will make even-odd subarray
// ending at index 'i'. After that, we will increment
// hash array for that 'difference' value for
// its occurrence at index 'i'. if difference is
// negative then use hash_negative
if (difference < 0)
{
ans += hash_negative[-difference];
hash_negative[-difference]++;
}
// else use hash_positive
else
{
ans += hash_positive[difference];
hash_positive[difference]++;
}
}
// return total number of even-odd subarrays
return ans;
}
// Driver code
int main()
{
372
Chapter 56. Count subarrays with same even and odd elements
C#
373
Chapter 56. Count subarrays with same even and odd elements
// since the difference is
// initially 0, we have to
// initialize hash_positive[0] with 1
hash_positive[0] = 1;
// for loop to iterate
// through whole array
// (zero-based indexing is used)
for (int i = 0; i < n ; i++)
{
// incrementing or decrementing
// difference based on
// arr[i] being even or odd,
// check if arr[i] is odd
if ((arr[i] & 1) == 1)
difference++;
else
difference--;
// adding hash value of 'difference'
// to our answer as all the previous
// occurrences of the same difference
// value will make even-odd subarray
// ending at index 'i'. After that,
// we will increment hash array for
// that 'difference' value for its
// occurrence at index 'i'. if
// difference is negative then use
// hash_negative
if (difference < 0)
{
ans += hash_negative[-difference];
hash_negative[-difference]++;
}
// else use hash_positive
else
{
ans += hash_positive[difference];
hash_positive[difference]++;
}
}
// return total number
// of even-odd subarrays
return ans;
}
374
Chapter 56. Count subarrays with same even and odd elements
// Driver code
static void Main()
{
int []arr = new int[]{3, 4, 6, 8,
1, 10, 5, 7};
int n = arr.Length;
// Printing total number
// of even-odd subarrays
Console.Write("Total Number of Even-Odd" +
" subarrays are " +
countSubarrays(arr,n));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output:
Source
https://www.geeksforgeeks.org/count-subarrays-with-same-even-and-odd-elements/
375
Chapter 57
Input : {4, 2, 1, 9, 2, 6, 5, 3}
Output : 7
The subsets are:
[4], [2], [6], [4, 2],
[2, 6], [4, 6], [4, 2, 6]
A simple approach is to consider all the subsets and check whether they satisfy the given
conditions or not. The time complexity will be in exponential.
An efficient approach is to count number of distinct even numbers. Let this be ceven.
And then apply formula:
2ceven – 1
This is similar to counting the number of subsets of a given set of n elements. 1 is subtracted
because the null set is not considered.
376
Chapter 57. Count subsets having distinct even numbers
#include <bits/stdc++.h>
using namespace std;
// function to count the
// required subsets
int countSubsets(int arr[], int n)
{
unordered_set<int> us;
int even_count = 0;
// inserting even numbers in the set 'us'
// single copy of each number is retained
for (int i=0; i<n; i++)
if (arr[i] % 2 == 0)
us.insert(arr[i]);
unordered_set<int>:: iterator itr;
// counting distinct even numbers
for (itr=us.begin(); itr!=us.end(); itr++)
even_count++;
// total count of required subsets
return (pow(2, even_count) - 1);
}
// Driver program to test above
int main()
{
int arr[] = {4, 2, 1, 9, 2, 6, 5, 3};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Number of subsets = "
<< countSubsets(arr, n);
return 0;
}
Output:
Number of subsets = 7
Source
https://www.geeksforgeeks.org/count-subsets-distinct-even-numbers/
377
Chapter 58
A Simple Solution is to use two loops to go through all possible subarrays of arr[] and
count the number of subarrays having XOR of their elements as m.
C++
378
Chapter 58. Count the number of subarrays having a given XOR
// Simple function that returns count of subarrays
// of arr with XOR value equals to m
long long subarrayXor(int arr[], int n, int m)
{
long long ans = 0; // Initialize ans
// Pick starting point i of subarrays
for (int i = 0; i < n; i++) {
int xorSum = 0; // Store XOR of current subarray
// Pick ending point j of subarray for each i
for (int j = i; j < n; j++) {
// calculate xorSum
xorSum = xorSum ^ arr[j];
// If xorSum is equal to given value,
// increase ans by 1.
if (xorSum == m)
ans++;
}
}
return ans;
}
// Driver program to test above function
int main()
{
int arr[] = { 4, 2, 2, 6, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
int m = 6;
cout << "Number of subarrays having given XOR is "
<< subarrayXor(arr, n, m);
return 0;
}
Java
379
Chapter 58. Count the number of subarrays having a given XOR
int n, int m)
{
// Initialize ans
long ans = 0;
// Pick starting point i of
// subarrays
for (int i = 0; i < n; i++)
{
// Store XOR of current
// subarray
int xorSum = 0;
// Pick ending point j of
// subarray for each i
for (int j = i; j < n; j++)
{
// calculate xorSum
xorSum = xorSum ^ arr[j];
// If xorSum is equal to
// given value, increase
// ans by 1.
if (xorSum == m)
ans++;
}
}
return ans;
}
// Driver code
public static void main(String args[])
{
int[] arr = { 4, 2, 2, 6, 4 };
int n = arr.length;
int m = 6;
System.out.println("Number of subarrays"
+ " having given XOR is "
+ subarrayXor(arr, n, m));
}
}
380
Chapter 58. Count the number of subarrays having a given XOR
C#
381
Chapter 58. Count the number of subarrays having a given XOR
// Driver Program
public static void Main()
{
int[] arr = { 4, 2, 2, 6, 4 };
int n = arr.Length;
int m = 6;
Console.Write("Number of subarrays"
+ " having given XOR is "
+ subarrayXor(arr, n, m));
}
}
// This code is contributed by Sam007.
PHP
<?php
// A simple PHP Program to
// count all subarrays having
// XOR of elements as given value m
// Simple function that returns
// count of subarrays of arr
// with XOR value equals to m
function subarrayXor($arr, $n,$m)
{
// Initialize ans
$ans = 0;
// Pick starting point
// i of subarrays
for ($i = 0; $i < $n; $i++)
{
// Store XOR of
// current subarray
$xorSum = 0;
// Pick ending point j of
// subarray for each i
for ($j = $i; $j < $n; $j++)
{
// calculate xorSum
$xorSum = $xorSum ^ $arr[$j];
382
Chapter 58. Count the number of subarrays having a given XOR
Output:
1) Initialize ans as 0.
2) Compute xorArr, the prefix xor-sum array.
3) Create a map mp in which we store count of
all prefixes with XOR as a particular value.
4) Traverse xorArr and for each element in xorArr
(A) If m^xorArr[i] XOR exists in map, then
there is another previous prefix with
same XOR, i.e., there is a subarray ending
at i with XOR equal to m. We add count of
all such subarrays to result.
(B) If xorArr[i] is equal to m, increment ans by 1.
383
Chapter 58. Count the number of subarrays having a given XOR
384
Chapter 58. Count the number of subarrays having a given XOR
mp[xorArr[i]]++;
}
// Return total count of subarrays having XOR of
// elements as given value m
return ans;
}
// Driver program to test above function
int main()
{
int arr[] = { 4, 2, 2, 6, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
int m = 6;
cout << "Number of subarrays having given XOR is "
<< subarrayXor(arr, n, m);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/count-number-subarrays-given-xor/
385
Chapter 59
A simple solution is to run two loops. For every item count number of times it occurs. To
avoid duplicate printing, keep track of processed items.
386
Chapter 59. Counting frequencies of array elements
Output:
10 3
20 4
5 1
387
Chapter 59. Counting frequencies of array elements
Output:
5 1
10 3
20 4
388
Chapter 59. Counting frequencies of array elements
Output:
10 3
20 4
5 1
389
Chapter 59. Counting frequencies of array elements
// If integer is not present in freqMap,
// putting this integer to freqMap with 1 as it's value
freqMap.put(arr[i], 1);
}
}
// Printing the freqMap
for (Map.Entry entry : freqMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};
int size = arr.length;
frequencyNumber(arr,size);
}
}
Source
https://www.geeksforgeeks.org/counting-frequencies-of-array-elements/
390
Chapter 60
Collisions are very likely even if we have a big table to store keys. Using the results from
the birthday paradox: with only 23 persons, the probability that two people share the same
birth date is 50%! There are 3 general strategies towards resolving hash collisions:
Although above solutions provide expected lookup cost as O(1), the expected worst-case
cost of a lookup in Open Addressing (with linear probing) is Ω(log n) and Θ(log n / log
log n) in simple chaining (Source : Standford Lecture Notes). To close the gap of expected
time and worst case expected time, two ideas are used:
• Multiple-choice hashing: Give each element multiple choices for positions where it
can reside in the hash table
• Relocation hashing: Allow elements in the hash table to move after being placed
391
Chapter 60. Cuckoo Hashing – Worst case O(1) Lookup!
Cuckoo Hashing :
Cuckoo hashing applies the idea of multiple-choice and relocation together and guarantees
O(1) worst case lookup time!
• Multiple-choice: We give a key two choices h1(key) and h2(key) for residing.
• Relocation: It may happen that h1(key) and h2(key) are preoccupied. This is re-
solved by imitating the Cuckoo bird: it pushes the other eggs or young out of the nest
when it hatches. Analogously, inserting a new key into a cuckoo hashing table may
push an older key to a different location. This leaves us with the problem of re-placing
the older key.
– If alternate position of older key is vacant, there is no problem.
– Otherwise, older key displaces another key. This continues until the procedure
finds a vacant position, or enters a cycle. In case of cycle, new hash functions
are chosen and the whole data structure is ‘rehashed’. Multiple rehashes might
be necessary before Cuckoo succeeds.
Insertion is expected O(1) (amortized) with high probability, even considering the possi-
bility rehashing, as long as the number of keys is kept below half of the capacity of the hash
table, i.e., the load factor is below 50%.
Deletion is O(1) worst-case as it requires inspection of just two locations in the hash table.
Illustration :
Input:
Hash Functions:
h1(key) = key%11
h2(key) = (key/11)%11
Let’s start with inserting 20 at its possible position in the first table determined by h1(20):
392
Chapter 60. Cuckoo Hashing – Worst case O(1) Lookup!
Nex
50
Next: 53. h1(53) = 9. But 20 is already there at 9. We place 53 in table 1 & 20 in table 2
at h2(20)
Next: 75. h1(75) = 9. But 53 is already there at 9. We place 75 in table 1 & 53 in table 2
at h2(53)
Next: 67. h1(67) = 1. But 100 is already there at 1. We place 67 in table 1 & 100 in table
2
393
Chapter 60. Cuckoo Hashing – Worst case O(1) Lookup!
Next: 105. h1(105) = 6. But 50 is already there at 6. We place 105 in table 1 & 50 in table
2 at h2(50) = 4. Now 53 has been displaced. h1(53) = 9. 75 displaced: h2(75) = 6.
Next: 3. h1(3) = 3.
Ne
39. h1(39) = 6. h2(105) = 9. h1(100) = 1. h2(67) = 6. h1(75) = 9. h2(53) = 4. h1(50) =
6. h2(39) = 3.
Here, the new key 39 is displaced later in the recursive calls to place 105 which it displaced.
Implementation :
Below is C/C++ implementation of Cuckoo hashing
394
Chapter 60. Cuckoo Hashing – Worst case O(1) Lookup!
#define MAXN 11
// choices for position
#define ver 2
// Auxiliary space bounded by a small multiple
// of MAXN, minimizing wastage
int hashtable[ver][MAXN];
// Array to store possible positions for a key
int pos[ver];
/* function to fill hash table with dummy value
* dummy value: INT_MIN
* number of hashtables: ver */
void initTable()
{
for (int j=0; j<MAXN; j++)
for (int i=0; i<ver; i++)
hashtable[i][j] = INT_MIN;
}
/* return hashed value for a key
* function: ID of hash function according to which
key has to hashed
* key: item to be hashed */
int hash(int function, int key)
{
switch (function)
{
case 1: return key%MAXN;
case 2: return (key/MAXN)%MAXN;
}
}
/* function to place a key in one of its possible positions
* tableID: table in which key has to be placed, also equal
to function according to which key must be hashed
* cnt: number of times function has already been called
in order to place the first input key
* n: maximum number of times function can be recursively
called before stopping and declaring presence of cycle */
void place(int key, int tableID, int cnt, int n)
{
/* if function has been recursively called max number
of times, stop and declare cycle. Rehash. */
if (cnt==n)
{
395
Chapter 60. Cuckoo Hashing – Worst case O(1) Lookup!
396
Chapter 60. Cuckoo Hashing – Worst case O(1) Lookup!
Output:
105 unpositioned
Cycle present. REHASH.
Final hash tables:
397
Chapter 60. Cuckoo Hashing – Worst case O(1) Lookup!
- 67 - 3 - - 39 - - 53 -
6 20 - 36 50 - 75 - - 100 -
Generalizations of cuckoo hashing that use more than 2 alternative hash functions can be
expected to utilize a larger part of the capacity of the hash table efficiently while sacrificing
some lookup and insertion speed. Example: if we use 3 hash functions, it’s safe to load 91%
and still be operating within expected bounds (Source : Wiki)
Source
https://www.geeksforgeeks.org/cuckoo-hashing/
398
Chapter 61
A simple solution is to use two nested loops, the outer loops picks an element from left to
right that are not visited. The inner loop counts its occurrences and mark occurrences as
visited. Time complexity of this solution is O(n*n) and auxiliary space required is O(n).
A better solution is to use sorting. We sort the array so that same elements come together.
After sorting, we linearly traverse elements and count their frequencies.
An efficient solution is to use hashing. Insert the element and its frequency in a set of
pairs. As the set stores unique values in a sorted order, it will store all the elements with
their frequencies in a sorted order. Iterate in the set and print the frequencies by adding
the previous ones at every step.
399
Chapter 61. Cumulative frequency of count of each element in an unsorted array
Output:
1 2
400
Chapter 61. Cumulative frequency of count of each element in an unsorted array
2 4
3 5
4 6
401
Chapter 61. Cumulative frequency of count of each element in an unsorted array
}
}
// Driver Code
int main()
{
int a[] = {1, 3, 2, 4, 2, 1};
int n = sizeof(a)/sizeof(a[0]);
countFreq(a, n);
return 0;
}
Output:
1->2
3->3
2->5
4->6
Source
https://www.geeksforgeeks.org/cumulative-frequency-of-count-of-each-element-in-an-unsorted-array/
402
Chapter 62
• Data bucket – Data buckets are the memory locations where the records are stored.
These buckets are also considered as Unit Of Storage.
• Hash Function – Hash function is a mapping function that maps all the set of search
keys to actual record address. Generally, hash function uses primary key to generate
the hash index – address of the data block. Hash function can be simple mathematical
function to any complex mathematical function.
• Hash Index-The prefix of an entire hash value is taken as a hash index. Every
hash index has a depth value to signify how many bits are used for computing a hash
function. These bits can address 2n buckets. When all these bits are consumed ? then
the depth value is increased linearly and twice the buckets are allocated.
In static hashing, when a search-key value is provided, the hash function always computes
the same address. For example, if we want to generate address for STUDENT_ID = 76
using mod (5) hash function, it always result in the same bucket address 4. There will not
be any changes to the bucket address here. Hence number of data buckets in the memory
for this static hashing remains constant throughout.
Operations –
403
Chapter 62. DBMS – File Organization | Set 4
• Insertion – When a new record is inserted into the table, The hash function h generate
a bucket address for the new record based on its hash key K.
Bucket address = h(K)
• Searching – When a record needs to be searched, The same hash function is used to
retrieve the bucket address for the record. For Example, if we want to retrieve whole
record for ID 76, and if the hash function is mod (5) on that ID, the bucket address
generated would be 4. Then we will directly got to address 4 and retrieve the whole
record for ID 104. Here ID acts as a hash key.
• Deletion – If we want to delete a record, Using the hash function we will first fetch
the record which is supposed to be deleted. Then we will remove the records for that
address in memory.
• Updation – The data record that needs to be updated is first searched using hash
function, and then the data record is updated.
Now, If we want to insert some new records into the file But the data bucket address gen-
erated by the hash function is not empty or the data already exists in that address. This
becomes a critical situation to handle. This situation in the static hashing is called bucket
overflow.
How will we insert data in this case?
There are several methods provided to overcome this situation. Some commonly used meth-
ods are discussed below:
1. Open Hashing –
In Open hashing method, next available data block is used to enter the new record,
instead of overwriting older one. This method is also called linear probing.
For example, D3 is a new record which needs to be inserted , the hash function
generates address as 105. But it is already full. So the system searches next available
data bucket, 123 and assigns D3 to it.
2. Closed hashing –
In Closed hashing method, a new data bucket is allocated with same address and is
linked it after the full data bucket. This method is also known as overflow chaining.
For example, we have to insert a new record D3 into the tables. The static hash
function generates the data bucket address as 105. But this bucket is full to store the
404
Chapter 62. DBMS – File Organization | Set 4
new data. In this case is a new data bucket is added at the end of 105 data bucket
and is linked to it. Then new record D3 is inserted into the new bucket.
• Quadratic probing :
Quadratic probing is very much similar to open hashing or linear probing. Here,
The only difference between old and new bucket is linear. Quadratic function is
used to determine the new bucket address.
• Double Hashing :
Double Hashing is another method similar to linear probing. Here the difference
is fixed as in linear probing, but this fixed difference is calculated by using another
hash function. That’s why the name is double hashing.
The drawback of static hashing is that that it does not expand or shrink dynamically as the
size of the database grows or shrinks. In Dynamic hashing, data buckets grows or shrinks
(added or removed dynamically) as the records increases or decreases. Dynamic hashing is
also known as extended hashing.
In dynamic hashing, the hash function is made to produce a large number of values. For
Example, there are three data records D1, D2 and D3 . The hash function generates three
addresses 1001, 0101 and 1010 respectively. This method of storing considers only part of
this address – especially only first one bit to store the data. So it tries to load three of them
at address 0 and 1.
405
Chapter 62. DBMS – File Organization | Set 4
But the problem is that No bucket address is remaining for D3. The bucket has to grow
dynamically to accommodate D3. So it changes the address have 2 bits rather than 1 bit,
and then it updates the existing data to have 2 bit address. Then it tries to accommodate
D3.
Reference –
cse.iitb.ac.in
Improved By : Smitha Dinesh Semwal
Source
https://www.geeksforgeeks.org/hashing-in-dbms/
406
Chapter 63
Design a data structure that supports insert, delete, search and getRandom in constant time
- GeeksforGeeks
Design a data structure that supports following operations in Θ(1) time.
insert(x): Inserts an item x to the data structure if not already present.
remove(x): Removes an item x from the data structure if present.
search(x): Searches an item x in the data structure.
getRandom(): Returns a random element from current set of elements
We can use hashingto support first 3 operations in Θ(1) time. How to do the 4th operation?
The idea is to use a resizable array (ArrayList in Java, vector in C) together with hashing.
Resizable arrays support insert in Θ(1) amortized time complexity. To implement getRan-
dom(), we can simply pick a random number from 0 to size-1 (size is number of current
elements) and return the element at that index. The hash map stores array values as keys
and array indexes as values.
Following are detailed operations.
insert(x)
1) Check if x is already present by doing a hash map lookup.
2) If not present, then insert it at the end of the array.
3) Add in hash table also, x is added as key and last array index as index.
remove(x)
1) Check if x is present by doing a hash map lookup.
407
Chapter 63. Design a data structure that supports insert, delete, search and getRandom in
constant time
2) If present, then find its index and remove it from hash map.
3) Swap the last element with this element in array and remove the last element.
Swapping is done because the last element can be removed in O(1) time.
4) Update index of last element in hash map.
getRandom()
1) Generate a random number from 0 to last index.
2) Return the array element at the randomly generated index.
search(x)
Do a lookup for x in hash map.
Below is implementation of the data structure.
Java
408
Chapter 63. Design a data structure that supports insert, delete, search and getRandom in
constant time
int s = arr.size();
arr.add(x);
// And put in hash also
hash.put(x, s);
}
// A Theta(1) function to remove an element from MyDS
// data structure
void remove(int x)
{
// Check if element is present
Integer index = hash.get(x);
if (index == null)
return;
// If present, then remove element from hash
hash.remove(x);
// Swap element with last element so that remove from
// arr[] can be done in O(1) time
int size = arr.size();
Integer last = arr.get(size-1);
Collections.swap(arr, index, size-1);
// Remove last element (This is O(1))
arr.remove(size-1);
// Update hash table for new index of last element
hash.put(last, index);
}
// Returns a random element from MyDS
int getRandom()
{
// Find a random index from 0 to size - 1
Random rand = new Random(); // Choose a different seed
int index = rand.nextInt(arr.size());
// Return element at randomly picked index
return arr.get(index);
}
// Returns index of element if element is present, otherwise null
Integer search(int x)
{
return hash.get(x);
}
409
Chapter 63. Design a data structure that supports insert, delete, search and getRandom in
constant time
}
// Driver class
class Main
{
public static void main (String[] args)
{
MyDS ds = new MyDS();
ds.add(10);
ds.add(20);
ds.add(30);
ds.add(40);
System.out.println(ds.search(30));
ds.remove(20);
ds.add(50);
System.out.println(ds.search(50));
System.out.println(ds.getRandom());
}
}
C++
410
Chapter 63. Design a data structure that supports insert, delete, search and getRandom in
constant time
if(Map.find(x) != Map.end())
return;
// Else put element at the end of arr[]
int index = arr.size();
arr.push_back(x);
// and hashmap also
Map.insert(std::pair<int,int>(x, index));
}
// function to remove a number to DS in O(1)
void remove(int x)
{
// element not found then return
if(Map.find(x) == Map.end())
return;
// remove element from map
int index = Map.at(x);
Map.erase(x);
// swap with last element in arr
// then remove element at back
int last = arr.size() - 1;
swap(arr[index], arr[last]);
arr.pop_back();
// Update hash table for new index of last element
Map.at(arr[index]) = index;
}
// Returns index of element if element is present, otherwise null
int search(int x)
{
if(Map.find(x) != Map.end())
return Map.at(x);
return -1;
}
// Returns a random element from myStructure
int getRandom()
{
// Find a random index from 0 to size - 1
srand (time(NULL));
int random_index = rand() % arr.size();
// Return element at randomly picked index
411
Chapter 63. Design a data structure that supports insert, delete, search and getRandom in
constant time
return arr.at(random_index);
}
};
// Driver main
int main()
{
myStructure ds;
ds.add(10);
ds.add(20);
ds.add(30);
ds.add(40);
cout << ds.search(30) << endl;
ds.remove(20);
ds.add(50);
cout << ds.search(50) << endl;
cout << ds.getRandom() << endl;
}
// This code is contributed by Aditi Sharma
Output:
2
3
40
This article is contributed by Manish Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : SwapnilShukla1
Source
https://www.geeksforgeeks.org/design-a-data-structure-that-supports-insert-delete-search-and-getrandom-in-consta
412
Chapter 64
1. It is a data structure that stores mapping from words to documents or set of documents
i.e. directs you from word to document.
2. Steps to build Inverted index are:
Word Documents
hello doc1
sky doc1, doc3
coffee doc2
hi doc2
greetings doc3
413
Chapter 64. Difference between Inverted Index and Forward Index
Forward Index:
1. It is a data structure that stores mapping from documents to words i.e. directs you
from document to word.
2. Steps to build Forward index are:
4. Searching is quite difficult as it has to look at every contents of index just to retrieve
all pages related to word.
5. Example of forward index:
Document Keywords
doc1 hello, sky, morning
doc2 tea, coffee, hi
doc3 greetings, sky
It stores duplicate keywords in index. Eg: word “sky” is stored multiple times.
Source
https://www.geeksforgeeks.org/difference-inverted-index-forward-index/
414
Chapter 65
A simple solution is to use two loops to count frequency of every element and keep track
of maximum and minimum frequencies.
A better solution is to sort the array in O(n log n) and check
consecutive element’s occurrence and compare their count respectively.
CPP
415
Chapter 65. Difference between highest and least frequencies in an array
{
// sort the array
sort(arr, arr + n);
int count = 0, max_count = 0, min_count = n;
for (int i = 0; i < (n - 1); i++) {
// checking consecutive elements
if (arr[i] == arr[i + 1]) {
count += 1;
continue;
}
else {
max_count = max(max_count, count);
min_count = min(min_count, count);
count = 0;
}
}
return (max_count - min_count);
}
// Driver
int main()
{
int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findDiff(arr, n) << "\n";
return 0;
}
Java
416
Chapter 65. Difference between highest and least frequencies in an array
for (int i = 0; i < (n - 1); i++) {
// checking consecutive elements
if (arr[i] == arr[i + 1]) {
count += 1;
continue;
}
else {
max_count = Math.max(max_count,
count);
min_count = Math.min(min_count,
count);
count = 0;
}
}
return (max_count - min_count);
}
// Driver program to test above function
public static void main(String[] args)
{
int arr[] = { 7, 8, 4, 5, 4, 1,
1, 7, 7, 2, 5 };
int n = arr.length;
System.out.println(findDiff(arr, n));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
417
Chapter 65. Difference between highest and least frequencies in an array
C#
418
Chapter 65. Difference between highest and least frequencies in an array
count = 0;
}
}
return (max_count - min_count);
}
// Driver program to test above function
public static void Main()
{
int[] arr = { 7, 8, 4, 5, 4, 1,
1, 7, 7, 2, 5 };
int n = arr.Length;
Console.WriteLine(findDiff(arr, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP code to find the
// difference between highest
// and least frequencies
// function that
// returns difference
function findDiff($arr, $n)
{
// sort the array
sort($arr);
$count = 0; $max_count = 0;
$min_count = $n;
for ($i = 0; $i < ($n - 1); $i++)
{
// checking consecutive elements
if ($arr[$i] == $arr[$i + 1])
{
$count += 1;
continue;
}
else
419
Chapter 65. Difference between highest and least frequencies in an array
{
$max_count = max($max_count, $count);
$min_count = min($min_count, $count);
$count = 0;
}
}
return ($max_count - $min_count);
}
// Driver Code
$arr = array(7, 8, 4, 5, 4, 1,
1, 7, 7, 2, 5);
$n = sizeof($arr);
echo(findDiff($arr, $n) . "\n");
// This code is contributed by Ajit.
?>
Output:
An efficient solution is to use hashing. We count frequencies of all elements and finally
traverse the hash table to find maximum and minimum.
Below is c++ implementation
420
Chapter 65. Difference between highest and least frequencies in an array
}
return (max_count - min_count);
}
// Driver
int main()
{
int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findDiff(arr, n) << "\n";
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/difference-between-highest-and-least-frequencies-in-an-array/
421
Chapter 66
Different substrings in a string that start and end with given strings - GeeksforGeeks
Given a string s and two other strings begin and end, find the number of different substrings
in the string which begin and end with the given begin and end strings.
Examples:
Input : s = "geeksforgeeks"
begin = "geeks"
end = "for"
Output : 1
Input : s = "vishakha"
begin = "h"
end = "a"
Output : 2
Two different sub-strings are "ha" and "hakha".
Approach : Find all occurrences of string begin and string end. Store the index of each
string in two different arrays. After that traverse through whole string and add one symbol
per iteration to already seen sub-strings and map new strings to some non-negative integers.
As the ends and beginnings of strings and different string of equal length are mapped to
different numbers (and equal strings are mapped equally), simply count the number of
necessary sub-strings of certain length.
C++
422
Chapter 66. Different substrings in a string that start and end with given strings
423
Chapter 66. Different substrings in a string that start and end with given strings
// if we found occurrence of "b".
if (y[j]) {
// now add string "b" to
// already existed substing.
curr_substr += s.substr(j, lb);
// If current substring is not
// included already.
if (hash.find(curr_substr) == hash.end())
ans++;
// put any non negative
// integer to make this
// string as already
// existed.
hash.insert(curr_substr);
}
}
// make substring null.
curr_substr = "";
}
}
// return answer.
return ans;
}
// Driver program for above function.
int main()
{
string s = "codecppforfood";
string begin = "c";
string end = "d";
cout << numberOfDifferentSubstrings(s, begin, end)
<< endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/different-substrings-in-a-string-that-start-and-end-with-given-strings/
424
Chapter 67
Advantages:
1. Searching in O(1) Time: Direct address tables use arrays which are random access
data structure, so, the key values (which are also the index of the array) can be easily
used to search the records in O(1) time.
425
Chapter 67. Direct Address Table
2. Insertion in O(1) Time: We can easily insert an element in an array in O(1) time.
The same thing follows in a direct address table also.
3. Deletion in O(1) Time: Deletion of an element takes O(1) time in an array. Simi-
larly, to delete an element in a direct address table we need O(1) time.
Limitations:
Source
https://www.geeksforgeeks.org/direct-address-table/
426
Chapter 68
Input : 1 2 3 4 5
Output : 3
Explanation: Here P = 1 * 2 * 3 * 4 * 5 = 120. Distinct prime divisors of 120
are 2, 3 and 5. So, the output is 3.
Input : 21 30 15 24 16
Output : 4
Explanation: Here P = 21 * 30 * 15 * 24 * 16 = 3628800. Distinct prime divisors
of 3628800 are 2, 3, 5 and 7. So, the output is 4.
Naive Approach :
The simple solution for the problem would be to multiply every number in the array an then
find the number of distinct prime factors of the product.
But this method can lead to integer overflow.
Better Approach :
To avoid the overflow instead of multiplying the numbers we can find the prime factors of
each element separately and store the prime factors in a set or a map for unique factors.
C++
427
Chapter 68. Distinct Prime Factors of Array Product
428
Chapter 68. Distinct Prime Factors of Array Product
return 0;
}
Java
// Java program to count distinct
// prime factors of a number.
import java.util.*;
class GFG
{
// Function to count the number
// of distinct prime factors of
// product of array
static int Distinct_Prime_factors(Vector a)
{
// use set to store distinct factors
HashSet m = new HashSet();
// iterate over every element of array
for (int i = 0; i < a.size(); i++) { int sq = (int)Math.sqrt(a.get(i)); // from 2 to square
root of number // run a loop and check the numbers // which are factors. for (int j = 2;
j <= sq; j++) { if (a.get(i) % j == 0) { // if j is a factor store // it in the set m.add(j);
// divide the number with j // till it is divisible so // that only prime factors // are stored
while (a.get(i) % j == 0) { a.set(i, a.get(i) / j); } } } // if the number is still greater //
than 1 then it is a prime factor, // insert in set if (a.get(i) > 1)
{
m.add(a.get(i));
}
}
// the number of unique prime
// factors will the size of the set
return m.size();
}
// Driver Code
public static void main(String args[])
{
Vector a = new Vector();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
a.add(5);
System.out.println(Distinct_Prime_factors(a));
}
}
// This code is contributed by Arnab Kundu
429
Chapter 68. Distinct Prime Factors of Array Product
Output :
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/distinct-prime-factors-of-array-product/
430
Chapter 69
• A character on odd index can be swapped with another character at odd index only.
• A character on even index can be swapped with another character on even index only.
Examples:
A simple solution is to run two loops. The outer loop picks a string and inner loop checks
if there is a previously string which can be converted to current string by doing allowed
transformations. This solution requires O(n2 m) time where n is number of strings and m is
maximum number of characters in any string.
An efficient solution generate an encoded string for every input string. The encoded
has counts of even and odd positioned characters separated by a separator. Two strings
431
Chapter 69. Distinct strings with odd and even changes allowed
are considered distinct if their encoded strings are same else not. Once we have a way to
encode string, the problem reduces to counting distinct encoded strings. This is a typical
problem of hashing. We create hash set and one by one store encodings of strings. If an
encoding already exists, we ignore string. Else we store encoding in hash and increment
count of distinct strings.
C/C++
432
Chapter 69. Distinct strings with odd and even changes allowed
return encoding;
}
// This function basically uses a hashing based set to
// store strings which are distinct according to accoding
// to criteria given in question.
int countDistinct(string input[], int n)
{
int countDist = 0; // Initialize result
// Create an empty set and store all distinct
// strings in it.
unordered_set<string> s;
for (int i=0; i<n; i++)
{
// If this encoding appears first time, increment
// count of distinct encodings.
if (s.find(encodeString(input[i])) == s.end())
{
s.insert(encodeString(input[i]));
countDist++;
}
}
return countDist;
}
// Driver code
int main()
{
string input[] = {"abcd", "acbd", "adcb", "cdba",
"bcda", "badc"};
int n = sizeof(input)/sizeof(input[0]);
cout << countDistinct(input, n);
return 0;
}
Java
433
Chapter 69. Distinct strings with odd and even changes allowed
434
Chapter 69. Distinct strings with odd and even changes allowed
return countDist;
}
public static void main(String[] args) {
String input[] = {"abcd", "acbd", "adcb", "cdba",
"bcda", "badc"};
int n = input.length;
System.out.println(countDistinct(input, n));
}
}
Output :
Improved By : krutikkhandhadiya
Source
https://www.geeksforgeeks.org/distinct-strings-odd-even-changes-allowed/
435
Chapter 70
Distributing items when a person cannot take more than two items of same type - Geeks-
forGeeks
Given N sweets which can be of many different types and k customers, one customer won’t
take the same type of sweet more than 2 pieces, the task is to find if it is possible to distribute
all sweets then print “Yes” otherwise “No”.
Given array arr[] represents array of sweets arr[i] is type of sweet.
Examples:
Method 1:
1- Traverse array for each element.
2- Count occurrences of each element in array
3- Check Resulting occurrence of each element must be less than or equal to 2*k.
436
Chapter 70. Distributing items when a person cannot take more than two items of same
type
C++
Java
437
Chapter 70. Distributing items when a person cannot take more than two items of same
type
438
Chapter 70. Distributing items when a person cannot take more than two items of same
type
C#
439
Chapter 70. Distributing items when a person cannot take more than two items of same
type
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program for above implementation
// Function to check occurrence
// of each element
function checkCount($arr, $n, $k)
{
$count;
// Start traversing the elements
for($i = 0; $i < $n; $i++)
{
// Count occurrences of
// current element
$count = 0;
for($j = 0; $j < $n; $j++)
{
if ($arr[$j] == $arr[$i])
$count++;
// If count of any element
// is greater than 2*k then
// return false
if ($count > 2 * $k)
return false;
}
}
return true;
}
// Driver Code
$arr = array(1, 1, 2, 3, 1);
$n =count($arr);
$k = 2;
if(checkCount($arr, $n, $k))
echo "Yes";
else
echo "No";
440
Chapter 70. Distributing items when a person cannot take more than two items of same
type
Output:
Yes
Method 2:
1. Maintain a hash for 32 different type of sweets.
2. Traverse an array and check for every arr[i]
441
Chapter 70. Distributing items when a person cannot take more than two items of same
type
Output:
Yes
Source
https://www.geeksforgeeks.org/distributing-items-person-cannot-take-two-items-type/
442
Chapter 71
Double Hashing
443
Chapter 71. Double Hashing
444
Chapter 71. Double Hashing
// function to check if hash table is full
bool isFull()
{
// if hash size reaches maximum size
return (curr_size == TABLE_SIZE);
}
// function to calculate first hash
int hash1(int key)
{
return (key % TABLE_SIZE);
}
// function to calculate second hash
int hash2(int key)
{
return (PRIME - (key % PRIME));
}
DoubleHash()
{
hashTable = new int[TABLE_SIZE];
curr_size = 0;
for (int i=0; i<TABLE_SIZE; i++)
hashTable[i] = -1;
}
// function to insert key into hash table
void insertHash(int key)
{
// if hash table is full
if (isFull())
return;
// get index from first hash
int index = hash1(key);
// if collision occurs
if (hashTable[index] != -1)
{
// get index2 from second hash
int index2 = hash2(key);
int i = 1;
while (1)
{
// get newIndex
445
Chapter 71. Double Hashing
446
Chapter 71. Double Hashing
Output:
0
1 --> 27
2
3
4
5 --> 10
6 --> 19
7
8
9
10 --> 36
11
12 --> 64
Source
https://www.geeksforgeeks.org/double-hashing/
447
Chapter 72
Efficiently find first repeated character in a string without using any additional data struc-
ture in one traversal - GeeksforGeeks
Implement a space efficient algorithm to check First repeated character in a string without
using any additional data structure in one traversal. Use additional data structures like
count array, hash, etc is not allowed.
Examples :
Input : abcfdeacf
Output : char = a, index= 6
The idea is to use an integer variable and uses bits in its binary representation to store
whether a character is present or not. Typically an integer has at-least 32 bits and we need
to store presence/absence of only 26 characters.
C++
448
Chapter 72. Efficiently find first repeated character in a string without using any
additional data structure in one traversal
// unique.
// Assumptions : (1) str contains only characters
// from 'a' to 'z'
// (2) integers are stored using 32
// bits
int FirstRepeated(string str)
{
// An integer to store presence/absence
// of 26 characters using its 32 bits.
int checker = 0;
for (int i = 0; i < str.length(); ++i)
{
int val = (str[i]-'a');
// If bit corresponding to current
// character is already set
if ((checker & (1 << val)) > 0)
return i;
// set bit in checker
checker |= (1 << val);
}
return -1;
}
// Driver code
int main()
{
string s = "abcfdeacf";
int i=FirstRepeated(s);
if (i!=-1)
cout <<"Char = "<< s[i] << " and Index = "<<i;
else
cout << "No repeated Char";
return 0;
}
Java
449
Chapter 72. Efficiently find first repeated character in a string without using any
additional data structure in one traversal
Python
450
Chapter 72. Efficiently find first repeated character in a string without using any
additional data structure in one traversal
pos = 0
for i in string:
val = ord(i) - ord('a');
# If bit corresponding to current
# character is already set
if ((checker & (1 << val)) > 0):
return pos
# set bit in checker
checker |= (1 << val)
pos += 1
return -1
# Driver code
string = "abcfdeacf"
i = FirstRepeated(string)
if i != -1:
print "Char = ", string[i], " and Index = ", i;
else:
print "No repeated Char"
# This code is contributed by Sachin Bisht
C#
// C# program to Efficiently
// check First repeated character
using System;
public class First_Repeated_char {
static int FirstRepeated(string str)
{
// An integer to store presence/absence
// of 26 characters using its 32 bits.
int checker = 0;
for (int i = 0; i < str.Length; ++i)
{
int val = (str[i]-'a');
// If bit corresponding to current
// character is already set
if ((checker & (1 << val)) > 0)
return i;
451
Chapter 72. Efficiently find first repeated character in a string without using any
additional data structure in one traversal
// set bit in checker
checker |= (1 << val);
}
return -1;
}
// Driver code
public static void Main()
{
string s = "abcfdeacf";
int i=FirstRepeated(s);
if (i!=-1)
Console.WriteLine("Char = " + s[i] +
" and Index = " + i);
else
Console.WriteLine( "No repeated Char");
}
}
// This code is contributed by vt_m.
Output:
Source
https://www.geeksforgeeks.org/efficiently-find-first-repeated-character-string-without-using-additional-data-structu
452
Chapter 73
The idea is to use hashing. We traverse first array and insert all elements and their frequen-
cies in a hash table. Now we traverse through the second array and reduce frequencies in
hash table for the common elements. Now we traverse through first array again and print
those elements whose frequencies are still more than 0. To avoid repeated printing of same
elements, we set frequency as 0.
453
Chapter 73. Elements of first array that have more frequencies
Output:
1 2 5
Time Complexity : O(m + n) under the assumption that unordered_map find() and insert()
work in O(1) time.
454
Chapter 73. Elements of first array that have more frequencies
Source
https://www.geeksforgeeks.org/elements-of-first-array-that-have-more-frequencies/
455
Chapter 74
Input: arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }
Output: 9 4
• Check for each element at index i (except the first and last element), if
456
Chapter 74. Elements that occurred only once in the array
Java
// Java implementation
// of above approach
import java.util.*;
457
Chapter 74. Elements that occurred only once in the array
class GFG
{
// Function to find the elements that
// appeared only once in the array
static void occurredOnce(int arr[], int n)
{
// Sort the array
Arrays.sort(arr);
// Check for first element
if (arr[0] != arr[1])
System.out.println(arr[0] + " ");
// Check for all the elements
// if it is different
// its adjacent elements
for (int i = 1; i < n - 1; i++)
if (arr[i] != arr[i + 1] &&
arr[i] != arr[i - 1])
System.out.print(arr[i] + " ");
// Check for the last element
if (arr[n - 2] != arr[n - 1])
System.out.print(arr[n - 1] + " ");
}
// Driver code
public static void main(String args[])
{
int arr[] = {7, 7, 8, 8, 9,
1, 1, 4, 2, 2};
int n = arr.length;
occurredOnce(arr, n);
}
}
// This code is contributed
// by Arnab Kundu
Python 3
# Python 3 implementation
# of above approach
# Function to find the elements
# that appeared only once in
458
Chapter 74. Elements that occurred only once in the array
# the array
def occurredOnce(arr, n):
# Sort the array
arr.sort()
# Check for first element
if arr[0] != arr[1]:
print(arr[0], end = " ")
# Check for all the elements
# if it is different its
# adjacent elements
for i in range(1, n - 1):
if (arr[i] != arr[i + 1] and
arr[i] != arr[i - 1]):
print( arr[i], end = " ")
# Check for the last element
if arr[n - 2] != arr[n - 1]:
print(arr[n - 1], end = " ")
# Driver code
if __name__ == "__main__":
arr = [ 7, 7, 8, 8, 9,
1, 1, 4, 2, 2 ]
n = len(arr)
occurredOnce(arr, n)
# This code is contributed
# by ChitraNayal
C#
// C# implementation
// of above approach
using System;
class GFG
{
// Function to find the elements that
// appeared only once in the array
static void occurredOnce(int[] arr, int n)
{
// Sort the array
Array.Sort(arr);
459
Chapter 74. Elements that occurred only once in the array
// Check for first element
if (arr[0] != arr[1])
Console.Write(arr[0] + " ");
// Check for all the elements
// if it is different
// its adjacent elements
for (int i = 1; i < n - 1; i++)
if (arr[i] != arr[i + 1] &&
arr[i] != arr[i - 1])
Console.Write(arr[i] + " ");
// Check for the last element
if (arr[n - 2] != arr[n - 1])
Console.Write(arr[n - 1] + " ");
}
// Driver code
public static void Main()
{
int[] arr = {7, 7, 8, 8, 9,
1, 1, 4, 2, 2};
int n = arr.Length;
occurredOnce(arr, n);
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// PHP implementation
// of above approach
// Function to find the elements
// that appeared only once in
// the array
function occurredOnce(&$arr, $n)
{
// Sort the array
sort($arr);
// Check for first element
if ($arr[0] != $arr[1])
460
Chapter 74. Elements that occurred only once in the array
Output:
4 9
C++
461
Chapter 74. Elements that occurred only once in the array
Output:
4 9
• Check if the first and last element is equal. If yes then start traversing the elements
between them.
• Check if the current element is equal to the element at immediate previous index. If
yes, check the same for next element.
462
Chapter 74. Elements that occurred only once in the array
C++
463
Chapter 74. Elements that occurred only once in the array
return 0;
}
Java
464
Chapter 74. Elements that occurred only once in the array
Python 3
465
Chapter 74. Elements that occurred only once in the array
# Check for the last element
if (arr[n - 1] != arr[0] and
arr[n - 1] != arr[n - 2]):
print(arr[n - 1])
# Driver code
if __name__ == "__main__":
arr = [ 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 ]
n = len(arr)
occurredOnce(arr, n)
# This code is contributed
# by ChitraNayal
C#
// C# implementation to find
// elements that appeared only once
using System;
class GFG
{
// Function to find the elements that
// appeared only once in the array
static void occurredOnce(int[] arr, int n)
{
int i = 1, len = n;
// Check if the first and last
// element is equal. If yes,
// remove those elements
if (arr[0] == arr[len - 1])
{
i = 2;
len--;
}
// Start traversing the
// remaining elements
for (; i < n; i++)
// Check if current element is
// equal to the element at
// immediate previous index
// If yes, check the same
// for next element
466
Chapter 74. Elements that occurred only once in the array
PHP
<?php
// PHP implementation to find
// elements that appeared only once
// Function to find the elements that
// appeared only once in the array
function occurredOnce(&$arr, $n)
{
$i = 1;
$len = $n;
// Check if the first and last
// element is equal. If yes,
// remove those elements
if ($arr[0] == $arr[$len - 1])
{
$i = 2;
$len--;
}
467
Chapter 74. Elements that occurred only once in the array
// Start traversing the
// remaining elements
for (; $i < $n; $i++)
// Check if current element is
// equal to the element at
// immediate previous index
// If yes, check the same for
// next element
if ($arr[$i] == $arr[$i - 1])
$i++;
// Else print the current element
else
echo $arr[$i - 1] . " ";
// Check for the last element
if ($arr[$n - 1] != $arr[0] &&
$arr[$n - 1] != $arr[$n - 2])
echo $arr[$n - 1];
}
// Driver code
$arr = array(7, 7, 8, 8, 9,
1, 1, 4, 2, 2);
$n = sizeof($arr);
occurredOnce($arr, $n);
// This code is contributed
// by ChitraNayal
?>
Output:
9 4
468
Chapter 74. Elements that occurred only once in the array
Source
https://www.geeksforgeeks.org/elements-that-occurred-only-once-in-the-array/
469
Chapter 75
Elements to be added so that all elements of a range are present in array - GeeksforGeeks
Given an array of size N. Let A and B be the minimum and maximum in the array respec-
tively. Task is to find how many number should be added to the given array such that all
the element in the range [A, B] occur at-least once in the array.
Examples:
Method 1 (Sorting)
1- Sort the array.
2- Compare arr[i] == arr[i+1]-1 or not. If not, update count = arr[i+1]-arr[i]-1.
3- Return count.
C++
470
Chapter 75. Elements to be added so that all elements of a range are present in array
Java
471
Chapter 75. Elements to be added so that all elements of a range are present in array
Python3
C#
472
Chapter 75. Elements to be added so that all elements of a range are present in array
PHP
<?php
// PHP program for
// above implementation
// Function to count
// numbers to be added
function countNum($arr, $n)
{
$count = 0;
473
Chapter 75. Elements to be added so that all elements of a range are present in array
// Sort the array
sort($arr);
// Check if elements are
// consecutive or not.
// If not, update count
for ($i = 0; $i < $n - 1; $i++)
if ($arr[$i] != $arr[$i + 1] &&
$arr[$i] != $arr[$i + 1] - 1)
$count += $arr[$i + 1] -
$arr[$i] - 1;
return $count;
}
// Driver code
$arr = array(3, 5, 8, 6);
$n = count($arr);
echo countNum($arr, $n) ;
// This code is contributed
// by anuj_67.
?>
Output:
C++
474
Chapter 75. Elements to be added so that all elements of a range are present in array
{
unordered_set<int> s;
int count = 0, maxm = INT_MIN, minm = INT_MAX;
// Make a hash of elements
// and store minimum and maximum element
for (int i = 0; i < n; i++) {
s.insert(arr[i]);
if (arr[i] < minm)
minm = arr[i];
if (arr[i] > maxm)
maxm = arr[i];
}
// Traverse all elements from minimum
// to maximum and count if it is not
// in the hash
for (int i = minm; i <= maxm; i++)
if (s.find(arr[i]) == s.end())
count++;
return count;
}
// Drivers code
int main()
{
int arr[] = { 3, 5, 8, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << countNum(arr, n) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/elements-to-be-added-so-that-all-elements-of-a-range-are-present-in-array/
475
Chapter 76
Equally divide into two sets such that one set has maximum distinct elements - Geeks-
forGeeks
There are two processes P1 and P2, and N resources where N is an even number. There is
an array of N size and arr[i] represents the type of ith resource.There may be more then one
instance of a resource.You are to divide these resources equally between P1 and P2 such
that maximum number of distinct number of resources are allocated to P2. Print maximum
number of distinct resources allocated to P2.
Examples:
476
Chapter 76. Equally divide into two sets such that one set has maximum distinct elements
2. Find out the elements which are unique by comparing the adjacent elements of the sorted
array.suppose count holds the distinct number of resources in array.
3. Return the minimum of count and N/2.
Time complexity- O(N log N)
C++
Java
477
Chapter 76. Equally divide into two sets such that one set has maximum distinct elements
C#
478
Chapter 76. Equally divide into two sets such that one set has maximum distinct elements
// by ankita_saini
Ouput:
Improved By : ankita_saini
Source
https://www.geeksforgeeks.org/equally-divide-into-two-sets-such-that-one-set-has-maximum-distinct-elements/
479
Chapter 77
Input :
1
/ \
2 3
/ / \
4 2 4
/
4
Output :
2
/ and 4
4
Explanation: Above Trees are two duplicate subtrees.
Therefore, you need to return above trees root in the
form of a list.
The idea is to use hashing. We store inorder traversals of subtrees in a hash. Since simple
inorder traversal cannot uniquely identify a tree, we use symbols like ‘(‘ and ‘)’ to represent
NULL nodes.
We pass a Unordered Map in C++ as an argument to the helper function which recursively
calculates inorder string and increases its count in map. If any string gets repeated, then it
will imply duplication of the subtree rooted at that node so push that node in Final result
and return the vector of these nodes.
480
Chapter 77. Find All Duplicate Subtrees
C++
481
Chapter 77. Find All Duplicate Subtrees
Java
482
Chapter 77. Find All Duplicate Subtrees
Output:
483
Chapter 77. Find All Duplicate Subtrees
4 2
Source
https://www.geeksforgeeks.org/find-duplicate-subtrees/
484
Chapter 78
Input:
"Chennai" -> "Banglore"
"Bombay" -> "Delhi"
"Goa" -> "Chennai"
"Delhi" -> "Goa"
Output:
Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore,
It may be assumed that the input list of tickets is not cyclic and there is one ticket from
every city except final destination.
One Solution is to build a graph and do Topological Sorting of the graph. Time complexity
of this solution is O(n).
We can also use hashingto avoid building a graph. The idea is to first find the starting point.
A starting point would never be on ‘to’ side of a ticket. Once we find the starting point, we
can simply traverse the given map to print itinerary in order. Following are steps.
485
Chapter 78. Find Itinerary from a given list of tickets
3) Start from above found starting point and traverse the 'dataset'
to print itinerary.
All of the above steps require O(n) time so overall time complexity is O(n).
Below is Java implementation of above idea.
Java
486
Chapter 78. Find Itinerary from a given list of tickets
C++
#include <iostream>
#include <map>
#include <string>
using namespace std;
void printItinerary(map<string, string> dataSet)
{
// To store reverse of given map
map<string, string> reversemap;
map<string, string>::iterator it;
// To fill reverse map, iterate through the given map
for (it = dataSet.begin(); it!=dataSet.end(); it++)
reversemap[it->second] = it->first;
487
Chapter 78. Find Itinerary from a given list of tickets
Output:
488
Chapter 78. Find Itinerary from a given list of tickets
This article is compiled by Rahul Jain. 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/find-itinerary-from-a-given-list-of-tickets/
489
Chapter 79
490
Chapter 79. Find Recurring Sequence in a Fraction
491
Chapter 79. Find Recurring Sequence in a Fraction
Output :
Recurring sequence is 27
This article is contributed by Dhruv Mahajan. 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/find-recurring-sequence-fraction/
492
Chapter 80
Find Sum of all unique sub-array sum for a given array. - GeeksforGeeks
Given an array of n-positive elements. Sub-array sum is defined as the sum of all elements
of a particular sub-array, the task is to find the sum of all unique sub-array sum.
Note: Unique Sub-array sum means no other sub-array will have the same sum value.
Examples:
493
Chapter 80. Find Sum of all unique sub-array sum for a given array.
494
Chapter 80. Find Sum of all unique sub-array sum for a given array.
Output:
41
Method 2 (Hashing Based) The idea is make an empty hash table. We generate all
subarrays. For every subarray, we compute its sum and increment count of sum in hash
table. Finally we add all those sums whose count is 1.
495
Chapter 80. Find Sum of all unique sub-array sum for a given array.
Output:
41
Source
https://www.geeksforgeeks.org/find-sum-unique-sub-array-sum-given-array/
496
Chapter 81
Find a pair of elements swapping which makes sum of two arrays same - GeeksforGeeks
Given two arrays of integers, find a pair of values (one value from each array) that you can
swap to give the two arrays the same sum.
Examples:
C/C++
497
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
498
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
Java
499
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
{
int A[] = { 4, 1, 2, 1, 1, 2 };
int n = A.length;
int B[] = { 3, 6, 3, 3 };
int m = B.length;
// Call to function
findSwapValues(A, n, B, m);
}
}
// Contributed by Pramod Kumar
Python
500
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
break
# If k is True, it means pair is found.
# So, no further iterations.
if k==True:
break
print val1,val2
return
# Driver code
A=[4,1,2,1,1,2]
B=[3,6,3,3]
# Call to function
findSwapValues(A,B)
# code contributed by sachin bisht
Output :
1 3
Therefore, we’re looking for two values that have a specific target difference: (sumA –
sumB) / 2.
C/C++
501
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
int sum = 0;
for (int i = 0; i < n; i++)
sum += X[i];
return sum;
}
// Function to calculate : a - b = (sumA - sumB) / 2
int getTarget(int A[], int n, int B[], int m)
{
// Calculation of sums from both arrays
int sum1 = getSum(A, n);
int sum2 = getSum(B, m);
// because that the target must be an integer
if ((sum1 - sum2) % 2 != 0)
return 0;
return ((sum1 - sum2) / 2);
}
void findSwapValues(int A[], int n, int B[], int m)
{
int target = getTarget(A, n, B, m);
if (target == 0)
return;
// Look for val1 and val2, such that
// val1 - val2 = (sumA - sumB) / 2
int val1, val2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (A[i] - B[j] == target) {
val1 = A[i];
val2 = B[j];
}
}
}
cout << val1 << " " << val2;
}
// Driver code
int main()
{
int A[] = { 4, 1, 2, 1, 1, 2 };
int n = sizeof(A) / sizeof(A[0]);
int B[] = { 3, 6, 3, 3 };
int m = sizeof(B) / sizeof(B[0]);
502
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
Java
503
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
{
if (A[i] - B[j] == target)
{
val1 = A[i];
val2 = B[j];
}
}
}
System.out.println(val1+" "+val2);
}
// driver program
public static void main (String[] args)
{
int A[] = { 4, 1, 2, 1, 1, 2 };
int n = A.length;
int B[] = { 3, 6, 3, 3 };
int m = B.length;
// Call to function
findSwapValues(A, n, B, m);
}
}
// Contributed by Pramod Kumar
Python
504
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
def findSwapValues(A,B):
target=getTarget(A,B)
if target==0:
return
# Boolean variable used to reduce further iterations
# after the pair is found
flag=False
# Look for val1 and val2, such that
# val1 - val2 = (sumA -sumB) /2
val1,val2=0,0
for i in A:
for j in B:
if i-j == target:
val1=i
val2=j
# Set to True when pair is found
flag=True
break
if flag==True:
break
print val1,val2
return
# Driver code
A=[4,1,2,1,1,2]
B=[3,6,3,3]
# Call to function
findSwapValues(A,B)
# code contributed by sachin bisht
Output:
1 3
505
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
C/C++
506
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
// target 0 means, answer is not possible
if (target == 0)
return;
int i = 0, j = 0;
while (i < n && j < m) {
int diff = A[i] - B[j];
if (diff == target) {
cout << A[i] << " " << B[j];
return;
}
// Look for a greater value in A[]
else if (diff < target)
i++;
// Look for a greater value in B[]
else
j++;
}
}
// Driver code
int main()
{
int A[] = { 4, 1, 2, 1, 1, 2 };
int n = sizeof(A) / sizeof(A[0]);
int B[] = { 1, 6, 3, 3 };
int m = sizeof(B) / sizeof(B[0]);
findSwapValues(A, n, B, m);
return 0;
}
Java
507
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
508
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
j++;
}
}
// driver program
public static void main (String[] args)
{
int A[] = { 4, 1, 2, 1, 1, 2 };
int n = A.length;
int B[] = { 3, 6, 3, 3 };
int m = B.length;
// Call to function
findSwapValues(A, n, B, m);
}
}
// Contributed by Pramod Kumar
Python
509
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
Output:
2 3
Time Complexity :-
If arrays are sorted : O(n + m)
If arrays aren’t sorted : O(nlog(n) + mlog(m))
Method 4 (Hashing)
We can solve this problem in O(m+n) time and O(m) auxiliary space. Below are algorith-
mic steps.
510
Chapter 81. Find a pair of elements swapping which makes sum of two arrays same
Source
https://www.geeksforgeeks.org/find-a-pair-swapping-which-makes-sum-of-two-arrays-same/
511
Chapter 82
Input : sum = 28
Root of below tree
We have discussed different approaches to find a pair with given sum in below post.Find a
pair with given sum in a Balanced BST
In this post, hashing based solution is discussed. We traverse binary search tree by inorder
way and insert node’s value into a set. Also check for any node, difference between given
sum and node’s value in set, if it is found then pair exists otherwise it doesn’t exist.
512
Chapter 82. Find a pair with given sum in BST
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node* insert(Node* root, int key)
{
if (root == NULL)
return NewNode(key);
if (key < root->data)
root->left = insert(root->left, key);
else
root->right = insert(root->right, key);
return root;
}
bool findpairUtil(Node* root, int sum, unordered_set<int> &set)
{
if (root == NULL)
return false;
if (findpairUtil(root->left, sum, set))
return true;
if (set.find(sum - root->data) != set.end()) {
cout << "Pair is found ("
<< sum - root->data << ", "
<< root->data << ")" << endl;
return true;
}
else
set.insert(root->data);
return findpairUtil(root->right, sum, set);
}
void findPair(Node* root, int sum)
{
unordered_set<int> set;
if (!findpairUtil(root, sum, set))
cout << "Pairs do not exit" << endl;
}
// Driver code
int main()
{
Node* root = NULL;
513
Chapter 82. Find a pair with given sum in BST
Output:
Source
https://www.geeksforgeeks.org/find-pair-given-sum-bst/
514
Chapter 83
C++
515
Chapter 83. Find all triplets with zero sum
Java
516
Chapter 83. Find all triplets with zero sum
System.out.print(" ");
System.out.print(arr[j]);
System.out.print(" ");
System.out.print(arr[k]);
System.out.print("\n");
found = true;
}
}
}
}
// If no triplet with 0 sum found in array
if (found == false)
System.out.println(" not exist ");
}
// Driver code
public static void main(String[] args)
{
int arr[] = {0, -1, 2, -3, 1};
int n =arr.length;
findTriplets(arr, n);
}
}
//This code is contributed by
//Smitha Dinesh Semwal
Python3
517
Chapter 83. Find all triplets with zero sum
found = True
# If no triplet with 0 sum
# found in array
if (found == False):
print(" not exist ")
# Driver code
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
# This code is contributed by Smitha Dinesh Semwal
C#
518
Chapter 83. Find all triplets with zero sum
PHP
<?php
// A simple PHP program to
// find three elements whose
// sum is equal to zero
// Prints all triplets
// in arr[] with 0 sum
function findTriplets($arr, $n)
{
$found = true;
for ($i = 0; $i < $n - 2; $i++)
{
for ($j = $i + 1; $j < $n - 1; $j++)
{
for ($k = $j + 1; $k < $n; $k++)
{
if ($arr[$i] + $arr[$j] +
$arr[$k] == 0)
{
echo $arr[$i] , " ",
$arr[$j] , " ",
$arr[$k] ,"\n";
$found = true;
}
}
}
}
// If no triplet with 0
519
Chapter 83. Find all triplets with zero sum
0 -1 1
2 -3 1
C++
520
Chapter 83. Find all triplets with zero sum
{
// Find all pairs with sum equals to
// "-arr[i]"
unordered_set<int> s;
for (int j=i+1; j<n; j++)
{
int x = -(arr[i] + arr[j]);
if (s.find(x) != s.end())
{
printf("%d %d %d\n", x, arr[i], arr[j]);
found = true;
}
else
s.insert(arr[j]);
}
}
if (found == false)
cout << " No Triplet Found" << endl;
}
// Driver code
int main()
{
int arr[] = {0, -1, 2, -3, 1};
int n = sizeof(arr)/sizeof(arr[0]);
findTriplets(arr, n);
return 0;
}
-1 0 1
-3 2 1
521
Chapter 83. Find all triplets with zero sum
C++
522
Chapter 83. Find all triplets with zero sum
}
if (found == false)
cout << " No Triplet Found" << endl;
}
// Driven source
int main()
{
int arr[] = {0, -1, 2, -3, 1};
int n = sizeof(arr)/sizeof(arr[0]);
findTriplets(arr, n);
return 0;
}
Python3
523
Chapter 83. Find all triplets with zero sum
# if sum is greater than zero than
# decrement in right side
else:
r-=1
if (found == False):
print(" No Triplet Found")
# Driven source
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
# This code is contributed by Smitha Dinesh Semwal
PHP
<?php
// PHP program to find
// triplets in a given
// array whose sum is zero
// function to print
// triplets with 0 sum
function findTriplets($arr, $n)
{
$found = false;
// sort array elements
sort($arr);
for ($i = 0; $i < $n - 1; $i++)
{
// initialize left
// and right
$l = $i + 1;
$r = $n - 1;
$x = $arr[$i];
while ($l < $r)
{
if ($x + $arr[$l] +
$arr[$r] == 0)
{
// print elements if
// it's sum is zero
echo $x," ", $arr[$l],
524
Chapter 83. Find all triplets with zero sum
Output :
-3 1 2
-1 0 1
525
Chapter 83. Find all triplets with zero sum
Source
https://www.geeksforgeeks.org/find-triplets-array-whose-sum-equal-zero/
526
Chapter 84
A Naive Solution is to make all pairs one by one and check their modulo is equal to k or
not. If equals to k, then print that pair.
C++
527
Chapter 84. Find all pairs (a, b) in an array such that a % b = k
// Consider each and every pair
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Print if their modulo equals to k
if (i != j && arr[i] % arr[j] == k) {
cout << "(" << arr[i] << ", "
<< arr[j] << ")"
<< " ";
isPairFound = true;
}
}
}
return isPairFound;
}
// Driver program
int main()
{
int arr[] = { 2, 3, 5, 4, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
if (printPairs(arr, n, k) == false)
cout << "No such pair exists";
return 0;
}
Java
528
Chapter 84. Find all pairs (a, b) in an array such that a % b = k
}
}
}
return isPairFound;
}
// Driver method
public static void main(String args[])
{
int arr[] = { 2, 3, 5, 4, 7 };
int k = 3;
if (printPairs(arr, arr.length, k) == false)
System.out.println("No such pair exists");
}
}
Python3
529
Chapter 84. Find all pairs (a, b) in an array such that a % b = k
C#
PHP
<?php
530
Chapter 84. Find all pairs (a, b) in an array such that a % b = k
// PHP implementation to
// find such pairs
// Function to find pair
// such that (a % b = k)
function printPairs($arr, $n, $k)
{
$isPairFound = true;
// Consider each and every pair
for ($i = 0; $i < $n; $i++)
{
for ( $j = 0; $j < $n; $j++)
{
// Print if their modulo
// equals to k
if ($i != $j && $arr[$i] %
$arr[$j] == $k)
{
echo "(" , $arr[$i] , ", ",
$arr[$j] , ")", " ";
$isPairFound = true;
}
}
}
return $isPairFound;
}
// Driver Code
$arr = array(2, 3, 5, 4, 7);
$n = sizeof($arr);
$k = 3;
if (printPairs($arr, $n, $k) == false)
echo "No such pair exists";
// This code is contributed by ajit
?>
Output :
531
Chapter 84. Find all pairs (a, b) in an array such that a % b = k
1. If k itself is present in arr[], then k forms a pair with all elements arr[i] where k <
arr[i]. For all such arr[i], we have k % arr[i] = k.
2. For all elements greater than or equal to arr[i], we use following fact.
If arr[i] % arr[j] = k,
==> arr[i] = x * arr[j] + k
==> (arr[i] - k) = x * arr[j]
We find all divisors of (arr[i] - k)
and see if they are present in arr[].
C++
532
Chapter 84. Find all pairs (a, b) in an array such that a % b = k
533
Chapter 84. Find all pairs (a, b) in an array such that a % b = k
Java
534
Chapter 84. Find all pairs (a, b) in an array such that a % b = k
Output:
Time Complexity: O(n* sqrt(max)) where max is the maximum element in the array.
535
Chapter 84. Find all pairs (a, b) in an array such that a % b = k
Reference:
https://stackoverflow.com/questions/12732939/find-pairs-in-an-array-such-that-ab-k-where-k-is-a-given-integer
Improved By : Sam007, jit_t
Source
https://www.geeksforgeeks.org/find-pairs-b-array-b-k/
536
Chapter 85
Find all pairs (a,b) and (c,d) in array which satisfy ab = cd - GeeksforGeeks
Given an array of distinct integers, the task is to find two pairs (a, b) and (c, d) such that
ab = cd, where a, b, c and d are distinct elements.
Examples:
A Simple Solution is to run four loops to generate all possible quadruples of array element.
For every quadruple (a, b, c, d), check if a*b = c*d. Time complexity of this solution is
O(n4 ).
An Efficient Solution of this problem is to use hashing. We use product as key and pair
as value in hash table.
537
Chapter 85. Find all pairs (a,b) and (c,d) in array which satisfy ab = cd
C++
538
Chapter 85. Find all pairs (a,b) and (c,d) in array which satisfy ab = cd
return 0;
}
Java
539
Chapter 85. Find all pairs (a,b) and (c,d) in array which satisfy ab = cd
{
pair p = hp.get(prod);
System.out.println(arr[p.first]
+ " " + arr[p.second]
+ " " + "and" + " " +
arr[i] + " " + arr[j]);
found = true;
}
}
}
// If no pair find then print not found
if(found == false)
System.out.println("No pairs Found");
}
// Driver code
public static void main (String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int n = arr.length;
findPairs(arr, n);
}
}
// This code is contributed by akash1295.
Output:
1 6 and 2 3
1 8 and 2 4
2 6 and 3 4
3 8 and 4 6
Time Complexity : O(n2 ) assuming hash search and insert operations take O(1) time.
Related Article:
Find four elements a, b, c and d in an array such that a+b = c+d
Improved By : akash1295
Source
https://www.geeksforgeeks.org/find-pairs-ab-cd-array-satisfy-ab-cd/
540
Chapter 86
A simple solution is to one by one sort all rows and check all rows. If any row is completely
equal to given row that means current row is a permutation of given row. Time complexity
for this approach will be O(m*n log n).
An efficient approach is to use a hashing. Simply create a hash set for given row. After
hash set creation, traverse through remaining rows and for every row check if all of its
elements are present in hash set or not.
CPP
541
Chapter 86. Find all permuted rows of a given row in a matrix
Python3
542
Chapter 86. Find all permuted rows of a given row in a matrix
543
Chapter 86. Find all permuted rows of a given row in a matrix
permutatedRows(mat, m, n, r)
# This code is contributed
# by Upendra Singh Bartwal.
Output:
0, 2
CPP
Output:
0, 2
544
Chapter 86. Find all permuted rows of a given row in a matrix
Exercise :
Extend the above solution to work for input matrix where all elements of a row don’t have
be distinct. (Hit : We can use Hash Map instead of Hash Set)
Improved By : banavath santhosh
Source
https://www.geeksforgeeks.org/find-permuted-rows-given-row-matrix/
545
Chapter 87
Input:
dict = ["abb", "abc", "xyz", "xyy"];
pattern = "foo"
Output: [xyy abb]
Explanation:
xyy and abb have same character at index 1 and 2 like the pattern
Input:
dict = ["abb", "abc", "xyz", "xyy"];
pat = "mno"
Output: [abc xyz]
Explanation:
abc and xyz have all distinct characters, similar to the pattern
Input:
dict = ["abb", "abc", "xyz", "xyy"];
pattern = "aba"
Output: []
Explanation:
Pattern has same character at index 0 and 2.
No word in dictionary follows the pattern.
546
Chapter 87. Find all strings that match specific pattern in a dictionary
Input:
dict = ["abab", "aba", "xyz", "xyx"];
pattern = "aba"
Output: [aba xyx]
Explanation:
aba and xyx have same character at index 0 and 2 like the pattern
The idea is to encode the pattern in such a way that any word from the dictionary that
matches the pattern will have same hash as that of the pattern after encoding. We iterate
through all words in dictionary one by one and print the words that have same hash as that
of the pattern.
Below is C++ implementation of above idea –
547
Chapter 87. Find all strings that match specific pattern in a dictionary
{
// len is length of the pattern
int len = pattern.length();
// encode the string
string hash = encodeString(pattern);
// for each word in the dictionary
for (string word : dict)
{
// If size of pattern is same as size of current
// dictionary word and both pattern and the word
// has same hash, print the word
if (word.length() == len && encodeString(word) == hash)
cout << word << " " ;
}
}
// Driver code
int main()
{
unordered_set<string> dict = { "abb", "abc", "xyz", "xyy" };
string pattern = "foo";
findMatchedWords(dict, pattern);
return 0;
}
Output:
xyy abb
Source
https://www.geeksforgeeks.org/find-all-strings-that-match-specific-pattern-in-a-dictionary/
548
Chapter 88
Find any one of the multiple repeating elements in read only array - GeeksforGeeks
Given a read only array of size ( n+1 ), find one of the multiple repeating elements in the
array where the array contains integers only between 1 and n.
Read only array means that the contents of the array can’t be modified.
Examples:
Input : n = 5
arr[] = {1, 1, 2, 3, 5, 4}
Output : One of the numbers repeated in the array is: 1
Input : n = 10
arr[] = {10, 1, 2, 3, 5, 4, 9, 8, 5, 6, 4}
Output : One of the numbers repeated in the array is: 4 OR 5
Since, the size of the array is n+1 and elements ranges from 1 to n then it is confirmed that
there will be at least one repeating element.
A simple solution is to create a count array and store counts of all elements. As soon as
we encounter an element with count more than 1, we return it. This solution works in O(n)
time and requires O(n) extra space.
A space optimized solution is to break the given range (from 1 to n) into blocks of size
equal to sqrt(n). We maintain the count of elements belonging to each block for every block.
Now as the size of array is (n+1) and blocks are of size sqrt(n), then there will be one
such block whose size will be more than sqrt(n). For the block whose count is greater than
549
Chapter 88. Find any one of the multiple repeating elements in read only array
sqrt(n), we can use hashing for the elements of this block to find which element appears
more than once.
Explanation:
The method described above works because of the following two reasons:
1. There would always be a block which has count greater than sqrt(n) because of one
extra element. Even when one extra element has been added it will occupy a position
in one of the blocks only, making that block to be selected.
2. The selected block definitely has a repeating element. Consider that ith block is
selected. Size of the block is greater than sqrt(n) (Hence, it is selected) Maximum
distinct elements in this block = sqrt(n). Thus, size can be greater than sqrt(n) only
if there is a repeating element in range ( i*sqrt(n), (i+1)*sqrt(n) ].
Note: The last block formed may or may not have range equal to sqrt(n). Thus, checking
if this block has a repeating element will be different than other blocks. However, this
difficulty can be overcome from implementation point of view by initialising the selected
block with the last block. This is safe because at least one block has to get selected.
Below is the step by step algorithm to solve this problem:
550
Chapter 88. Find any one of the multiple repeating elements in read only array
551
Chapter 88. Find any one of the multiple repeating elements in read only array
}
}
// return -1 if no repeating element exists
return -1;
}
// Driver Program
int main()
{
// read only array, not to be modified
const int arr[] = { 1, 1, 2, 3, 5, 4 };
// array of size 6(n + 1) having
// elements between 1 and 5
int n = 5;
cout << "One of the numbers repeated in"
" the array is: "
<< findRepeatingNumber(arr, n) << endl;
}
Output:
Source
https://www.geeksforgeeks.org/find-one-multiple-repeating-elements-read-array/
552
Chapter 89
Input :
10 15 20 25 12
10 12 13 15
10 12 15 24 25 26
Output : 10 12 15
Input :
1 2 3 4 5
1 2 3 4 6 9 8
1 2 4 5 10
Output : 1 2 4
Method 1 : (Simple)
Use three-pointers to iterate the given three linked lists and if any element common print
that element.
Time complexity of the above solution will be O(N*N*N)
Method 2 : (Use Merge Sort)
In this method, we first sort the three lists and then we traverse the sorted lists to get the
intersection.
Following are the steps to be followed to get intersection of three lists:
1) Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this
post for details of this step.
553
Chapter 89. Find common elements in three linked lists
2) Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this
post for details of this step.
3) Sort the third Linked List using merge sort. This step takes O(pLogp) time. Refer this
post for details of this step.
3) Linearly scan three sorted lists to get the intersection. This step takes O(m + n + p)
time. This step can be implemented using the same algorithm as sorted arrays algorithm
discussed here.
Time complexity of this method is O(mLogm + nLogn + plogp) which is better than method
1’s time complexity.
Method 3 : (Hashing)
Following are the steps to be followed to get intersection of three lists using hashing:
1) Create an empty hash table. Iterate through the first linked list and mark all the element
frequency as 1 in the hash table. This step takes O(m) time.
2) Iterate through the second linked list and if current element frequency is 1 in hash table
mark it as 2. This step takes O(n) time.
3) Iterate the third linked list and if the current element frequency is 2 in hash table mark
it as 3. This step takes O(p) time.
4) Now iterate first linked list again to check the frequency of elements. if an element with
frequency three exist in hash table, it will be present in the intersection of three linked lists.
This step takes O(m) time.
Time complexity of this method is O(m + n + p) which is better than time complexity of
method 1 and 2.
Below is the C++ implementation of the above idea.
554
Chapter 89. Find common elements in three linked lists
}
/* print the common element in between
given three linked list*/
void Common(struct Node* head1,
struct Node* head2, struct Node* head3)
{
// Creating empty hash table;
unordered_map<int, int> hash;
struct Node* p = head1;
while (p != NULL) {
// set frequency by 1
hash[p->data] = 1;
p = p->next;
}
struct Node* q = head2;
while (q != NULL) {
// if the element is already exist in the
// linked list set its frequency 2
if (hash.find(q->data) != hash.end())
hash[q->data] = 2;
q = q->next;
}
struct Node* r = head3;
while (r != NULL) {
if (hash.find(r->data) != hash.end() &&
hash[r->data] == 2)
// if the element frquancy is 2 it means
// its present in both the first and second
// linked list set its frquancy 3
hash[r->data] = 3;
r = r->next;
}
for (auto x : hash) {
// if current frequency is 3 its means
// element is common in all the given
// linked list
if (x.second == 3)
555
Chapter 89. Find common elements in three linked lists
Output:
10 15 20
Source
https://www.geeksforgeeks.org/find-common-elements-in-three-linked-lists/
556
Chapter 90
Method 1: Using three nested loops. Check if an element of 1st row is present in all the
subsequent rows. Time Complexity of O(n3 ). Extra space could be required to handle the
duplicate elements.
Method 2: Sort all the rows of the matrix individually in increasing order. Then apply a
modified approach of the problem of finding common elements in 3 sorted arrays. Below
an implementation for the same is given.
557
Chapter 90. Find distinct elements common to all rows of a matrix
C++
558
Chapter 90. Find distinct elements common to all rows of a matrix
curr_index[i]++;
// if the element was not present at the column
// before to the 'curr_index' of the row
if (mat[i][curr_index[i]-1] != value)
present = false;
// if all elements of the row have
// been traversed
if (curr_index[i] == n)
{
f = 1;
break;
}
}
// if the 'value' is common to all the rows
if (present)
cout << value << " ";
// if any row have been completely traversed
// then no more common elements can be found
if (f == 1)
break;
}
}
// Driver program to test above
int main()
{
int mat[][MAX] = { {12, 1, 14, 3, 16},
{14, 2, 1, 3, 35},
{14, 1, 14, 3, 11},
{14, 25, 3, 2, 1},
{1, 18, 3, 21, 14}
};
int n = 5;
findAndPrintCommonElements(mat, n);
return 0;
}
Java
559
Chapter 90. Find distinct elements common to all rows of a matrix
class GFG {
// function to individually sort
// each row in increasing order
public static void sortRows(int mat[][], int n)
{
for (int i=0; i<n; i++)
Arrays.sort(mat[i]);
}
// function to find all the common elements
public static void findAndPrintCommonElements(int mat[][],
int n)
{
// sort rows individually
sortRows(mat, n);
// current column index of each row is stored
// from where the element is being searched in
// that row
int curr_index[] = new int[n];
int f = 0;
for (; curr_index[0]<n; curr_index[0]++)
{
// value present at the current column index
// of 1st row
int value = mat[0][curr_index[0]];
boolean present = true;
// 'value' is being searched in all the
// subsequent rows
for (int i=1; i<n; i++)
{
// iterate through all the elements of
// the row from its current column index
// till an element greater than the 'value'
// is found or the end of the row is
// encountered
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
curr_index[i]++;
// if the element was not present at the
// column before to the 'curr_index' of the
// row
560
Chapter 90. Find distinct elements common to all rows of a matrix
Output:
1 3 14
Time Complexity: O(n2 log n), each row of size n requires O(nlogn) for sorting and there
are total n rows.
Auxiliary Space : O(n) to store current column indexes for each row.
561
Chapter 90. Find distinct elements common to all rows of a matrix
562
Chapter 90. Find distinct elements common to all rows of a matrix
us.erase(*itr);
// if size of 'us' becomes 0,
// then there are no common elements
if (us.size() == 0)
break;
}
// print the common elements
unordered_set<int>:: iterator itr;
for (itr=us.begin(); itr!=us.end(); itr++)
cout << *itr << " ";
}
// Driver program to test above
int main()
{
int mat[][MAX] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
int n = 4;
findAndPrintCommonElements(mat, n);
return 0;
}
Output:
3 2
Source
https://www.geeksforgeeks.org/find-distinct-elements-common-rows-matrix/
563
Chapter 91
Find duplicates in a given array when elements are not limited to a range - GeeksforGeeks
Given an array of n integers. The task is to print the duplicates in the given array. If there
are no duplicates then print -1.
Examples:
564
Chapter 91. Find duplicates in a given array when elements are not limited to a range
Java
565
Chapter 91. Find duplicates in a given array when elements are not limited to a range
Output:
12 11 5
566
Chapter 91. Find duplicates in a given array when elements are not limited to a range
Source
https://www.geeksforgeeks.org/find-duplicates-given-array-elements-not-limited-range/
567
Chapter 92
Find elements which are present in first array and not in second - GeeksforGeeks
Given two arrays, the task is that we find numbers which are present in first array, but not
present in the second array.
Examples :
Method 1 (Simple)
A Naive Approach is to use two loops and check element which not present in second array.
C++
568
Chapter 92. Find elements which are present in first array and not in second
Java
569
Chapter 92. Find elements which are present in first array and not in second
break;
if (j == m)
System.out.print(a[i] + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int a[] = { 1, 2, 6, 3, 4, 5 };
int b[] = { 2, 4, 3, 1, 0 };
int n = a.length;
int m = b.length;
findMissing(a, b, n, m);
}
}
// This code is contributed
// by Anant Agarwal.
C#
570
Chapter 92. Find elements which are present in first array and not in second
}
// Driver code
public static void Main()
{
int []a = {1, 2, 6, 3, 4, 5};
int []b = {2, 4, 3, 1, 0};
int n = a.Length;
int m = b.Length;
findMissing(a, b, n, m);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP simple program to find
// elements which are not
// present in second array
// Function for finding
// elements which are there
// in a[] but not in b[].
function findMissing( $a, $b, $n, $m)
{
for ( $i = 0; $i < $n; $i++)
{
$j;
for ($j = 0; $j < $m; $j++)
if ($a[$i] == $b[$j])
break;
if ($j == $m)
echo $a[$i] , " ";
}
}
// Driver code
$a = array( 1, 2, 6, 3, 4, 5 );
$b = array( 2, 4, 3, 1, 0 );
$n = count($a);
$m = count($b);
findMissing($a, $b, $n, $m);
571
Chapter 92. Find elements which are present in first array and not in second
Output :
6 5
572
Chapter 92. Find elements which are present in first array and not in second
Output :
5 6
Source
https://www.geeksforgeeks.org/find-elements-present-first-array-not-second/
573
Chapter 93
Find four elements a, b, c and d in an array such that a+b = c+d - GeeksforGeeks
Given an array of distinct integers, find if there are two pairs (a, b) and (c, d) such that
a+b = c+d, and a, b, c and d are distinct elements. If there are multiple answers, then
print any of them.
Example:
Input: {3, 4, 7, 1, 2, 9, 8}
Output: (3, 8) and (4, 7)
Explanation: 3+8 = 4+7
574
Chapter 93. Find four elements a, b, c and d in an array such that a+b = c+d
Loop i = 0 to n-1 :
Loop j = i + 1 to n-1 :
calculate sum
If in hash table any index already exist
Then print (i, j) and previous pair
from hash table
Else update hash table
EndLoop;
EndLoop;
Below are implementations of above idea. In below implementation, map is used instead of
hash. Time complexity of map insert and search is actually O(Log n) instead of O(1). So
below implementation is O(n2 Log n).
C/C++
575
Chapter 93. Find four elements a, b, c and d in an array such that a+b = c+d
return true;
}
}
}
cout << "No pairs found";
return false;
}
// Driver program
int main()
{
int arr[] = {3, 4, 7, 1, 2, 9, 8};
int n = sizeof arr / sizeof arr[0];
findPairs(arr, n);
return 0;
}
Java
576
Chapter 93. Find four elements a, b, c and d in an array such that a+b = c+d
{
// If sum of current pair is not in hash,
// then store it and continue to next pair
int sum = arr[i]+arr[j];
if (!map.containsKey(sum))
map.put(sum,new pair(i,j));
else // Else (Sum already present in hash)
{
// Find previous pair
pair p = map.get(sum);
// Since array elements are distinct, we don't
// need to check if any element is common among pairs
System.out.println("("+arr[p.first]+", "+arr[p.second]+
") and ("+arr[i]+", "+arr[j]+")");
return true;
}
}
}
return false;
}
// Testing program
public static void main(String args[])
{
int arr[] = {3, 4, 7, 1, 2, 9, 8};
ArrayElements a = new ArrayElements();
a.findPairs(arr);
}
}
// This code is contributed by Aakash Hasija
Python
577
Chapter 93. Find four elements a, b, c and d in an array such that a+b = c+d
Output:
578
Chapter 93. Find four elements a, b, c and d in an array such that a+b = c+d
Source
https://www.geeksforgeeks.org/find-four-elements-a-b-c-and-d-in-an-array-such-that-ab-cd/
579
Chapter 94
Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution) - GeeksforGeeks
Given an array of integers, find any one combination of four elements in the array whose
sum is equal to a given value X.
For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and X = 23, then your function
should print “3 5 7 8” (3 + 5 + 7 + 8 = 23).
We have discussed a O(n^3) algorithm in the previous post on this topic. The problem can
be solved in O(n^2Logn) time with the help of auxiliary space.
Thanks to itsnimish for suggesting this method. Following is the detailed process.
Let the input array be A[].
1) Create an auxiliary array aux[] and store sum of all possible pairs in aux[]. The size of
aux[] will be n*(n-1)/2 where n is the size of A[].
2) Sort the auxiliary array aux[].
3) Now the problem reduces to find two elements in aux[] with sum equal to X. We can use
method 1 ofthis postto find the two elements efficiently. There is following important point
to note though. An element of aux[] represents a pair from A[]. While picking two elements
from aux[], we must check whether the two elements have an element of A[] in common. For
example, if first element sum of A[1] and A[2], and second element is sum of A[2] and A[4],
then these two elements of aux[] don’t represent four distinct elements of input array A[].
Following is C implementation of this method.
#include <stdio.h>
#include <stdlib.h>
580
Chapter 94. Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)
// The following structure is needed to store pair sums in aux[]
struct pairSum
{
int first; // index (int A[]) of first element in pair
int sec; // index of second element in pair
int sum; // sum of the pair
};
// Following function is needed for library function qsort()
int compare (const void *a, const void * b)
{
return ( (*(pairSum *)a).sum - (*(pairSum*)b).sum );
}
// Function to check if two given pairs have any common element or not
bool noCommon(struct pairSum a, struct pairSum b)
{
if (a.first == b.first || a.first == b.sec ||
a.sec == b.first || a.sec == b.sec)
return false;
return true;
}
// The function finds four elements with given sum X
void findFourElements (int arr[], int n, int X)
{
int i, j;
// Create an auxiliary array to store all pair sums
int size = (n*(n-1))/2;
struct pairSum aux[size];
/* Generate all possible pairs from A[] and store sums
of all possible pairs in aux[] */
int k = 0;
for (i = 0; i < n-1; i++)
{
for (j = i+1; j < n; j++)
{
aux[k].sum = arr[i] + arr[j];
aux[k].first = i;
aux[k].sec = j;
k++;
}
}
581
Chapter 94. Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)
// Sort the aux[] array using library function for sorting
qsort (aux, size, sizeof(aux[0]), compare);
// Now start two index variables from two corners of array
// and move them toward each other.
i = 0;
j = size-1;
while (i < size && j >=0 )
{
if ((aux[i].sum + aux[j].sum == X) && noCommon(aux[i], aux[j]))
{
printf ("%d, %d, %d, %d\n", arr[aux[i].first], arr[aux[i].sec],
arr[aux[j].first], arr[aux[j].sec]);
return;
}
else if (aux[i].sum + aux[j].sum < X)
i++;
else
j--;
}
}
// Driver program to test above function
int main()
{
int arr[] = {10, 20, 30, 40, 1, 2};
int n = sizeof(arr) / sizeof(arr[0]);
int X = 91;
findFourElements (arr, n, X);
return 0;
}
Output:
20, 1, 30, 40
Please note that the above code prints only one quadruple. If we remove the return statement
and add statements “i++; j–;”, then it prints same quadruple five times. The code can
modified to print all quadruples only once. It has been kept this way to keep it simple.
Time complexity: The step 1 takes O(n^2) time. The second step is sorting an array of
size O(n^2). Sorting can be done in O(n^2Logn) time using merge sort or heap sort or
any other O(nLogn) algorithm. The third step takes O(n^2) time. So overall complexity is
O(n^2Logn).
Auxiliary Space: O(n^2). The big size of auxiliary array can be a concern in this method.
582
Chapter 94. Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)
2. Traverse through all pairs again and search for X – (current pair sum) in the hash
table.
3. If a pair is found with the required sum, then make sure that all elements are distinct
array elements and an element is not considered more than once.
583
Chapter 94. Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)
Source
https://www.geeksforgeeks.org/find-four-elements-that-sum-to-a-given-value-set-2/
584
Chapter 95
Find four elements that sum to a given value | Set 3 (Hashmap) - GeeksforGeeks
Given an array of integers, Check if there exist four elements at different indexes in the
array whose sum is equal to a given value k.
For example, if the given array is {1 5 1 0 6 0} and k = 7, then your function should print
“YES” as (1+5+1+0=7).
Examples:
Input : arr[] = {1 5 1 0 6 0}
k = 7
Output : YES
Loop i = 0 to n-1 :
Loop j = i + 1 to n-1
585
Chapter 95. Find four elements that sum to a given value | Set 3 (Hashmap)
586
Chapter 95. Find four elements that sum to a given value | Set 3 (Hashmap)
Output:
YES
Source
https://www.geeksforgeeks.org/find-four-elements-sum-given-value-set-3-hashmap/
587
Chapter 96
Find if there is a pair in root to a leaf path with sum equals to root’s data - GeeksforGeeks
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in
pair is equal to root’s data. For example, in below tree (2, 3) and (4, 1) are pairs with sum
equals to root’s data.
588
Chapter 96. Find if there is a pair in root to a leaf path with sum equals to root’s data
The idea is based on hashing and tree traversal. The idea is similar to method 2 of array
pair sum problem.
589
Chapter 96. Find if there is a pair in root to a leaf path with sum equals to root’s data
590
Chapter 96. Find if there is a pair in root to a leaf path with sum equals to root’s data
return res;
}
// A wrapper over printPathUtil()
bool isPathSum(Node *root)
{
// create an empty hash table
unordered_set<int> s;
// Recursively check in left and right subtrees.
return printPathUtil(root->left, s, root->data) ||
printPathUtil(root->right, s, root->data);
}
// Driver program to run the case
int main()
{
struct Node *root = newnode(8);
root->left = newnode(5);
root->right = newnode(4);
root->left->left = newnode(9);
root->left->right = newnode(7);
root->left->right->left = newnode(1);
root->left->right->right = newnode(12);
root->left->right->right->right = newnode(2);
root->right->right = newnode(11);
root->right->right->left = newnode(3);
isPathSum(root)? cout << "Yes" : cout << "No";
return 0;
}
Output:
Yes
Time Complexity : O(n) under the assumption that hash search, insert and erase take O(1)
time.
Exercise : Extend the above solution to print all root to leaf paths that have a pair with
sum equals to root’s data.
Source
https://www.geeksforgeeks.org/find-pair-root-leaf-path-sum-equals-roots-data/
591
Chapter 97
Input :
mat[][] = { 1 0 0 1 0
0 0 1 0 1
0 0 0 1 0
1 0 1 0 1}
Output : Yes
as there exists-
1 0 1
0 1 0
1 0 1
for i = 1 to rows
for j = 1 to columns
if matrix[i][j] == 1
for k=i+1 to rows
592
Chapter 97. Find if there is a rectangle in binary matrix with corners as 1
593
Chapter 97. Find if there is a rectangle in binary matrix with corners as 1
Output:
Yes
Efficient Approach
– Scan from top to down, line by line
– For each line, remember each combination of 2 1’s and push that into a hash-set
– If we ever find that combination again in a later line, we get our rectangle
– Time Complexity of this solution- O(n*m^2)
594
Chapter 97. Find if there is a rectangle in binary matrix with corners as 1
Output:
Yes
Improved By : abhishekahuja02
Source
https://www.geeksforgeeks.org/find-rectangle-binary-matrix-corners-1/
595
Chapter 98
Input: {4, 2, 0, 1, 6}
Output: true
There is a subarray with zero sum from index 2 to 2.
Input: {-3, 2, 3, 1, 6}
Output: false
There is no subarray with zero sum.
A simple solution is to consider all subarrays one by one and check the sum of every
subarray. We can run two loops: the outer loop picks a starting point i and the inner loop
tries all subarrays starting from i (See thisfor implementation). Time complexity of this
method is O(n2 ).
We can also use hashing. The idea is to iterate through the array and for every element
arr[i], calculate sum of elements form 0 to i (this can simply be done as sum += arr[i]). If
the current sum has been seen before, then there is a zero sum array. Hashing is used to
store the sum values, so that we can quickly store sum and find out whether the current
sum is seen before or not.
Example :
596
Chapter 98. Find if there is a subarray with 0 sum
C++
597
Chapter 98. Find if there is a subarray with 0 sum
int n = sizeof(arr)/sizeof(arr[0]);
if (subArrayExists(arr, n))
cout << "Found a subarray with 0 sum";
else
cout << "No Such Sub Array Exists!";
return 0;
}
Java
598
Chapter 98. Find if there is a subarray with 0 sum
C#
599
Chapter 98. Find if there is a subarray with 0 sum
Output :
Time Complexity of this solution can be considered as O(n) under the assumption that we
have good hashing function that allows insertion and retrieval operations in O(1) time.
Exercise:
Extend the above program to print starting and ending indexes of all subarrays with 0 sum.
This article is contributed by Chirag Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007
Source
https://www.geeksforgeeks.org/find-if-there-is-a-subarray-with-0-sum/
600
Chapter 99
601
Chapter 99. Find k numbers with most occurrences in the given array
602
Chapter 99. Find k numbers with most occurrences in the given array
Output:
Time Complexity: O(dlogd), where d is the count of distinct elements in the array.
Auxiliary Space: O(d), where d is the count of distinct elements in the array.
Method 2: Create the array freq_arr[] as described in Method 1 of this post. Now,
build the max heap using elements of this freq_arr[]. The root of the max heap should
be the most frequent number and in case of conflicts the larger number gets the preference.
Now remove the top k numbers of this max heap. C++ STL priority_queue has been used
as max heap.
603
Chapter 99. Find k numbers with most occurrences in the given array
Output:
Time Complexity: O(klogd), where d is the count of distinct elements in the array.
Auxiliary Space: O(d), where d is the count of distinct elements in the array.
References: https://www.careercup.com/question?id=5082885552865280
Source
https://www.geeksforgeeks.org/find-k-numbers-occurrences-given-array/
604
Chapter 100
Constraints:
1 � number of elements in the set � 1000
INT_MIN � each element in the set � INT_MAX
Examples :
C++
605
Chapter 100. Find largest d in array such that a + b + c = d
606
Chapter 100. Find largest d in array such that a + b + c = d
return INT_MIN;
}
// Driver Code
int main()
{
// Set of distinct Integers
int S[] = { 2, 3, 5, 7, 12 };
int n = sizeof(S) / sizeof(S[0]);
int ans = findLargestd(S, n);
if (ans == INT_MIN)
cout << "No Solution" << endl;
else
cout << "Largest d such that a + b + "
<< "c = d is " << ans << endl;
return 0;
}
Java
607
Chapter 100. Find largest d in array such that a + b + c = d
continue;
for (int k = j + 1; k < n; k++)
{
if (i == k)
continue;
for (int l = k + 1; l < n; l++)
{
if (i == l)
continue;
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest d since we are
// iterating in descending order
if (S[i] == S[j] + S[k] + S[l])
{
found = true;
return S[i];
}
}
}
}
}
if (found == false)
return Integer.MAX_VALUE;
return -1;
}
// Driver Code
public static void main(String []args)
{
// Set of distinct Integers
int []S = new int[]{ 2, 3, 5, 7, 12 };
int n = S.length;
int ans = findLargestd(S, n);
if (ans == Integer.MAX_VALUE)
System.out.println("No Solution");
else
System.out.println("Largest d such that " +
"a + " + "b + c = d is " +
ans );
608
Chapter 100. Find largest d in array such that a + b + c = d
}
}
// This code is contributed by Sam007
Python3
609
Chapter 100. Find largest d in array such that a + b + c = d
# Set of distinct Integers
S = [ 2, 3, 5, 7, 12 ]
n = len(S)
ans = findLargestd(S, n)
if (ans == -1) :
print ("No Solution")
else :
print ("Largest d such that a + b +" ,
"c = d is" ,ans)
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
610
Chapter 100. Find largest d in array such that a + b + c = d
if (i == k)
continue;
for (int l = k + 1; l < n; l++)
{
if (i == l)
continue;
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest dsince we are
// iterating in descending order
if (S[i] == S[j] + S[k] + S[l])
{
found = true;
return S[i];
}
}
}
}
}
if (found == false)
return int.MaxValue;
return -1;
}
// Driver Code
public static void Main()
{
// Set of distinct Integers
int []S = new int[]{ 2, 3, 5, 7, 12 };
int n = S.Length;
int ans = findLargestd(S, n);
if (ans == int.MaxValue)
Console.WriteLine( "No Solution");
else
Console.Write("Largest d such that a + " +
"b + c = d is " + ans );
}
}
// This code is contributed by Sam007
611
Chapter 100. Find largest d in array such that a + b + c = d
PHP
<?php
// PHP Program to find the largest
// d such that d = a + b + c
function findLargestd( $S, $n)
{
$found = false;
// sort the array in
// ascending order
sort($S);
// iterating from backwards to
// find the required largest d
for ( $i = $n - 1; $i >= 0; $i--)
{
for ( $j = 0; $j < $n; $j++)
{
// since all four a, b, c,
// d should be distinct
if ($i == $j)
continue;
for ( $k = $j + 1; $k < $n; $k++)
{
if ($i == $k)
continue;
for ( $l = $k + 1; $l < $n; $l++)
{
if ($i == $l)
continue;
// if the current combination
// of j, k, l in the set is
// equal to S[i] return this
// value as this would be the
// largest d since we are
// iterating in descending order
if ($S[$i] == $S[$j] + $S[$k] + $S[$l])
{
$found = true;
return $S[$i];
}
}
612
Chapter 100. Find largest d in array such that a + b + c = d
}
}
}
if ($found == false)
return PHP_INT_MIN;
}
// Driver Code
// Set of distinct Integers
$S = array( 2, 3, 5, 7, 12 );
$n = count($S);
$ans = findLargestd($S, $n);
if ($ans == PHP_INT_MIN)
echo "No Solution" ;
else
echo "Largest d such that a + b + " ,
"c = d is " , $ans ;
// This code is contributed by anuj_67.
?>
Output :
C++
613
Chapter 100. Find largest d in array such that a + b + c = d
614
Chapter 100. Find largest d in array such that a + b + c = d
Output:
12
The overall time complexity for this efficient approach is O(N2 ) (where N is the size of the
set).
Improved By : Nishant Tanwar, Sam007, vt_m, manishshaw1
Source
https://www.geeksforgeeks.org/find-largest-d-in-array-such-that-a-b-c-d/
615
Chapter 101
One simple solution is to iterate over arrays and check element by element and flag the
missing element when an unmatch is found, but this solution requires linear time over size
of array.
Another efficient solution is based onbinary searchapproach. Algorithm steps are as
follows:
1. Start binary search in bigger array and get mid as (lo + hi) / 2
2. If value from both array is same then missing element must be in right part so set lo
as mid
3. Else set hi as mid because missing element must be in left part of bigger array if mid
elements are not equal.
616
Chapter 101. Find lost element from a duplicated array
4. Special case are handled separately as for single element and zero element array, single
element itself will be the missing element.
If first element itself is not equal then that element will be the missing element./li>
C++
617
Chapter 101. Find lost element from a duplicated array
// missing element will be at hi index of
// bigger array
return arr1[hi];
}
// This function mainly does basic error checking
// and calls findMissingUtil
void findMissing(int arr1[], int arr2[], int M, int N)
{
if (N == M-1)
cout << "Missing Element is "
<< findMissingUtil(arr1, arr2, M) << endl;
else if (M == N-1)
cout << "Missing Element is "
<< findMissingUtil(arr2, arr1, N) << endl;
else
cout << "Invalid Input";
}
// Driver Code
int main()
{
int arr1[] = {1, 4, 5, 7, 9};
int arr2[] = {4, 5, 7, 9};
int M = sizeof(arr1) / sizeof(int);
int N = sizeof(arr2) / sizeof(int);
findMissing(arr1, arr2, M, N);
return 0;
}
Java
618
Chapter 101. Find lost element from a duplicated array
int N)
{
// special case, for only element
// which is missing in second array
if (N == 1)
return arr1[0];
// special case, for first
// element missing
if (arr1[0] != arr2[0])
return arr1[0];
// Initialize current corner points
int lo = 0, hi = N - 1;
// loop until lo < hi
while (lo < hi) {
int mid = (lo + hi) / 2;
// If element at mid indices are
// equal then go to right subarray
if (arr1[mid] == arr2[mid])
lo = mid;
else
hi = mid;
// if lo, hi becomes
// contiguous, break
if (lo == hi - 1)
break;
}
// missing element will be at hi
// index of bigger array
return arr1[hi];
}
// This function mainly does basic error
// checking and calls findMissingUtil
void findMissing(int arr1[], int arr2[],
int M, int N)
{
if (N == M - 1)
System.out.println("Missing Element is "
+ findMissingUtil(arr1, arr2, M) + "\n");
else if (M == N - 1)
System.out.println("Missing Element is "
+ findMissingUtil(arr2, arr1, N) + "\n");
619
Chapter 101. Find lost element from a duplicated array
else
System.out.println("Invalid Input");
}
// Driver Code
public static void main(String args[])
{
MissingNumber obj = new MissingNumber();
int arr1[] = { 1, 4, 5, 7, 9 };
int arr2[] = { 4, 5, 7, 9 };
int M = arr1.length;
int N = arr2.length;
obj.findMissing(arr1, arr2, M, N);
}
}
// This code is contributed by Anshika Goyal.
Python3
620
Chapter 101. Find lost element from a duplicated array
C#
621
Chapter 101. Find lost element from a duplicated array
class GFG {
/* Funtion to find missing element based
on binary search approach. arr1[] is of
larger size and N is size of it.arr1[] and
arr2[] are assumed to be in same order. */
static int findMissingUtil(int []arr1,
int []arr2, int N)
{
// special case, for only element
// which is missing in second array
if (N == 1)
return arr1[0];
// special case, for first
// element missing
if (arr1[0] != arr2[0])
return arr1[0];
// Initialize current corner points
int lo = 0, hi = N - 1;
// loop until lo < hi
while (lo < hi) {
int mid = (lo + hi) / 2;
// If element at mid indices are
// equal then go to right subarray
if (arr1[mid] == arr2[mid])
lo = mid;
else
hi = mid;
// if lo, hi becomes
// contiguous, break
if (lo == hi - 1)
break;
}
// missing element will be at hi
// index of bigger array
return arr1[hi];
}
// This function mainly does basic error
// checking and calls findMissingUtil
static void findMissing(int []arr1, int []arr2,
622
Chapter 101. Find lost element from a duplicated array
int M, int N)
{
if (N == M - 1)
Console.WriteLine("Missing Element is "
+ findMissingUtil(arr1, arr2, M) + "\n");
else if (M == N - 1)
Console.WriteLine("Missing Element is "
+ findMissingUtil(arr2, arr1, N) + "\n");
else
Console.WriteLine("Invalid Input");
}
// Driver Code
public static void Main()
{
int []arr1 = { 1, 4, 5, 7, 9 };
int []arr2 = { 4, 5, 7, 9 };
int M = arr1.Length;
int N = arr2.Length;
findMissing(arr1, arr2, M, N);
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find missing
// element from same arrays
// (except one missing element)
// Function to find missing
// element based on binary
// search approach. arr1[]
// is of larger size and
// N is size of it. arr1[]
// and arr2[] are assumed
// to be in same order.
function findMissingUtil($arr1, $arr2, $N)
{
// special case, for only
// element which is
// missing in second array
if ($N == 1)
return $arr1[0];
623
Chapter 101. Find lost element from a duplicated array
624
Chapter 101. Find lost element from a duplicated array
else
echo "Invalid Input";
}
// Driver Code
$arr1 = array(1, 4, 5, 7, 9);
$arr2 = array(4, 5, 7, 9);
$M = count($arr1);
$N = count($arr2);
findMissing($arr1, $arr2, $M, $N);
// This code is contributed by anuj_67.
?>
Output :
Missing Element is 1
CPP
625
Chapter 101. Find lost element from a duplicated array
res = res^arr2[i];
cout << "Missing element is " << res;
}
// Driver Code
int main()
{
int arr1[] = {4, 1, 5, 9, 7};
int arr2[] = {7, 5, 9, 4};
int M = sizeof(arr1) / sizeof(int);
int N = sizeof(arr2) / sizeof(int);
findMissing(arr1, arr2, M, N);
return 0;
}
Java
626
Chapter 101. Find lost element from a duplicated array
}
// Driver Code
public static void main(String args[])
{
Missing obj = new Missing();
int arr1[] = { 4, 1, 5, 9, 7 };
int arr2[] = { 7, 5, 9, 4 };
int M = arr1.length;
int N = arr2.length;
obj.findMissing(arr1, arr2, M, N);
}
}
// This code is contributed by Anshika Goyal.
Python3
627
Chapter 101. Find lost element from a duplicated array
findMissing(arr1, arr2, M, N)
# This code is contributed
# by Smitha Dinesh Semwal
C#
628
Chapter 101. Find lost element from a duplicated array
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP program to find missing
// element from one array
// such that it has all elements
// of other array except
// one. Elements in two arrays
// can be in any order.
// This function mainly does
// XOR of all elements
// of arr1[] and arr2[]
function findMissing($arr1, $arr2,
$M, $N)
{
if ($M != $N - 1 && $N != $M - 1)
{
echo "Invalid Input";
return;
}
// Do XOR of all element
$res = 0;
for ($i = 0; $i < $M; $i++)
$res = $res ^ $arr1[$i];
for ($i = 0; $i < $N; $i++)
$res = $res ^ $arr2[$i];
echo "Missing element is ", $res;
}
// Driver Code
$arr1 = array(4, 1, 5, 9, 7);
$arr2 = array(7, 5, 9, 4);
$M = sizeof($arr1);
$N = sizeof($arr2);
findMissing($arr1, $arr2, $M, $N);
// This code is contributed by aj_36
?>
Output :
629
Chapter 101. Find lost element from a duplicated array
Missing Element is 1
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t, vt_m
Source
https://www.geeksforgeeks.org/find-lost-element-from-a-duplicated-array/
630
Chapter 102
1. Use Sorting : Sort the array, then do binary search for ‘low’. Once location of low
is find, start traversing array from that location and keep printing all missing numbers.
C++
631
Chapter 102. Find missing elements of a range
632
Chapter 102. Find missing elements of a range
Java
633
Chapter 102. Find missing elements of a range
}
// Utility function to find ceil index of given element
static int ceilindex(int ar[], int val, int low, int high)
{
if (val < ar[0])
return 0;
if (val > ar[ar.length - 1])
return ar.length;
int mid = (low + high) / 2;
if (ar[mid] == val)
return mid;
if (ar[mid] < val)
{
if (mid + 1 < high && ar[mid + 1] >= val)
return mid + 1;
return ceilindex(ar, val, mid + 1, high);
}
else
{
if (mid - 1 >= low && ar[mid - 1] < val)
return mid;
return ceilindex(ar, val, low, mid - 1);
}
}
// Driver program to test above function
public static void main(String[] args)
{
int arr[] = { 1, 3, 5, 4 };
int low = 1, high = 10;
printMissing(arr, low, high);
}
}
// This code is contributed by Rishabh Mahrsee
Output:
2 6 7 8 9 10
2. Use Hashing : Create a hash table and insert all array items into the hash table.
Once all items are in hash table, traverse through the range and print all missing
elements.
C++
634
Chapter 102. Find missing elements of a range
Java
635
Chapter 102. Find missing elements of a range
Output:
2 6 7 8 9 10
Source
https://www.geeksforgeeks.org/find-missing-elements-of-a-range/
636
Chapter 103
{ "A", "C" },
{ "B", "C" },
{ "C", "F" },
{ "D", "E" },
{ "E", "F" },
{ "F", "F" }
Write a function to get no of employees under each manager in the hierarchy not just their
direct reports. It may be assumed that an employee directly reports to only one manager.
In the above dictionary the root node/ceo is listed as reporting to himself.
Output should be a Dictionary that contains following.
A - 0
B - 0
C - 2
D - 0
E - 1
F - 5
637
Chapter 103. Find number of Employees Under every Employee
638
Chapter 103. Find number of Employees Under every Employee
{
Map<String, String> dataSet = new HashMap<String, String>();
dataSet.put("A", "C");
dataSet.put("B", "C");
dataSet.put("C", "F");
dataSet.put("D", "E");
dataSet.put("E", "F");
dataSet.put("F", "F");
populateResult(dataSet);
System.out.println("result = " + result);
}
// This function populates 'result' for given input 'dataset'
private static void populateResult(Map<String, String> dataSet)
{
// To store reverse of original map, each key will have 0
// to multiple values
Map<String, List<String>> mngrEmpMap =
new HashMap<String, List<String>>();
// To fill mngrEmpMap, iterate through the given map
for (Map.Entry<String,String> entry: dataSet.entrySet())
{
String emp = entry.getKey();
String mngr = entry.getValue();
if (!emp.equals(mngr)) // excluding emp-emp entry
{
// Get the previous list of direct reports under
// current 'mgr' and add the current 'emp' to the list
List<String> directReportList = mngrEmpMap.get(mngr);
// If 'emp' is the first employee under 'mgr'
if (directReportList == null)
directReportList = new ArrayList<String>();
directReportList.add(emp);
// Replace old value for 'mgr' with new
// directReportList
mngrEmpMap.put(mngr, directReportList);
}
}
// Now use manager-Emp map built above to populate result
// with use of populateResultUtil()
// note- we are iterating over original emp-manager map and
639
Chapter 103. Find number of Employees Under every Employee
Output:
This article is contributed by Chandan Prakash. 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/find-number-of-employees-under-every-manager/
640
Chapter 104
Given an array of size N. Find the number of pairs (i, j) such that XOR =
0, and 1 <= i < j <= N.
Examples :
to the answer.
641
Chapter 104. Find number of pairs in an array such that their XOR is 0
642
Chapter 104. Find number of pairs in an array such that their XOR is 0
Java
643
Chapter 104. Find number of pairs in an array such that their XOR is 0
Python3
644
Chapter 104. Find number of pairs in an array such that their XOR is 0
C#
645
Chapter 104. Find number of pairs in an array such that their XOR is 0
PHP
<?php
// PHP program to find number
// of pairs in an array such
// that their XOR is 0
// Function to calculate
// the count
function calculate($a, $n)
{
// Sorting the list using
// built in function
sort($a);
$count = 1;
$answer = 0;
// Traversing through the
// elements
for ($i = 1; $i < $n; $i++)
{
646
Chapter 104. Find number of pairs in an array such that their XOR is 0
Output :
647
Chapter 104. Find number of pairs in an array such that their XOR is 0
C++
Python 3
648
Chapter 104. Find number of pairs in an array such that their XOR is 0
PHP
Output :
649
Chapter 104. Find number of pairs in an array such that their XOR is 0
Source
https://www.geeksforgeeks.org/find-number-pairs-array-xor-0/
650
Chapter 105
A naive approach is to pick an element and then check for each pair product if equal to
that number and update the max if the number is maximum,repeat until whole array gets
651
Chapter 105. Find pair with greatest product in array
C++
Java
652
Chapter 105. Find pair with greatest product in array
C#
653
Chapter 105. Find pair with greatest product in array
PHP
<?php
// PHP program to find a pair
// with product in given array.
// Function to find
// greatest number
function findGreatest($arr , $n)
{
$result = -1;
for ($i = 0; $i < $n ; $i++)
for ($j = 0; $j < $n-1; $j++)
for ($k = $j+1 ; $k < $n ; $k++)
if ($arr[$j] * $arr[$k] == $arr[$i])
$result = max($result, $arr[$i]);
return $result;
}
// Driver code
$arr = array(30, 10, 9, 3, 35);
$n = count($arr);
echo findGreatest($arr, $n);
// This code is contributed by anuj_67.
?>
Output :
30
1. Create an empty hash table and store all array elements in it.
2. Sort the array in ascending order.
3. Pick elements one by one from end of the array.
4. And check if there exists a pair whose product is equal to that number. In this
efficiency can be achieved. The idea is to reach till sqrt of that number. If we don’t
get the pair till sqrt that means no such pair exists. We use hash table to make sure
that we can find other element of pair in O(1) time.
5. Repeat steps 2 to 3 until we get the element or whole array gets traversed.
654
Chapter 105. Find pair with greatest product in array
655
Chapter 105. Find pair with greatest product in array
return 0;
}
Output :
30
Improved By : vt_m
Source
https://www.geeksforgeeks.org/find-pair-with-greatest-product-in-array/
656
Chapter 106
A Naive Approach is to run three loops to find pair whose sum exists in array.
C++
657
Chapter 106. Find pairs in array whose sums already exist in array
Java
658
Chapter 106. Find pairs in array whose sums already exist in array
if (found == false)
System.out.println("Not exist");
}
// Driver code
static public void main(String[] args)
{
int[] arr = {10, 4, 8, 13, 5};
int n = arr.length;
findPair(arr, n);
}
}
// This code is contributed by vt_m.
C#
659
Chapter 106. Find pairs in array whose sums already exist in array
{
int[] arr = {10, 4, 8, 13, 5};
int n = arr.Length;
findPair(arr, n);
}
}
// This code is contributed by vt_m.
PHP
<?php
// A simple php program to
// find pair whose sum
// already exists in array
// Function to find pair whose
// sum exists in arr[]
function findPair($arr, $n)
{
$found = false;
for ($i = 0; $i < $n; $i++)
{
for ($j = $i + 1; $j < $n; $j++)
{
for ($k = 0; $k < $n; $k++)
{
if ($arr[$i] + $arr[$j] == $arr[$k])
{
echo $arr[$i] , " " , $arr[$j] ;
$found = true;
}
}
}
}
if ($found == false)
echo "Not exist" ;
}
// Driver code
$arr = array( 10, 4, 8, 13, 5 );
$n = sizeof($arr) / sizeof($arr[0]);
findPair($arr, $n);
// This code is contributed by nitin mittal.
?>
660
Chapter 106. Find pairs in array whose sums already exist in array
Output :
8 5
An Efficient solution is to store all element in an hash table (unordered_set in C++) and
check one by one all pairs and check its sum exists in set or not. If it exists in set then print
pair. If no pair found in array then print not exists .
C++
661
Chapter 106. Find pairs in array whose sums already exist in array
Java
662
Chapter 106. Find pairs in array whose sums already exist in array
{
int[] arr = { 10, 4, 8, 13, 5 };
int n = arr.length;
findPair(arr, n);
}
}
// This code is contributed by Smarak Chopdar
Output:
8 5
Source
https://www.geeksforgeeks.org/find-pairs-in-array-whose-sums-already-exist-in-array/
663
Chapter 107
Find pairs with given sum such that elements of pair are in different rows - GeeksforGeeks
Given a matrix of distinct values and a sum. The task is to find all the pairs in given whose
summation is equal to given sum. Each element of pair must be from different rows i.e; pair
must not lie in same row.
Examples:
Method 1 (Simple)
A simple solution for this problem is to one by one take each element of all rows and find
pair starting from immediate next row with in matrix. Time complexity for this approach
will be O(n4 ).
• Sort all the rows in ascending order. Time complexity for this preprocessing will be
O(n2 logn).
664
Chapter 107. Find pairs with given sum such that elements of pair are in different rows
• Now we will select each row one by one and find pair element in remaining rows after
current row.
• Take two iterators left and right. left iterator points left corner of current i’th row
and right iterator points right corner of next j’th row in which we are going to find
pair element.
• If mat[i][left] + mat[j][right] < sum then left++ i.e; move in i’th row towards
right corner, otherwise right++ i.e; move in j’th row towards left corner.
CPP
665
Chapter 107. Find pairs with given sum such that elements of pair are in different rows
right--;
}
}
}
}
}
// Driver program to run the case
int main()
{
int n = 4, sum = 11;
int mat[][MAX] = {{1, 3, 2, 4},
{5, 8, 7, 6},
{9, 10, 13, 11},
{12, 0, 14, 15}};
pairSum(mat, n, sum);
return 0;
}
Java
666
Chapter 107. Find pairs with given sum such that elements of pair are in different rows
right--;
}
else {
if ((mat[i][left] + mat[j][right]) < sum)
left++;
else
right--;
}
}
}
}
}
// Driver code
public static void main(String[] args) {
int n = 4, sum = 11;
int mat[]
[] = {{1 , 3, 2, 4},
{5 , 8, 7, 6},
{9 , 10, 13, 11},
{12, 0, 14, 15}};
pairSum(mat, n, sum);
}
}
// This code is contributed by Anant Agarwal.
Output:
Method 3 (Hashing)
1. Create an empty hash table and store all elements of matrix in hash as key and their
locations as values.
2. Traverse the matrix again to check for every element whether its pair exists in hash
table or not. If exists, then compare row numbers. If row numbers are not same, then
print the pair.
CPP
667
Chapter 107. Find pairs with given sum such that elements of pair are in different rows
668
Chapter 107. Find pairs with given sum such that elements of pair are in different rows
}
// Driver program
int main()
{
int n = 4, sum = 11;
int mat[][MAX]= {{1, 3, 2, 4},
{5, 8, 7, 6},
{9, 10, 13, 11},
{12, 0, 14, 15}};
pairSum(mat, n, sum);
return 0;
}
Output :
(1, 10), (3, 8), (2, 9), (4, 7), (11, 0),
One important thing is, when we traverse a matrix, a pair may be printed twice. To make
sure that a pair is printed only once, we check if row number of other element picked from
hash table is more than row number of current element.
Time Complexity : O(n2 ) under the assumption that hash table insert and search operations
take O(1) time.
Source
https://www.geeksforgeeks.org/find-pairs-given-sum-elements-pair-different-rows/
669
Chapter 108
Input:
K = 3
arr1[] : [4, 7, 9, 12, 15]
arr2[] : [0, 8, 10, 14, 20]
arr3[] : [6, 12, 16, 30, 50]
Output:
The smallest range is [6 8]
Explanation: Smallest range is formed by
number 7 from first list, 8 from second
list and 6 from third list.
Input:
k = 3
arr1[] : [4, 7]
arr2[] : [1, 2]
arr3[] : [20, 40]
The smallest range is [2 20]
Naive approach : The idea is to maintain pointers to every list using array ptr[k].Below
are the steps :
670
Chapter 108. Find smallest range containing elements from k lists
1. Initially the index of every list is 0,therefore initialize every element of ptr[0..k] to 0;
2. Repeat the following steps until atleast one list exhausts :
• Now find the minimum and maximum value among the current elements of all
the list pointed by the ptr[0…k] array.
• Now update the minrange if current (max-min) is less than minrange.
• increment the pointer pointing to current minimum element.
671
Chapter 108. Find smallest range containing elements from k lists
// find minimum value among all the list elements pointing by the ptr[] array
if(ptr[i] < n && arr[i][ptr[i]] < minval)
{
minind=i; // update the index of the list
minval=arr[i][ptr[i]];
}
// find maximum value among all the list elements pointing by the ptr[] array
if(ptr[i] < n && arr[i][ptr[i]] > maxval)
{
maxval = arr[i][ptr[i]];
}
}
//if any list exhaust we will not get any better answer ,so break the while loop
if(flag)
break;
ptr[minind]++;
//updating the minrange
if((maxval-minval) < minrange)
{
minel = minval;
maxel = maxval;
minrange = maxel - minel;
}
}
printf("The smallest range is [%d , %d]\n",minel,maxel);
}
// Driver program to test above function
int main()
{
int arr[][N] = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
int k = sizeof(arr)/sizeof(arr[0]);
findSmallestRange(arr,N,k);
return 0;
}
// This code is contributed by Aditya Krishna Namdeo
672
Chapter 108. Find smallest range containing elements from k lists
1. Create a min heap of size k and insert first elements of all k lists into the heap.
2. Maintain two variables min and max to store minimum and maximum values present
in the heap at any point. Note min will always contain value of the root of the heap.
3. Repeat following steps
• Get minimum element from heap (minimum is always at root) and compute the
range.
• Replace heap root with next element of the list from which the min element is
extracted. After replacing the root, heapify the tree. Update max if next element
is greater. If the list doesn’t have any more elements, break the loop.
673
Chapter 108. Find smallest range containing elements from k lists
674
Chapter 108. Find smallest range containing elements from k lists
675
Chapter 108. Find smallest range containing elements from k lists
root.element = arr[root.i][root.j];
root.j += 1;
// update max element
if (root.element > max)
max = root.element;
}
// break if we have reached end of any list
else break;
// Replace root with next element of list
hp.replaceMin(root);
}
cout << "The smallest range is " << "["
<< start << " " << end << "]" << endl;;
}
// Driver program to test above functions
int main()
{
int arr[][N] = {
{4, 7, 9, 12, 15},
{0, 8, 10, 14, 20},
{6, 12, 16, 30, 50}
};
int k = sizeof(arr)/sizeof(arr[0]);
findSmallestRange(arr, k);
return 0;
}
Output :
Time Complexity: The while loop inside findSmallestRange() function can run maximum
n*k times. In every iteration of loop, we call heapify which takes O(Logk) time. Therefore,
the time complexity is O(nk Logk).
Source
https://www.geeksforgeeks.org/find-smallest-range-containing-elements-from-k-lists/
676
Chapter 109
Find subarray with given sum | Set 2 (Handles Negative Numbers) - GeeksforGeeks
Given an unsorted array of integers, find a subarray which adds to a given number. If there
are more than one subarrays with sum as the given number, print any of them.
Examples:
We have discussed a solution that do not handles negative integers here. In this post,
negative integers are also handled.
A simple solution is to consider all subarrays one by one and check if sum of every subarray
is equal to given sum or not. The complexity of this solution would be O(n^2).
An efficient way is to use a map. The idea is to maintain sum of elements encountered so
far in a variable (say curr_sum). Let the given number is sum. Now for each element, we
check if curr_sum – sum exists in the map or not. If we found it in the map that means, we
have a subarray present with given sum, else we insert curr_sum into the map and proceed
to next element. If all elements of the array are processed and we didn’t find any subarray
with given sum, then subarray doesn’t exists.
677
Chapter 109. Find subarray with given sum | Set 2 (Handles Negative Numbers)
678
Chapter 109. Find subarray with given sum | Set 2 (Handles Negative Numbers)
int main()
{
int arr[] = {10, 2, -2, -20, 10};
int n = sizeof(arr)/sizeof(arr[0]);
int sum = -10;
subArraySum(arr, n, sum);
return 0;
}
Output:
Time complexity of above solution is O(n) as we are doing only one traversal of the
array.
Source
https://www.geeksforgeeks.org/find-subarray-with-given-sum-in-array-of-integers/
679
Chapter 110
680
Chapter 110. Find substrings that contain all vowels
Output:
aeiou aeiouu
681
Chapter 110. Find substrings that contain all vowels
682
Chapter 110. Find substrings that contain all vowels
int main()
{
string str = "aeoibsddaeiouudb";
FindSubstring(str);
return 0;
}
Output:
aeiou aeiouu
Source
https://www.geeksforgeeks.org/find-substrings-contain-vowels/
683
Chapter 111
A Simple Solution is to use two nested loops. The outer loop picks an element one by one
starting from the leftmost element. The inner loop checks if the element is present on left
side of it. If present, then ignores the element.
Time Complexity : O(n2 )
Auxiliary Space : O(1)
A Better Solution of this problem is that using sorting technique we firstly sort all elements
of array in ascending order and and find one by one distinct elements in array.
684
Chapter 111. Find sum of non-repeating (distinct) elements in an array
// Find the sum of all non-repeated elements
// in an array
int findSum(int arr[], int n)
{
// sort all elements of array
sort(arr, arr + n);
int sum = 0;
for (int i=0; i<n; i++)
{
if (arr[i] != arr[i+1])
sum = sum + arr[i];
}
return sum;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
int n = sizeof(arr)/sizeof(int);
cout << findSum(arr, n);
return 0;
}
Output:
21
685
Chapter 111. Find sum of non-repeating (distinct) elements in an array
int sum = 0;
// Hash to store all element of array
unordered_set< int > s;
for (int i=0; i<n; i++)
{
if (s.find(arr[i]) == s.end())
{
sum += arr[i];
s.insert(arr[i]);
}
}
return sum;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
int n = sizeof(arr)/sizeof(int);
cout << findSum(arr, n);
return 0;
}
Output:
21
Source
https://www.geeksforgeeks.org/find-sum-non-repeating-distinct-elements-array/
686
Chapter 112
A Simple Solution is to run two nested loops. The outer loop picks all elements one by
one and inner loop counts number of occurrences of the element picked by outer loop. Time
complexity of this solution is O(n2 ).
Below is the implementation of the brute force approach :
C++
687
Chapter 112. Find the Number Occurring Odd Number of Times
{
for (int i = 0; i < arr_size; i++) {
int count = 0;
for (int j = 0; j < arr_size; j++)
{
if (arr[i] == arr[j])
count++;
}
if (count % 2 != 0)
return arr[i];
}
return -1;
}
// driver code
int main()
{
int arr[] = { 2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function calling
cout << getOddOccurrence(arr, n);
return 0;
}
Java
688
Chapter 112. Find the Number Occurring Odd Number of Times
}
return -1;
}
// driver code
public static void main(String[] args)
{
int arr[] = new int[]{ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.length;
System.out.println(getOddOccurrence(arr, n));
}
}
// This code has been contributed by Kamal Rawal
Python3
C#
689
Chapter 112. Find the Number Occurring Odd Number of Times
using System;
class GFG
{
// Funtion to find the element
// occurring odd number of times
static int getOddOccurrence(int []arr, int arr_size)
{
for (int i = 0; i < arr_size; i++) {
int count = 0;
for (int j = 0; j < arr_size; j++) {
if (arr[i] == arr[j])
count++;
}
if (count % 2 != 0)
return arr[i];
}
return -1;
}
// Driver code
public static void Main()
{
int []arr = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 };
int n = arr.Length;
Console.Write(getOddOccurrence(arr, n));
}
}
// This code is contributed by Sam007
PHP
<?php
// PHP program to find the
// element occurring odd
// number of times
// Function to find the element
// occurring odd number of times
function getOddOccurrence(&$arr, $arr_size)
{
$count = 0;
for ($i = 0;
$i < $arr_size; $i++)
{
690
Chapter 112. Find the Number Occurring Odd Number of Times
for ($j = 0;
$j < $arr_size; $j++)
{
if ($arr[$i] == $arr[$j])
$count++;
}
if ($count % 2 != 0)
return $arr[$i];
}
return -1;
}
// Driver code
$arr = array(2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2);
$n = sizeof($arr);
// Function calling
echo(getOddOccurrence($arr, $n));
// This code is contributed
// by Shivi_Aggarwal
?>
Output :
A Better Solution is to use Hashing. Use array elements as key and their counts as value.
Create an empty hash table. One by one traverse the given array elements and store counts.
Time complexity of this solution is O(n). But it requires extra space for hashing.
Program :
Java
691
Chapter 112. Find the Number Occurring Odd Number of Times
{
HashMap<Integer,Integer> hmap = new HashMap<>();
// Putting all elements into the HashMap
for(int i = 0; i < n; i++)
{
if(hmap.containsKey(arr[i]))
{
int val = hmap.get(arr[i]);
// If array element is already present then
// increase the count of that element.
hmap.put(arr[i], val + 1);
}
else
// if array element is not present then put
// element into the HashMap and initialize
// the count to one.
hmap.put(arr[i], 1);
}
// Checking for odd occurrence of each element present
// in the HashMap
for(Integer a:hmap.keySet())
{
if(hmap.get(a) % 2 != 0)
return a;
}
return -1;
}
// driver code
public static void main(String[] args)
{
int arr[] = new int[]{2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
int n = arr.length;
System.out.println(getOddOccurrence(arr, n));
}
}
// This code is contributed by Kamal Rawal
Output :
The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives
692
Chapter 112. Find the Number Occurring Odd Number of Times
us odd occurring element. Please note that XOR of two elements is 0 if both elements are
same and XOR of a number x with 0 is x.
Below is the implementation of the above approach.
C++
// C program to find the element
// occurring odd number of times
#include <stdio.h>
// Function to find element occurring
// odd number of times
int getOddOccurrence(int ar[], int ar_size)
{
int res = 0;
693
Chapter 112. Find the Number Occurring Odd Number of Times
Java
Python
694
Chapter 112. Find the Number Occurring Odd Number of Times
C#
695
Chapter 112. Find the Number Occurring Odd Number of Times
PHP
<?php
// PHP program to find the
// element occurring odd
// number of times
// Function to find element
// occurring odd number of times
function getOddOccurrence(&$ar, $ar_size)
{
$res = 0;
for ($i = 0; $i < $ar_size; $i++)
$res = $res ^ $ar[$i];
return $res;
}
// Driver Code
$ar = array(2, 3, 5, 4, 5, 2,
4, 3, 5, 2, 4, 4, 2);
$n = sizeof($ar);
// Function calling
echo(getOddOccurrence($ar, $n));
// This code is contributed
// by Shivi_Aggarwal
?>
Output :
Source
https://www.geeksforgeeks.org/find-the-number-occurring-odd-number-of-times/
696
Chapter 113
Find the character in first string that is present at minimum index in second string - Geeks-
forGeeks
Given a string str and another string patt. Find the character in patt that is present at
the minimum index in str. If no character of patt is present in str then print ‘No character
present’.
Examples:
697
Chapter 113. Find the character in first string that is present at minimum index in second
string
698
Chapter 113. Find the character in first string that is present at minimum index in second
string
printMinIndexChar(str, patt);
return 0;
}
Java
699
Chapter 113. Find the character in first string that is present at minimum index in second
string
// Driver Method
public static void main(String[] args)
{
String str = "geeksforgeeks";
String patt = "set";
printMinIndexChar(str, patt);
}
}
C#
700
Chapter 113. Find the character in first string that is present at minimum index in second
string
Output:
Time Complexity: O(mn), where m and n are the lengths of the two strings.
Auxiliary Space: O(1)
Method 2 Efficient Approach(Hashing): Create a hash table with (key, value) tuple
represented as (character, index) tuple. Store the first index of each character of str
in the hash table. Now, for each character of patt check if it is present in the hash table
or not. If present then get its index from the hash table and update minIndex(minimum
index encountered so far). For no matching character print “No character present”. Hash
table is implemented using unordered_set in C++.
C++
701
Chapter 113. Find the character in first string that is present at minimum index in second
string
Java
702
Chapter 113. Find the character in first string that is present at minimum index in second
string
import java.util.HashMap;
public class GFG
{
// method to find the minimum index character
static void printMinIndexChar(String str, String patt)
{
// map to store the first index of each character of 'str'
HashMap<Character, Integer> hm = new HashMap<>();
// to store the index of character having
// minimum index
int minIndex = Integer.MAX_VALUE;
// lengths of the two strings
int m = str.length();
int n = patt.length();
// store the first index of each character of 'str'
for (int i = 0; i < m; i++)
if(!hm.containsKey(str.charAt(i)))
hm.put(str.charAt(i),i);
// traverse the string 'patt'
for (int i = 0; i < n; i++)
// if patt[i] is found in 'um', check if
// it has the minimum index or not accordingly
// update 'minIndex'
if (hm.containsKey(patt.charAt(i)) &&
hm.get(patt.charAt(i)) < minIndex)
minIndex = hm.get(patt.charAt(i));
// print the minimum index character
if (minIndex != Integer.MAX_VALUE)
System.out.println("Minimum Index Character = " +
str.charAt(minIndex));
// if no character of 'patt' is present in 'str'
else
System.out.println("No character present");
}
// Driver Method
public static void main(String[] args)
{
String str = "geeksforgeeks";
String patt = "set";
printMinIndexChar(str, patt);
703
Chapter 113. Find the character in first string that is present at minimum index in second
string
}
}
Output:
Time Complexity: O(m + n), where m and n are the lengths of the two strings.
Auxiliary Space: O(d), where d is the size of hash table, which is the count of distinct
characters in str.
Source
https://www.geeksforgeeks.org/find-character-first-string-present-minimum-index-second-string/
704
Chapter 114
1. Create an empty DLL. Also create two arrays inDLL[] and repeated[] of size 256.
inDLL is an array of pointers to DLL nodes. repeated[] is a boolean array, repeated[x]
is true if x is repeated two or more times, otherwise false. inDLL[x] contains pointer
to a DLL node if character x is present in DLL, otherwise NULL.
2. Initialize all entries of inDLL[] as NULL and repeated[] as false.
3. To get the first non-repeating character, return character at head of DLL.
4. Following are steps to process a new character ‘x’ in stream.
705
Chapter 114. Find the first non-repeating character from a stream of characters
Note that appending a new node to DLL is O(1) operation if we maintain tail pointer.
Removing a node from DLL is also O(1). So both operations, addition of new character and
finding first non-repeating character take O(1) time.
C/C++
706
Chapter 114. Find the first non-repeating character from a stream of characters
// Note that the function may change head and tail pointers,
// that is why pointers to these pointers are passed.
void removeNode(struct node **head_ref, struct node **tail_ref,
struct node *temp)
{
if (*head_ref == NULL)
return;
if (*head_ref == temp)
*head_ref = (*head_ref)->next;
if (*tail_ref == temp)
*tail_ref = (*tail_ref)->prev;
if (temp->next != NULL)
temp->next->prev = temp->prev;
if (temp->prev != NULL)
temp->prev->next = temp->next;
delete(temp);
}
void findFirstNonRepeating()
{
// inDLL[x] contains pointer to a DLL node if x is present
// in DLL. If x is not present, then inDLL[x] is NULL
struct node *inDLL[MAX_CHAR];
// repeated[x] is true if x is repeated two or more times.
// If x is not seen so far or x is seen only once. then
// repeated[x] is false
bool repeated[MAX_CHAR];
// Initialize the above two arrays
struct node *head = NULL, *tail = NULL;
for (int i = 0; i < MAX_CHAR; i++)
{
inDLL[i] = NULL;
repeated[i] = false;
}
// Let us consider following stream and see the process
char stream[] = "geeksforgeeksandgeeksquizfor";
for (int i = 0; stream[i]; i++)
{
char x = stream[i];
cout << "Reading " << x << " from stream n";
// We process this character only if it has not occurred
// or occurred only once. repeated[x] is true if x is
707
Chapter 114. Find the first non-repeating character from a stream of characters
Java
708
Chapter 114. Find the first non-repeating character from a stream of characters
709
Chapter 114. Find the first non-repeating character from a stream of characters
}
//This code is contributed by Sumit Ghosh
Python
Output:
710
Chapter 114. Find the first non-repeating character from a stream of characters
711
Chapter 114. Find the first non-repeating character from a stream of characters
This article is contributed by Amit Jain. 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/find-first-non-repeating-character-stream-characters/
712
Chapter 115
Examples:
Input: ch = "geeksforgeeks"
Output: e
e is the first element that repeats
Simple Solution: The solution is to run two nested loops. Start traversing from left side.
For every character, check if it repeats or not. If the character repeats, increment count of
713
Chapter 115. Find the first repeated character in a string
repeating characters. When the count becomes k, return the character. Time Complexity
of this solution is O(n2 )
We can Use Sorting to solve the problem in O(n Log n) time. Following are detailed steps.
1) Copy the given array to an auxiliary array temp[].
2) Sort the temp array using a O(nLogn) time sorting algorithm.
3) Scan the input array from left to right. For every element, count its
occurrences in temp[] using binary search. As soon as we find a characterthat occurs more
than once, we return the character.
This step can be done in O(n Log n) time.
An efficient solution is to use Hashing to solve this in O(n) time on average.
C/C++
714
Chapter 115. Find the first repeated character in a string
// Driver method to test above method
int main ()
{
string str = "geeksforgeeks";
cout << firstRepeating(str);
return 0;
}
Java
715
Chapter 115. Find the first repeated character in a string
Python
Output:
Further Optimization : Size of alphabet is typically small and fixed. In case of ASCII,
size is 256. So we can create a fixed size array and use character ASCII values as index.
Similar Problem: finding first non-repeated character in a string.
Source
https://www.geeksforgeeks.org/find-the-first-repeated-character-in-a-string/
716
Chapter 116
A Simple Solution is to use two nested loops. The outer loop picks an element one by
one, the inner loop checks whether the element is repeated or not. Once we find an element
that repeats, we break the loops and print the element. Time Complexity of this solution
is O(n2 )
We can Use Sorting to solve the problem in O(nLogn) time. Following are detailed steps.
1) Copy the given array to an auxiliary array temp[].
2) Sort the temp array using a O(nLogn) time sorting algorithm.
3) Scan the input array from left to right. For every element, count its occurrences in temp[]
using binary search. As soon as we find an element that occurs more than once, we return
the element. This step can be done in O(nLogn) time.
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given
array from right to left and update the minimum index whenever we find an element that
has been visited on right side. Thanks to Mohammad Shahid for suggesting this solution.
Following are C++ and Java implementation of this idea.
C++
717
Chapter 116. Find the first repeating element in an array of integers
Java
718
Chapter 116. Find the first repeating element in an array of integers
Output:
Source
https://www.geeksforgeeks.org/find-first-repeating-element-array-integers/
719
Chapter 117
Find the largest area rectangular sub-matrix whose sum is equal to k - GeeksforGeeks
Given a 2D matrix mat[][] and a value k. Find the largest rectangular sub-matrix whose
sum is equal to k.
Example:
Naive Approach: Check every possible rectangle in given 2D array having sum equal to
‘k’ and print the largest one. This solution requires 4 nested loops and time complexity of
this solution would be O(n^4).
Efficient Approach: Longest sub-array having sum k for 1-D array can be used to reduce
the time complexity to O(n^3). The idea is to fix the left and right columns one by one
and find the longest sub-array having sum equal to ‘k’ for contiguous rows for every left and
right column pair. We basically find top and bottom row numbers (which are part of the
720
Chapter 117. Find the largest area rectangular sub-matrix whose sum is equal to k
largest sub-matrix) for every fixed left and right column pair. To find the top and bottom
row numbers, calculate sum of elements in every row from left to right and store these sums
in an array say temp[]. So temp[i] indicates sum of elements from left to right in row i.
Now, apply Longest sub-array having sum k 1D algorithm on temp[], and get the longest
sub-array having sum equal to ‘k’ of temp[]. This length would be the maximum possible
length with left and right as boundary columns. Set the ‘top’ and ‘bottom’ row indexes for
the left right column pair and calculate the area. In similar manner get the top, bottom,
left, right indexes for other sub-matrices having sum equal to ‘k’ and print the one having
maximum area.
721
Chapter 117. Find the largest area rectangular sub-matrix whose sum is equal to k
// check if 'sum-k' is present in 'um'
// or not
if (um.find(sum - k) != um.end()) {
// update maxLength and start and end points
if (maxLen < (i - um[sum - k])) {
maxLen = i - um[sum - k];
start = um[sum - k] + 1;
end = i;
}
}
}
// Return true if maximum length is non-zero
return (maxLen != 0);
}
// function to find the largest area rectangular
// sub-matrix whose sum is equal to k
void sumZeroMatrix(int mat[][MAX], int row, int col, int k)
{
// Variables to store the temporary values
int temp[row], area;
bool sum;
int up, down;
// Variables to store the final output
int fup = 0, fdown = 0, fleft = 0, fright = 0;
int maxArea = INT_MIN;
// Set the left column
for (int left = 0; left < col; left++) {
// Initialize all elements of temp as 0
memset(temp, 0, sizeof(temp));
// Set the right column for the left column
// set by outer loop
for (int right = left; right < col; right++) {
// Calculate sum between current left
// and right column for every row 'i'
for (int i = 0; i < row; i++)
temp[i] += mat[i][right];
// Find largest subarray with 'k' sum in
// temp[]. The sumEqualToK() function also
// sets values of 'up' and 'down;'. So
// if 'sum' is true then rectangle exists between
722
Chapter 117. Find the largest area rectangular sub-matrix whose sum is equal to k
723
Chapter 117. Find the largest area rectangular sub-matrix whose sum is equal to k
int main()
{
int mat[][MAX] = { { 1, 7, -6, 5 },
{ -8, 6, 7, -2 },
{ 10, -15, 3, 2 },
{ -5, 2, 0, 9 } };
int row = 4, col = 4;
int k = 7;
sumZeroMatrix(mat, row, col, k);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-the-largest-area-rectangular-sub-matrix-whose-sum-is-equal-to-k/
724
Chapter 118
A simple solution is to consider all subarrays one by one and check the sum of every
subarray. We can run two loops: the outer loop picks a starting point i and the inner loop
tries all subarrays starting from i. Time complexity of this method is O(n2 ).
Below are implementations of this solution.
C/C++
725
Chapter 118. Find the length of largest subarray with 0 sum
Java
726
Chapter 118. Find the length of largest subarray with 0 sum
{
// Initialize curr_sum for every
// starting point
int curr_sum = 0;
// try all subarrays starting with 'i'
for (int j = i; j < n; j++)
{
curr_sum += arr[j];
// If curr_sum becomes 0, then update
// max_len
if (curr_sum == 0)
max_len = Math.max(max_len, j-i+1);
}
}
return max_len;
}
public static void main(String args[])
{
int arr[] = {15, -2, 2, -8, 1, 7, 10, 23};
int n = arr.length;
System.out.println("Length of the longest 0 sum "+
"subarray is "+ maxLen(arr, n));
}
}
// This code is contributed by Kamal Rawal
Python
727
Chapter 118. Find the length of largest subarray with 0 sum
curr_sum += arr[j]
# if curr_sum becomes 0, then update max_len
if curr_sum == 0:
max_len = max(max_len, j-i+1)
return max_len
# test array
arr = [15, -2, 2, -8, 1, 7, 10, 13]
print "Length of the longest 0 sum subarray is %d" % maxLen(arr)
C#
728
Chapter 118. Find the length of largest subarray with 0 sum
return max_len;
}
// Driver code
static public void Main ()
{
int []arr = {15, -2, 2, -8,
1, 7, 10, 23};
int n = arr.Length;
Console.WriteLine("Length of the longest 0 sum "+
"subarray is "+ maxLen(arr, n));
}
}
// This code is contributed by ajit
PHP
<?php
// A simple PHP program to find
// largest subarray with 0 sum
// Returns length of the
// largest subarray with 0 sum
function maxLen($arr, $n)
{
$max_len = 0; // Initialize result
// Pick a starting point
for ($i = 0; $i < $n; $i++)
{
// Initialize currr_sum
// for every starting point
$curr_sum = 0;
// try all subarrays
// starting with 'i'
for ($j = $i; $j < $n; $j++)
{
$curr_sum += $arr[$j];
// If curr_sum becomes 0,
// then update max_len
// if required
if ($curr_sum == 0)
$max_len = max($max_len,
$j - $i + 1);
}
729
Chapter 118. Find the length of largest subarray with 0 sum
}
return $max_len;
}
// Driver Code
$arr = array(15, -2, 2, -8,
1, 7, 10, 23);
$n = sizeof($arr);
echo "Length of the longest 0 " .
"sum subarray is ",
maxLen($arr, $n);
// This code is contributed by aj_36
?>
Output :
We can Use Hashing to solve this problem in O(n) time. The idea is to iterate through
the array and for every element arr[i], calculate sum of elements form 0 to i (this can simply
be done as sum += arr[i]). If the current sum has been seen before, then there is a zero
sum array. Hashing is used to store the sum values, so that we can quickly store sum and
find out whether the current sum is seen before or not.
Following are implementations of the above approach.
C++
730
Chapter 118. Find the length of largest subarray with 0 sum
if (arr[i]==0 && max_len==0)
max_len = 1;
if (sum == 0)
max_len = i+1;
// Look for this sum in Hash table
if(presum.find(sum) != presum.end())
{
// If this sum is seen before, then update max_len
max_len = max(max_len, i-presum[sum]);
}
else
{
// Else insert this sum with index in hash table
presum[sum] = i;
}
}
return max_len;
}
// Driver Program to test above function
int main()
{
int arr[] = {15, -2, 2, -8, 1, 7, 10, 23};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Length of the longest 0 sum subarray is "
<< maxLen(arr, n);
return 0;
}
Java
731
Chapter 118. Find the length of largest subarray with 0 sum
// Traverse through the given array
for (int i = 0; i < arr.length; i++)
{
// Add current element to sum
sum += arr[i];
if (arr[i] == 0 && max_len == 0)
max_len = 1;
if (sum == 0)
max_len = i+1;
// Look this sum in hash table
Integer prev_i = hM.get(sum);
// If this sum is seen before, then update max_len
// if required
if (prev_i != null)
max_len = Math.max(max_len, i-prev_i);
else // Else put this sum in hash table
hM.put(sum, i);
}
return max_len;
}
// Drive method
public static void main(String arg[])
{
int arr[] = {15, -2, 2, -8, 1, 7, 10, 23};
System.out.println("Length of the longest 0 sum subarray is "
+ maxLen(arr));
}
}
Python
732
Chapter 118. Find the length of largest subarray with 0 sum
Output :
Time Complexity of this solution can be considered as O(n) under the assumption that we
have good hashing function that allows insertion and retrieval operations in O(1) time.
This article is contributed by Rahul Agrawal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : jit_t, Mahin_251
733
Chapter 118. Find the length of largest subarray with 0 sum
Source
https://www.geeksforgeeks.org/find-the-largest-subarray-with-0-sum/
734
Chapter 119
Find the longest substring with k unique characters in a given string - GeeksforGeeks
Given a string you need to print longest possible substring that has exactly M unique
characters. If there are more than one substring of longest possible length, then print any
one of them.
Examples:
"aabbcc", k = 1
Max substring can be any one from {"aa" , "bb" , "cc"}.
"aabbcc", k = 2
Max substring can be any one from {"aabb" , "bbcc"}.
"aabbcc", k = 3
There are substrings with exactly 3 unique characters
{"aabbcc" , "abbcc" , "aabbc" , "abbc" }
Max is "aabbcc" with length 6.
"aaabbb", k = 3
There are only two unique characters, thus show error message.
735
Chapter 119. Find the longest substring with k unique characters in a given string
or not. If we apply this brute force, it would take O(n2 ) to generate all substrings and O(n)
to do a check on each one. Thus overall it would go O(n3 ).
We can further improve this solution by creating a hash table and while generating the
substrings, check the number of unique characters using that hash table. Thus it would
improve up to O(n2 ).
Method 2 (Linear Time)
The problem can be solved in O(n). Idea is to maintain a window and add elements to the
window till it contains less or equal k, update our result if required while doing so. If unique
elements exceeds than required in window, start removing the elements from left side.
Below are C++ and Python implementations of above. The implementations assume that
the input string alphabet contains only 26 characters (from ‘a’ to ‘z’). The code can be
easily extended to 256 characters.
C++
736
Chapter 119. Find the longest substring with k unique characters in a given string
// Traverse the string, Fills the associative array
// count[] and count number of unique characters
for (int i=0; i<n; i++)
{
if (count[s[i]-'a']==0)
u++;
count[s[i]-'a']++;
}
// If there are not enough unique characters, show
// an error message.
if (u < k)
{
cout << "Not enough unique characters";
return;
}
// Otherwise take a window with first element in it.
// start and end variables.
int curr_start = 0, curr_end = 0;
// Also initialize values for result longest window
int max_window_size = 1, max_window_start = 0;
// Initialize associative array count[] with zero
memset(count, 0, sizeof(count));
count[s[0]-'a']++; // put the first character
// Start from the second character and add
// characters in window according to above
// explanation
for (int i=1; i<n; i++)
{
// Add the character 's[i]' to current window
count[s[i]-'a']++;
curr_end++;
// If there are more than k unique characters in
// current window, remove from left side
while (!isValid(count, k))
{
count[s[curr_start]-'a']--;
curr_start++;
}
// Update the max window size if required
737
Chapter 119. Find the longest substring with k unique characters in a given string
Python
738
Chapter 119. Find the longest substring with k unique characters in a given string
739
Chapter 119. Find the longest substring with k unique characters in a given string
# Driver function
s = "aabacbebebe"
k = 3
kUniques(s, k)
# This code is contributed by BHAVYA JAIN
Output:
Time Complexity: Considering function “isValid()” takes constant time, time complexity
of above solution is O(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
Source
https://www.geeksforgeeks.org/find-the-longest-substring-with-k-unique-characters-in-a-given-string/
740
Chapter 120
Input: x = 12234
Output: The most frequent digit is 2
Input: x = 1223377
Output: The most frequent digit is 7
Input: x = 5
Output: The most frequent digit is 5
Input: x = 1000
Output: The most frequent digit is 0
We strongly recommend you to minimize your browser and try this yourself
first.
We could create a map of size 10 and store count of all digits, but use of any array/string
is not allowed.
The idea is simple, we write a function that counts occurrences of a given digit in a given
integer. Then we count all digits from 0 to 9 in given integer. We keep updating maximum
count whenever count becomes more or same as previous count. Below is C++ implemen-
tation.
741
Chapter 120. Find the most frequent digit without using array/string
742
Chapter 120. Find the most frequent digit without using array/string
{
long int x = 1223355;
cout << "Max occurring digit is " << maxOccurring(x);
return 0;
}
Java
743
Chapter 120. Find the most frequent digit without using array/string
// Initialize count
// of result
int max_count = 1;
// Traverse through
// all digits
for (int d = 0; d <= 9; d++)
{
// Count occurrences
// of current digit
int count = countOccurrences(x, d);
// Update max_count
// and result if needed
if (count >= max_count)
{
max_count = count;
result = d;
}
}
return result;
}
// Driver Code
public static void main (String[] args)
{
int x = 1223355;
System.out.println("Max occurring digit is " +
maxOccurring(x));
}
}
// This code is contributed
// by akt_mit
Output:
Improved By : jit_t
Source
https://www.geeksforgeeks.org/find-the-most-frequent-digit-without-using-arraystring/
744
Chapter 121
Add each number once and multiply the sum by a, we will get a times the sum of each
element of the array. Store it as a_sum. Subtract the sum of the whole array from the
a_sum and divide the result by (a-b). The number we get is the required number (which
appears b times in the array).
745
Chapter 121. Find the only element that appears b times
s.insert(arr[i]);
a_sum += arr[i];
}
sum += arr[i];
}
a_sum = a * a_sum;
return ((a_sum - sum) / (a - b));
}
int main()
{
int arr[] = { 1, 1, 2, 2, 2, 3, 3, 3 };
int a = 3, b = 2;
int n = sizeof(arr) / sizeof(arr[0]);
cout << appearsbTimes(arr, n, a, b);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-element-appears-b-times/
746
Chapter 122
Method 1 (Simple) We use two nested loops. The outer loop traverses through all
elements and the inner loop check if the element picked by outer loop appears anywhere
else.
Time Complexity : O(n*n)
Method 2 (Using Sum Formula): We know sum of first n-1 natural numbersis (n –
1)*n/2. We compute sum of array elements and subtract natural number sum from it to
find the only missing element.
C++
747
Chapter 122. Find the only repetitive element between 1 to n-1
int findRepeating(int arr[], int n)
{
// Find array sum and subtract sum
// first n-1 natural numbers from it
// to find the result.
return accumulate(arr , arr+n , 0) -
((n - 1) * n/2);
}
// driver code
int main()
{
int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findRepeating(arr, n);
return 0;
}
Output :
748
Chapter 122. Find the only repetitive element between 1 to n-1
// If input is correct, we should
// never reach here
return -1;
}
// driver code
int main()
{
int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findRepeating(arr, n);
return 0;
}
Output :
C++
749
Chapter 122. Find the only repetitive element between 1 to n-1
return res;
}
// driver code
int main()
{
int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findRepeating(arr, n);
return 0;
}
Java
Python3
750
Chapter 122. Find the only repetitive element between 1 to n-1
C#
751
Chapter 122. Find the only repetitive element between 1 to n-1
// Driver code
public static void Main()
{
int []arr = { 9, 8, 2, 6, 1,
8, 5, 3, 4, 7 };
int n = arr.Length;
Console.Write(findRepeating(arr, n));
}
}
// This code is contributed
// by Smitha Dinesh Semwal.
PHP
<?php
// PHP program to find the only repeating
// element in an array where elements are
// from 1 to n-1.
function findRepeating($arr, $n)
{
// res is going to store value of
// 1 ^ 2 ^ 3 .. ^ (n-1) ^ arr[0] ^
// arr[1] ^ .... arr[n-1]
$res = 0;
for($i = 0; $i < $n - 1; $i++)
$res = $res ^ ($i + 1) ^ $arr[$i];
$res = $res ^ $arr[$n - 1];
return $res;
}
// Driver Code
$arr =array(9, 8, 2, 6, 1, 8, 5, 3, 4, 7);
$n = sizeof($arr) ;
echo findRepeating($arr, $n);
// This code is contributed by ajit
?>
Output:
752
Chapter 122. Find the only repetitive element between 1 to n-1
C++
753
Chapter 122. Find the only repetitive element between 1 to n-1
return 0;
}
Java
754
Chapter 122. Find the only repetitive element between 1 to n-1
Python3
PHP
<?php
// PHP program to find the only
// repeating element in an array
// where elements are from 1 to n-1.
// Function to find repeted element
function findRepeating($arr, $n)
{
$missingElement = 0;
// indexing based
for ($i = 0; $i < $n; $i++)
{
755
Chapter 122. Find the only repetitive element between 1 to n-1
$element = $arr[abs($arr[$i])];
if($element < 0)
{
$missingElement = $arr[$i];
break;
}
$arr[abs($arr[$i])] = -$arr[abs($arr[$i])];
}
return abs($missingElement);
}
// Driver Code
$arr = array (5, 4, 3, 9, 8,
9, 1, 6, 2, 5);
$n = sizeof($arr);
echo findRepeating($arr, $n);
// This code is contributed by ajit
?>
Output :
Source
https://www.geeksforgeeks.org/find-repetitive-element-1-n-1/
756
Chapter 123
Brute Force Method : The simple approach is that for each element in A[] check whether
it is present in B[] and if it is present in B[] then add that number two times(once for A[]
and once for B[]) to the sum. Repeat this procedure for all elements in the array A[].
Time Complexity: O(n^2).
Efficient Method : An efficient method is to use Hashing. Traverse both of the arrays
and insert the elements into a hash table to keep track of the count of elements. Add the
elements to sum whose count equals to two.
Below is the implementation of above approach:
757
Chapter 123. Find the overlapping sum of two arrays
758
Chapter 123. Find the overlapping sum of two arrays
}
return sum;
}
// driver code
int main()
{
int A[] = { 5, 4, 9, 2, 3 };
int B[] = { 2, 8, 7, 6, 3 };
// size of array
int n = sizeof(A) / sizeof(A[0]);
// function call
cout << findSum(A, B, n);
return 0;
}
Output:
52
Source
https://www.geeksforgeeks.org/find-the-overlapping-sum-of-two-arrays/
759
Chapter 124
Find the smallest window in a string containing all characters of another string - Geeks-
forGeeks
Given two strings string1 and string2, find the smallest substring in string1 containing all
characters of string2 efficiently.
For Example:
760
Chapter 124. Find the smallest window in a string containing all characters of another
string
761
Chapter 124. Find the smallest window in a string containing all characters of another
string
762
Chapter 124. Find the smallest window in a string containing all characters of another
string
// update window size
int len_window = j - start + 1;
if (min_len > len_window)
{
min_len = len_window;
start_index = start;
}
}
}
// If no window found
if (start_index == -1)
{
cout << "No such window exists";
return "";
}
// Return substring starting from start_index
// and length min_len
return str.substr(start_index, min_len);
}
// Driver code
int main()
{
string str = "this is a test string";
string pat = "tist";
cout << "Smallest window is : n"
<< findSubString(str, pat);
return 0;
}
Java
763
Chapter 124. Find the smallest window in a string containing all characters of another
string
764
Chapter 124. Find the smallest window in a string containing all characters of another
string
// update window size
int len_window = j - start + 1;
if (min_len > len_window)
{
min_len = len_window;
start_index = start;
}
}
}
// If no window found
if (start_index == -1)
{
System.out.println("No such window exists");
return "";
}
// Return substring starting from start_index
// and length min_len
return str.substring(start_index, start_index + min_len);
}
// Driver Method
public static void main(String[] args)
{
String str = "this is a test string";
String pat = "tist";
System.out.print("Smallest window is : n" +
findSubString(str, pat));
}
}
Output:
Smallest window is :
t stri
Improved By : kamikaze101
765
Chapter 124. Find the smallest window in a string containing all characters of another
string
Source
https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-characters-of-another-string/
766
Chapter 125
Find the starting indices of the substrings in string (S) which is made by concatenating all
words from a list(L) - GeeksforGeeks
You are given a string S, and a list of words L i.e array/vector of strings (Words in list L
are all of the same length). Find the starting indices of the substrings in string S, which
contains all the words present in list L.
The order of words of list L appearing inside string S does not matter i.e if string S is
“barfooapplefoobar” and list of words (L) is [“foo”, “bar”] then we have to look for substrings
“foobar”, “barfoo” in string S.
Note : Words inside the list L can repeat.
Examples :
Input : S: "barfoothefoobarman"
L: ["foo", "bar"]
Output : 0 9
Explanation :
// at index 0 : barfoo
// at index 9 : foobar
Input : S: "catbatatecatatebat"
L: ["cat", "ate", "bat"]
Output : 0 3 9
767
Chapter 125. Find the starting indices of the substrings in string (S) which is made by
concatenating all words from a list(L)
Explanation :
// at index 0 : catbatate
// at index 3 : batatecat
// at index 9 : catatebat
Input : S : "abcdababcd"
L : ["ab", "ab", "cd"]
Output : 0 2 4
Explanation :
// at index 0 : abcdab
// at index 2 : cdabab
// at index 4 : ababcd
Input : S : "abcdababcd"
L : ["ab", "ab"]
Output : 4
Approach :
We can use Hashing Technique to solve the above problem. Let’s see the steps :
1. Declare a map (hash_map) which stores all words of List L corresponding to their
occurrences inside list L.
2. Traverse through all possible substrings in string S which are equal to size_L(total
number of characters produced if all the words in list L are concatenated).
3. Create a temporary map (temp_hash_map) and initialize it with original
map(hash_map) for every possible substring.
4. Extract the words from the substring and if the word is present in temp_hash_map
we decrease it’s corresponding count, if it’s not present in temp_hash_map we simply
break.
5. After traversing the substring we traverse temp_hash_map and look for any key which
has it’s count > 0. If we found no such key it means that all the words in list L were
found in substring and store the given starting index of the substring, if we find a key
which has it’s count > 0 it means we did not traversed whole substring because we
came across a word which was not in temp_hash_map.
768
Chapter 125. Find the starting indices of the substrings in string (S) which is made by
concatenating all words from a list(L)
{
// Number of a characters of a word in list L.
int size_word = L[0].size();
// Number of words present inside list L.
int word_count = L.size();
// Total characters present in list L.
int size_L = size_word * word_count;
// Resultant vector which stores indices.
vector<int> res;
// If the total number of characters in list L
// is more than length of string S itself.
if (size_L > S.size())
return res;
// Map stores the words present in list L
// against it's occurrences inside list L
unordered_map<string, int> hash_map;
for (int i = 0; i < word_count; i++)
hash_map[L[i]]++;
for (int i = 0; i <= S.size() - size_L; i++) {
unordered_map<string, int> temp_hash_map(hash_map);
int j = i;
// Traverse the substring
while (j < i + size_L) {
// Extract the word
string word = S.substr(j, size_word);
// If word not found simply break.
if (hash_map.find(word) == hash_map.end())
break;
// Else decrement the count of word from hash_map
else
temp_hash_map[word]--;
j += size_word;
}
769
Chapter 125. Find the starting indices of the substrings in string (S) which is made by
concatenating all words from a list(L)
int count = 0;
for (auto itr = temp_hash_map.begin();
itr != temp_hash_map.end(); itr++)
if (itr->second > 0)
count++;
// Store the starting index of that substring
if (count == 0)
res.push_back(i);
}
return res;
}
// Driver Code
int main()
{
string S = "barfoothefoobarman";
vector<string> L = { "foo", "bar" };
vector<int> indices = findSubstringIndices(S, L);
for (int i = 0; i < indices.size(); i++)
cout << indices[i] << " ";
return 0;
}
Output :
0 9
Source
https://www.geeksforgeeks.org/find-starting-indices-substrings-string-s-made-concatenating-words-listl/
770
Chapter 126
Find three element from different three arrays such that that a + b + c = sum - Geeks-
forGeeks
Given three integer arrays and a “sum”, the task is to check if there are three elements a,
b, c such that a + b + c = sum and a, b and c belong to three different arrays.
Examples :
Input : a1[] = { 1 , 2 , 3 , 4 , 5 };
a2[] = { 2 , 3 , 6 , 1 , 2 };
a3[] = { 3 , 2 , 4 , 5 , 6 };
sum = 9
Output : Yes
1 + 2 + 6 = 9 here 1 from a1[] and 2 from
a2[] and 6 from a3[]
Input : a1[] = { 1 , 2 , 3 , 4 , 5 };
a2[] = { 2 , 3 , 6 , 1 , 2 };
a3[] = { 3 , 2 , 4 , 5 , 6 };
sum = 20
Output : No
A naive approach is to run three loops and check sum of three element form different
arrays equal to given number if find then print exist and otherwise print not exist.
C++
771
Chapter 126. Find three element from different three arrays such that that a + b + c =
sum
Java
772
Chapter 126. Find three element from different three arrays such that that a + b + c =
sum
Python3
773
Chapter 126. Find three element from different three arrays such that that a + b + c =
sum
C#
774
Chapter 126. Find three element from different three arrays such that that a + b + c =
sum
int sum)
{
for (int i = 0; i < n1; i++)
for (int j = 0; j < n2; j++)
for (int k = 0; k < n3; k++)
if (a1[i] + a2[j] + a3[k] == sum)
return true;
return false;
}
// Driver Code
static public void Main ()
{
int []a1 = {1 , 2 , 3 , 4 , 5};
int []a2 = {2 , 3 , 6 , 1 , 2};
int []a3 = {3 , 2 , 4 , 5 , 6};
int sum = 9;
int n1 = a1.Length;
int n2 = a2.Length;
int n3 = a3.Length;
if(findTriplet(a1, a2, a3, n1,
n2, n3, sum))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program to find three element
// from different three arrays such
// that that a + b + c is equal to
// given sum
// Function to check if there is an
// element from each array such that
// sum of the three elements is equal
// to given sum.
function findTriplet($a1, $a2, $a3,
$n1, $n2, $n3,
775
Chapter 126. Find three element from different three arrays such that that a + b + c =
sum
$sum)
{
for ( $i = 0; $i < $n1; $i++)
for ( $j = 0; $j < $n2; $j++)
for ( $k = 0; $k < $n3; $k++)
if ($a1[$i] + $a2[$j] + $a3[$k] == $sum)
return true;
return false;
}
// Driver Code
$a1 = array( 1 , 2 , 3 , 4 , 5 );
$a2 = array( 2 , 3 , 6 , 1 , 2 );
$a3 = array( 3 , 2 , 4 , 5 , 6 );
$sum = 9;
$n1 = count($a1);
$n2 = count($a2);
$n3 = count($a3);
if(findTriplet($a1, $a2, $a3, $n1,
$n2, $n3, $sum)==true)
echo "Yes" ;
else
echo "No";
// This code is contributed by anuj_67.
?>
Output :
Yes
An efficient solution is to store all elements of first array in hash table (unordered_set in
C++) and calculate sum of two elements last two array elements one by one and substract
from given number k and check in hash table if it’s exist in hash table then print exist and
otherwise not exist.
776
Chapter 126. Find three element from different three arrays such that that a + b + c =
sum
C++
777
Chapter 126. Find three element from different three arrays such that that a + b + c =
sum
int a1[] = { 1 , 2 , 3 , 4 , 5 };
int a2[] = { 2 , 3 , 6 , 1 , 2 };
int a3[] = { 3 , 2 , 4 , 5 , 6 };
int sum = 9;
int n1 = sizeof(a1) / sizeof(a1[0]);
int n2 = sizeof(a2) / sizeof(a2[0]);
int n3 = sizeof(a3) / sizeof(a3[0]);
findTriplet(a1, a2, a3, n1, n2, n3, sum)?
cout << "Yes" : cout << "No";
return 0;
}
Output :
Yes
Source
https://www.geeksforgeeks.org/find-three-element-from-different-three-arrays-such-that-that-a-b-c-k/
778
Chapter 127
779
Chapter 127. Find top k (or most frequent) numbers in a stream
of 2 as 2. So we keep 2 at the top and then rest of element with same frequency in sorted
order. So print, 2 1 3 5.
Below is the step by step algorithm to do this:
C++
780
Chapter 127. Find top k (or most frequent) numbers in a stream
Python
781
Chapter 127. Find top k (or most frequent) numbers in a stream
# increase the frequency
if a[m] in freq.keys():
freq[a[m]] += 1
else:
freq[a[m]] = 1
# store that element in top vector
top[k] = a[m]
i = top.index(a[m])
i -= 1
while i >= 0:
# compare the frequency and swap if higher
# frequency element is stored next to it
if (freq[top[i]] < freq[top[i + 1]]):
t = top[i]
top[i] = top[i + 1]
top[i + 1] = t
# if frequency is same compare the elements
# and swap if next element is high
elif ((freq[top[i]] == freq[top[i + 1]]) and (top[i] > top[i + 1])):
t = top[i]
top[i] = top[i + 1]
top[i + 1] = t
else:
break
i -= 1
# print top k elements
i = 0
while i < k and top[i] != 0:
print top[i],
i += 1
print
# Driver program to test above function
k = 4
arr = [ 5, 2, 1, 3, 2 ]
n = len(arr)
kTop(arr, n, k)
# This code is contributed by Sachin Bisht
Output:
782
Chapter 127. Find top k (or most frequent) numbers in a stream
5 2 5 1 2 5 1 2 3 5 2 1 3 5
Time Complexity: O( n * k )
Source
https://www.geeksforgeeks.org/find-top-k-or-most-frequent-numbers-in-a-stream/
783
Chapter 128
Asked in :Zoho
First We have to find the frequency of each element in a hash table freq. Now Our Task is
to Find top 3 elements in the hash table, To Find it We just use three pair type variable (
suppose x, y, z)in which first store the frequency and second store the actual number.
Algorithm
784
Chapter 128. Find top three repeated in array
z = y
y = x
x.first = fre[p]
x.second = p;
}
c) Else if (fre[p] !=0 && free[p] > y.first)
{
z = y
y.first = fre[p]
y.second = p
}
d) Else if (fre[p] !=0 && free[p] > z.first)
{
z.first = fre[p]
z.second = p
}
785
Chapter 128. Find top three repeated in array
786
Chapter 128. Find top three repeated in array
}
// Driver's Code
int main()
{
int arr[] = { 3, 4, 2, 3, 16, 3, 15,
16, 15, 15, 16, 2, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
top3Repeated(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-top-three-repeated-array/
787
Chapter 129
Naive Approach: Using two loops. For each charactrer of 1st string check whether it is
present in 2nd string or not. Likewise, for each character of 2nd string check whether it is
present in 1st string or not. Time Complexity O(n2 ) and extra would be required to handle
duplicates.
Efficient Approach: Use hashing. Use a hash table of size 26 for all the lowercase charac-
ters.
Initially, mark presence of each character as ‘0’ (denoting that the character is not present
in both the strings). Traverse the 1st string and mark presence of each character of 1st
string as ‘1’ (denoting 1st string) in the hash table. Now, traverse the 2nd string. For each
character of 2nd string, check whether its presence in the hash table is ‘1’ or not. If it is ‘1’,
788
Chapter 129. Find uncommon characters of the two strings
then mark its presence as ‘-1’ (denoting that the character is common to both the strings),
else mark its presence as ‘2’ (denoting 2nd string).
789
Chapter 129. Find uncommon characters of the two strings
// Driver program to test above
int main()
{
string str1 = "characters";
string str2 = "alphabets";
findAndPrintUncommonChars(str1, str2);
return 0;
}
Output:
b c l p r
Time Complexity: O(m + n), where m and n are the sizes of the two strings respectively.
Source
https://www.geeksforgeeks.org/find-uncommon-characters-two-strings/
790
Chapter 130
Method 1 (Using Two Loops) This is the simple way where two loops are used. Outer
loop is used to pick the elements one by one and inner loop compares the picked element
with rest of the elements. If Element is not equal to other elements than Print that Element.
Time Complexity : O(N * n)
Method 2 (Sorting) : Sort the elements using Merge Sort. O(n Log n). Now Traverse
List in linear time and check if current element is not equal to previous element then Print
O(N)
Please note that this method doesn’t preserve the original order of elements.
Time Complexity: O(NLogN)
Method 3 (Hashing)
We use the concept of Hash table Here, We traverse the link list from head to end. For
every newly encountered element, we put it in the hash table after that we again traverse
list and Print those elements whose frequency is 1.Time Complexity : O(N)
Below is the Implementation of this
791
Chapter 130. Find unique elements in linked list
792
Chapter 130. Find unique elements in linked list
int main()
{
struct Node* head = NULL;
// creating linked list
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 5);
push(&head, 3);
push(&head, 2);
push(&head, 4);
push(&head, 4);
push(&head, 1);
uniqueElements(head);
return 0;
}
Output:
1 2
Source
https://www.geeksforgeeks.org/find-unique-elements-linked-list/
793
Chapter 131
#include<bits/stdc++.h>
/* Return 1 if arr2[] is a subset of
arr1[] */
bool isSubset(int arr1[], int arr2[],
int m, int n)
{
794
Chapter 131. Find whether an array is subset of another array | Added Method 3
int i = 0;
int j = 0;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
if(arr2[i] == arr1[j])
break;
}
/* If the above inner loop was
not broken at all then arr2[i]
is not present in arr1[] */
if (j == m)
return 0;
}
/* If we reach here then all
elements of arr2[] are present
in arr1[] */
return 1;
}
// Driver code
int main()
{
int arr1[] = {11, 1, 13, 21, 3, 7};
int arr2[] = {11, 3, 7, 1};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
if(isSubset(arr1, arr2, m, n))
printf("arr2[] is subset of arr1[] ");
else
printf("arr2[] is not a subset of arr1[]");
getchar();
return 0;
}
Java
795
Chapter 131. Find whether an array is subset of another array | Added Method 3
C#
796
Chapter 131. Find whether an array is subset of another array | Added Method 3
797
Chapter 131. Find whether an array is subset of another array | Added Method 3
}
// This code is contributed by Sam007
PHP
<?php
/* Return 1 if arr2[] is a subset of
arr1[] */
function isSubset($arr1, $arr2, $m, $n)
{
$i = 0;
$j = 0;
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $m; $j++)
{
if($arr2[$i] == $arr1[$j])
break;
}
/* If the above inner loop was
not broken at all then arr2[i]
is not present in arr1[] */
if ($j == $m)
return 0;
}
/* If we reach here then all
elements of arr2[] are present
in arr1[] */
return 1;
}
// Driver code
$arr1 = array(11, 1, 13, 21, 3, 7);
$arr2 = array(11, 3, 7, 1);
$m = count($arr1);
$n = count($arr2);
if(isSubset($arr1, $arr2, $m, $n))
echo "arr2[] is subset of arr1[] ";
else
echo "arr2[] is not a subset of arr1[]";
// This code is contributed by anuj_67.
?>
798
Chapter 131. Find whether an array is subset of another array | Added Method 3
Output:
#include<stdio.h>
/* Fucntion prototypes */
void quickSort(int *arr, int si, int ei);
int binarySearch(int arr[], int low, int high, int x);
/* Return 1 if arr2[] is a subset of arr1[] */
bool isSubset(int arr1[], int arr2[], int m, int n)
{
int i = 0;
quickSort(arr1, 0, m-1);
for (i=0; i<n; i++)
{
if (binarySearch(arr1, 0, m-1, arr2[i]) == -1)
return 0;
}
/* If we reach here then all elements of arr2[]
are present in arr1[] */
return 1;
}
/* FOLLOWING FUNCTIONS ARE ONLY FOR SEARCHING AND SORTING PURPOSE */
/* Standard Binary Search function*/
int binarySearch(int arr[], int low, int high, int x)
{
if(high >= low)
{
int mid = (low + high)/2; /*low + (high - low)/2;*/
799
Chapter 131. Find whether an array is subset of another array | Added Method 3
/* Check if arr[mid] is the first occurrence of x.
arr[mid] is first occurrence if x is one of the following
is true:
(i) mid == 0 and arr[mid] == x
(ii) arr[mid-1] < x and arr[mid] == x
*/
if(( mid == 0 || x > arr[mid-1]) && (arr[mid] == x))
return mid;
else if(x > arr[mid])
return binarySearch(arr, (mid + 1), high, x);
else
return binarySearch(arr, low, (mid -1), x);
}
return -1;
}
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
*/
800
Chapter 131. Find whether an array is subset of another array | Added Method 3
Java
class Main
{
/* Return true if arr2[] is a subset of arr1[] */
static boolean isSubset(int arr1[], int arr2[], int m, int n)
{
int i = 0;
sort(arr1, 0, m-1);
for (i=0; i<n; i++)
{
if (binarySearch(arr1, 0, m-1, arr2[i]) == -1)
return false;
}
/* If we reach here then all elements of arr2[]
are present in arr1[] */
return true;
}
801
Chapter 131. Find whether an array is subset of another array | Added Method 3
/* FOLLOWING FUNCTIONS ARE ONLY FOR SEARCHING AND SORTING PURPOSE */
/* Standard Binary Search function*/
static int binarySearch(int arr[], int low, int high, int x)
{
if(high >= low)
{
int mid = (low + high)/2; /*low + (high - low)/2;*/
/* Check if arr[mid] is the first occurrence of x.
arr[mid] is first occurrence if x is one of the following
is true:
(i) mid == 0 and arr[mid] == x
(ii) arr[mid-1] < x and arr[mid] == x
*/
if(( mid == 0 || x > arr[mid-1]) && (arr[mid] == x))
return mid;
else if(x > arr[mid])
return binarySearch(arr, (mid + 1), high, x);
else
return binarySearch(arr, low, (mid -1), x);
}
return -1;
}
/* 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];
int i = (low-1); // index of smaller element
for (int j=low; j<high; 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;
}
802
Chapter 131. Find whether an array is subset of another array | Added Method 3
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
static void sort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
public static void main(String args[])
{
int arr1[] = {11, 1, 13, 21, 3, 7};
int arr2[] = {11, 3, 7, 1};
int m = arr1.length;
int n = arr2.length;
if(isSubset(arr1, arr2, m, n))
System.out.print("arr2[] is subset of arr1[] ");
else
System.out.print("arr2[] is not a subset of arr1[]");
}
}
Time Complexity: O(mLogm + nLogm). Please note that this will be the complexity if an
mLogm algorithm is used for sorting which is not the case in above code. In above code
Quick Sort is sued and worst case time complexity of Quick Sort is O(m^2)
803
Chapter 131. Find whether an array is subset of another array | Added Method 3
C++
#include <bits/stdc++.h>
using namespace std;
/* Return 1 if arr2[] is a subset of arr1[] */
bool isSubset(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
if (m < n)
return 0;
sort(arr1, arr1 + m);
sort(arr2, arr2 + n);
while (i < n && j < m )
{
if( arr1[j] <arr2[i] )
j++;
else if( arr1[j] == arr2[i] )
{
j++;
i++;
}
else if( arr1[j] > arr2[i] )
return 0;
}
return (i < n)? false : true;
}
/*Driver program to test above functions */
int main()
{
int arr1[] = {11, 1, 13, 21, 3, 7};
int arr2[] = {11, 3, 7, 1};
int m = sizeof(arr1)/sizeof(arr1[0]);
int n = sizeof(arr2)/sizeof(arr2[0]);
if(isSubset(arr1, arr2, m, n))
804
Chapter 131. Find whether an array is subset of another array | Added Method 3
Java
805
Chapter 131. Find whether an array is subset of another array | Added Method 3
C#
806
Chapter 131. Find whether an array is subset of another array | Added Method 3
return false;
}
if( i < n )
return false;
else
return true;
}
// Driver Code
public static void Main()
{
int []arr1 = {11, 1, 13, 21, 3, 7};
int []arr2 = {11, 3, 7, 1};
int m = arr1.Length;
int n = arr2.Length;
if(isSubset(arr1, arr2, m, n))
Console.Write("arr2 is a subset of arr1");
else
Console.Write("arr2 is not a subset of arr1");
}
}
// This code is contributed by nitin mittal.
PHP
<?php
/* Return 1 if arr2[] is a subset of arr1[] */
function isSubset( $arr1, $arr2, $m, $n)
{
$i = 0; $j = 0;
if ($m < $n)
return 0;
sort($arr1);
sort($arr2);
while ($i < $n and $j < $m )
{
if( $arr1[$j] <$arr2[$i] )
$j++;
else if( $arr1[$j] == $arr2[$i] )
{
807
Chapter 131. Find whether an array is subset of another array | Added Method 3
$j++;
$i++;
}
else if( $arr1[$j] > $arr2[$i] )
return 0;
}
return ($i < $n) ? false : true;
}
/*Driver program to test above functions */
$arr1 = array(11, 1, 13, 21, 3, 7);
$arr2 = array(11, 3, 7, 1);
$m = count($arr1);
$n = count($arr2);
if(isSubset($arr1, $arr2, $m, $n))
echo "arr2[] is subset of arr1[] ";
else
echo "arr2[] is not a subset of arr1[] ";
// This code is contributed by anuj_67.
?>
Output:
Time Complexity: O(mLogm + nLogn) which is better than method 2. Please note that
this will be the complexity if an nLogn algorithm is used for sorting both arrays which is not
the case in above code. In above code Quick Sort is sued and worst case time complexity of
Quick Sort is O(n^2)
Method 4 (Use Hashing)
1) Create a Hash Table for all the elements of arr1[].
2) Traverse arr2[] and search for each element of arr2[] in the Hash Table. If element is not
found then return 0.
3) If all elements are found then return 1.
808
Chapter 131. Find whether an array is subset of another array | Added Method 3
Note that method 1, method 2 and method 4 don’t handle the cases when we have duplicates
in arr2[]. For example, {1, 4, 4, 2} is not a subset of {1, 4, 2}, but these methods will print
it as a subset.
Improved By : Sam007, nitin mittal, vt_m
809
Chapter 131. Find whether an array is subset of another array | Added Method 3
Source
https://www.geeksforgeeks.org/find-whether-an-array-is-subset-of-another-array-set-1/
810
Chapter 132
Find winner of an election where votes are represented as candidate names - GeeksforGeeks
Given an array of names of candidates in an election. A candidate name in array represents
a vote casted to the candidate. Print the name of candidates received Max vote. If there is
tie, print lexicographically smaller name.
Examples:
A simple solution is to run two loops and count occurrences of every word. Time com-
plexity of this solution is O(n * n * MAX_WORD_LEN).
An efficient solution is to use Hashing. We insert all votes in a hash map and keep track of
counts of different names. Finally we traverse the map and print the person with maximum
votes.
811
Chapter 132. Find winner of an election where votes are represented as candidate names
import java.util.*;
public class ElectoralVotingBallot
{
/* We have four Candidates with name as 'John',
'Johnny', 'jamie', 'jackie'.
The votes in String array are as per the
votes casted. Print the name of candidates
received Max vote. */
public static void findWinner(String votes[])
{
// Insert all votes in a hashmap
Map<String,Integer> map =
new HashMap<String, Integer>();
for (String str : votes)
{
if (map.keySet().contains(str))
map.put(str, map.get(str) + 1);
else
map.put(str, 1);
}
// Traverse through map to find the candidate
// with maximum votes.
int maxValueInMap = 0;
String winner = "";
for (Map.Entry<String,Integer> entry : map.entrySet())
{
String key = entry.getKey();
Integer val = entry.getValue();
if (val > maxValueInMap)
{
maxValueInMap = val;
winner = key;
}
// If there is a tie, pick lexicographically
// smaller.
else if (val == maxValueInMap &&
winner.compareTo(key) > 0)
winner = key;
}
System.out.println(winner);
}
// Driver code
public static void main(String[] args)
{
812
Chapter 132. Find winner of an election where votes are represented as candidate names
Output:
John
Another efficient solution is to use Trie. Please refer most frequent word in an array of
strings.
Improved By : Ankit Verma 10
Source
https://www.geeksforgeeks.org/find-winner-election-votes-represented-candidate-names/
813
Chapter 133
C++
814
Chapter 133. First element occurring k times in an array
Python3
815
Chapter 133. First element occurring k times in an array
Output:
Source
https://www.geeksforgeeks.org/first-element-occurring-k-times-array/
816
Chapter 134
Input : 10->20->30->10->20->40->30->NULL
Output :First Non-repeating element is 40.
Input :1->1->2->2->3->4->3->4->5->NULL
Output :First Non-repeating element is 5.
Input :1->1->2->2->3->4->3->4->NULL
Output :No NOn-repeating element is found.
817
Chapter 134. First non-repeating in a linked list
};
/* Function to find the first non-repeating
element in the linked list */
int firstNonRepeating(struct Node *head)
{
// Create an empty map and insert all linked
// list elements into hash table
unordered_map<int, int> mp;
for (Node *temp=head; temp!=NULL; temp=temp->next)
mp[temp->data]++;
// Traverse the linked list again and return
// the first node whose count is 1
for (Node *temp=head; temp!=NULL; temp=temp->next)
if (mp[temp->data] == 1)
return temp->data;
return -1;
}
/* Function to push a node */
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;
}
/* Driver program to test above function*/
int main()
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 35);
push(&head, 85);
push(&head, 20);
push(&head, 18);
push(&head, 15);
push(&head, 85);
cout << firstNonRepeating(head);
return 0;
}
818
Chapter 134. First non-repeating in a linked list
Output:
15
Further Optimizations:
The above solution requires two traversals of linked list. In case we have many repeating
elements, we can save one traversal by storing positions also in hash table. Please refer last
method of Given a string, find its first non-repeating character for details.
Source
https://www.geeksforgeeks.org/first-non-repeating-linked-list/
819
Chapter 135
For each element in 1st array count elements less than or equal to it in 2nd array | Set 2 -
GeeksforGeeks
Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element
in arr1[] count elements less than or equal to it in array arr2[].
Examples:
This problem is already discussed in the previous post. In this article, a more optimized
linear time solution to the above problem is discussed. The approach discussed here works
for arrays with values in small range. A range of values that can be used as index in an
array.
The idea is to use an array to create a direct address tableinitially filled with zero, such that
hash[i] gives the count of an element in the second array arr2[]. Now, calculate pre-sum
of the hash array. Doing this, hash[i] will now give the count of elements less than or equal
to in second array arr2[].
820
Chapter 135. For each element in 1st array count elements less than or equal to it in 2nd
array | Set 2
C++
821
Chapter 135. For each element in 1st array count elements less than or equal to it in 2nd
array | Set 2
m = sizeof(arr1) / sizeof(arr1[0]);
n = sizeof(arr2) / sizeof(arr2[0]);
countEleLessThanOrEqual(arr1, m, arr2, n);
return 0;
}
Java
822
Chapter 135. For each element in 1st array count elements less than or equal to it in 2nd
array | Set 2
// Traverse arr1[] and
// print hash[arr[i]]
for (int i = 0; i < m; i++)
{
System.out.print(hash[arr1[i]] + " ");
}
}
// Driver code
public static void main (String[] args)
{
int arr1[] = {1, 2, 3, 4, 7, 9};
int arr2[] = {0, 1, 2, 1, 1, 4};
int m, n;
m = arr1.length;
n = arr2.length;
countEleLessThanOrEqual(arr1, m, arr2, n);
}
}
// This code is contributed
// by inder_verma
Output:
4 5 5 6 6 6
Improved By : inderDuMCA
Source
https://www.geeksforgeeks.org/for-each-element-in-1st-array-count-elements-less-than-or-equal-to-it-in-2nd-array-
823
Chapter 136
Frequency Measuring
Techniques for Competitive
Programming
We run two loops. For every item count number of times it occurs. To avoid duplicate
printing, keep track of processed items.
824
Chapter 136. Frequency Measuring Techniques for Competitive Programming
Output:
10 3
20 4
5 1
Optimized methods :
Measuring frequencies when elements are limited by value
If our input array has small values, we can use array elements as index in a count array and
increment count. In below example, elements are maximum 10.
825
Chapter 136. Frequency Measuring Techniques for Competitive Programming
2 1
3 1
5 3
6 3
10 2
Output:
1 1
2 1
3 1
5 3
6 3
10 2
826
Chapter 136. Frequency Measuring Techniques for Competitive Programming
Output:
G 2
e 4
f 1
k 2
o 1
r 1
s 2
827
Chapter 136. Frequency Measuring Techniques for Competitive Programming
#include <bits/stdc++.h>
using namespace std;
const int limit = 25;
void countFreq(string str)
{
// Create an array to store counts. The size
// of array is limit+1 and all values are
// initially 0
vector<int> count(limit+1, 0);
// Traverse through string characters and
// count frequencies
for (int i = 0; i < str.length(); i++)
count[str[i] - 'A']++;
for (int i = 0; i <= limit; i++)
if (count[i] > 0)
cout << (char)(i + 'A') << " " << count[i] << endl;
}
int main()
{
string str = "GEEKSFORGEEKS";
countFreq(str);
return 0;
}
Output:
E 4
F 1
G 2
K 2
O 1
R 1
S 2
828
Chapter 136. Frequency Measuring Techniques for Competitive Programming
Output:
5 1
10 3
20 4
Output:
5 1
10 3
20 4
829
Chapter 136. Frequency Measuring Techniques for Competitive Programming
void countFreq(int arr[], int n)
{
unordered_map<int, int> mp;
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++)
mp[arr[i]]++;
// To print elements according to first
// occurrence, traverse array one more time
// print frequencies of elements and mark
// frequencies as -1 so that same element
// is not printed multiple times.
for (int i = 0; i < n; i++) {
if (mp[arr[i]] != -1)
{
cout << arr[i] << " " << mp[arr[i]] << endl;
mp[arr[i]] = -1;
}
}
}
int main()
{
int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
countFreq(arr, n);
return 0;
}
Output:
10 3
20 4
5 1
Output:
10 3
20 4
5 1
830
Chapter 136. Frequency Measuring Techniques for Competitive Programming
In Java, we can get elements in same order using LinkedHashMap. Therefore we do not
need an extra loop.
Lot of problems are based on frequency measurement and will be a cheesecake if we know
how to calculate frequency of various elements in a given array. For example try the given
below problems which are based on frequency measurement:
1. Anagrams
2. Sorting Elements of an Array by Frequency
3. Single Number
Source
https://www.geeksforgeeks.org/frequency-measurement-techniques-for-competitive-programming/
831
Chapter 137
Frequency of a string in an
array of strings
Method 1 (Simple)
The idea is simple, for every query string we compare it with all strings given in array. If
the query string is matches, we increment count.
Java
832
Chapter 137. Frequency of a string in an array of strings
C#
833
Chapter 137. Frequency of a string in an array of strings
static void answerQueries(String []arr, String []q)
{
for (int i = 0; i < q.Length; i++)
Console.Write(search(arr, q[i]) + " ");
}
// Driver code
public static void Main()
{
String []arr = {"aba","baba","aba","xzxb"};
String []q = {"aba","xzxb","ab"};
answerQueries(arr, q);
}
}
//This code is contributed by nitin mittal
Output:
2 1 0
834
Chapter 137. Frequency of a string in an array of strings
Trie()
{
for(int i=0; i<MAX_CHAR; i++)
node[i] = NULL;
cnt = 0;
}
};
/* function to insert a string into the Trie*/
Trie *insert(Trie *root,string s)
{
Trie *temp = root;
int n = s.size();
for(int i=0; i<n; i++)
{
/*calculation ascii value*/
int index = s[i]-'a';
/* If the given node is not already
present in the Trie than create
the new node*/
if (!root->node[index])
root->node[index] = new Trie();
root = root->node[index];
}
root->cnt++;
return temp;
}
/* Returns count of occurrences of s in Trie*/
int search(Trie *root, string s)
{
int n = s.size();
for (int i=0; i<n; i++)
{
int index = s[i]-'a';
if (!root->node[index])
return 0;
root = root->node[index];
}
return root->cnt;
}
void answerQueries(string arr[], int n, string q[],
int m)
{
Trie *root = new Trie();
835
Chapter 137. Frequency of a string in an array of strings
/* inserting in Trie */
for (int i=0; i<n; i++)
root = insert(root,arr[i]);
/* searching the strings in Trie */
for (int i=0; i<m; i++)
cout << search(root, q[i]) << " ";
}
/* Driver code */
int main()
{
string arr[] = {"aba","baba","aba","xzxb"};
int n = sizeof(arr)/sizeof(arr[0]);
string q[] = {"aba","xzxb","ab"};
int m = sizeof(q)/sizeof(q[0]);
answerQueries(arr, n, q, m);
return 0;
}
Output:
2
1
0
Method 3 (Hashing)
We can use a hash map and insert all given strings into it. For every query string, we simply
do a look-up in the hash map.
Please referData Structure for Dictionary for comparison of hashing and Trie based solutions.
Improved By : nitin mittal
Source
https://www.geeksforgeeks.org/frequency-of-a-string-in-an-array-of-strings/
836
Chapter 138
Input : arr[] = { 1, 2, 1, 2 }
Output : Player 1 wins
From above examples, we can observe that if number of count of distinct element is even,
first player always wins. Else second player wins.
Lets take an another example :
837
Chapter 138. Game of replacing array elements
int arr[] = 1, 2, 3, 4, 5, 6
Here number of distinct element is even(n). If player 1 pick any two number lets say (4, 1),
then we left with n-1 distinct element. So player second left with n-1 distinct element. This
precess go on until distinct element become 1. Here n = 6
Player : P1 p2 P1 p2 P1 P2
distinct : [n, n-1, n-2, n-3, n-4, n-5 ]
Output:
Player 1 Wins
838
Chapter 138. Game of replacing array elements
Source
https://www.geeksforgeeks.org/game-replacing-array-elements/
839
Chapter 139
Given a sequence of words, print all anagrams together using STL - GeeksforGeeks
Given an array of words, print all anagrams together. For example, if the given array is
{“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”.
Other approaches are discussed here in these posts
1) given-a-sequence-of-words-print-all-anagrams-together
2) given-a-sequence-of-words-print-all-anagrams-together-set-2
Here is HashMap solution using C++ Standard Template Library.
Approach :
1) Store the vector elements in HashMap with key as the sorted string
2) if key is same, then add string to value of HashMap(string vector)
3) Traverse the HashMap and print the anagram strings
840
Chapter 139. Given a sequence of words, print all anagrams together using STL
841
Chapter 139. Given a sequence of words, print all anagrams together using STL
arr.push_back("geeksforgeeks");
arr.push_back("abcd");
arr.push_back("forgeeksgeeks");
arr.push_back("zuiqkeegs");
arr.push_back("cat");
arr.push_back("act");
arr.push_back("tca");
// utility function for storing strings
// into hashmap
storeInMap(arr);
return 0;
}
Source
https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together-using-stl/
842
Chapter 140
1) Create two auxiliary arrays index[] and words[]. Copy all given words to words[] and
store the original indexes in index[]
index[]: 0 1 2 3 4
words[]: cat dog tac god act
843
Chapter 140. Given a sequence of words, print all anagrams together | Set 1
index[]: 0 1 2 3 4
words[]: act dgo act dgo act
3) Sort the words array. Compare individual words using strcmp() to sort
index: 0 2 4 1 3
words[]: act act act dgo dgo
4) All anagrams come together. But words are changed in words array. To print the original
words, take index from the index array and use it in the original array. We get
Following are the implementations of the above algorithm. In the following program, an
array of structure “Word” is used to store both index and word arrays. DupArray is another
structure that stores array of structure “Word”.
C/C++
844
Chapter 140. Given a sequence of words, print all anagrams together | Set 1
int i;
for (i = 0; i < size; ++i) {
dupArray->array[i].index = i;
dupArray->array[i].str = (char*)malloc(strlen(str[i]) + 1);
strcpy(dupArray->array[i].str, str[i]);
}
return dupArray;
}
// Compare two characters. Used in qsort() for sorting an array of
// characters (Word)
int compChar(const void* a, const void* b)
{
return *(char*)a - *(char*)b;
}
// Compare two words. Used in qsort() for sorting an array of words
int compStr(const void* a, const void* b)
{
struct Word* a1 = (struct Word*)a;
struct Word* b1 = (struct Word*)b;
return strcmp(a1->str, b1->str);
}
// Given a list of words in wordArr[],
void printAnagramsTogether(char* wordArr[], int size)
{
// Step 1: Create a copy of all words present in given wordArr.
// The copy will also have orignal indexes of words
struct DupArray* dupArray = createDupArray(wordArr, size);
// Step 2: Iterate through all words in dupArray and sort
// individual words.
int i;
for (i = 0; i < size; ++i)
qsort(dupArray->array[i].str,
strlen(dupArray->array[i].str), sizeof(char), compChar);
// Step 3: Now sort the array of words in dupArray
qsort(dupArray->array, size, sizeof(dupArray->array[0]), compStr);
// Step 4: Now all words in dupArray are together, but these
// words are changed. Use the index member of word struct to
// get the corresponding original word
for (i = 0; i < size; ++i)
printf("%s ", wordArr[dupArray->array[i].index]);
}
845
Chapter 140. Given a sequence of words, print all anagrams together | Set 1
// Driver program to test above functions
int main()
{
char* wordArr[] = { "cat", "dog", "tac", "god", "act" };
int size = sizeof(wordArr) / sizeof(wordArr[0]);
printAnagramsTogether(wordArr, size);
return 0;
}
Java
846
Chapter 140. Given a sequence of words, print all anagrams together | Set 1
}
}
}
// Compare two words. Used in Arrays.sort() for
// sorting an array of words
static class compStr implements Comparator<Word> {
public int compare(Word a, Word b)
{
return a.str.compareTo(b.str);
}
}
// Given a list of words in wordArr[],
static void printAnagramsTogether(String wordArr[],
int size)
{
// Step 1: Create a copy of all words present
// in given wordArr. The copy will also have
// original indexes of words
DupArray dupArray = new DupArray(wordArr, size);
// Step 2: Iterate through all words in
// dupArray and sort individual words.
int i;
for (i = 0; i < size; ++i) {
char[] char_arr = dupArray.array[i].str.toCharArray();
Arrays.sort(char_arr);
dupArray.array[i].str = new String(char_arr);
}
// Step 3: Now sort the array of words in
// dupArray
Arrays.sort(dupArray.array, new compStr());
// Step 4: Now all words in dupArray are together,
// but these words are changed. Use the index
// member of word struct to get the corresponding
// original word
for (i = 0; i < size; ++i)
System.out.print(wordArr[dupArray.array[i].index] + " ");
}
// Driver program to test above functions
public static void main(String args[])
{
String wordArr[] = { "cat", "dog", "tac", "god", "act" };
int size = wordArr.length;
847
Chapter 140. Given a sequence of words, print all anagrams together | Set 1
printAnagramsTogether(wordArr, size);
}
}
// This code is contributed by Sumit Ghosh
Python
848
Chapter 140. Given a sequence of words, print all anagrams together | Set 1
# Driver program
wordArr = ["cat", "dog", "tac", "god", "act"]
size = len(wordArr)
printAnagramsTogether(wordArr, size)
# This code is contributed by BHAVYA JAIN
Output:
Time Complexity: Let there be N words and each word has maximum M characters. The
upper bound is O(NMLogM + MNLogN).
Step 2 takes O(NMLogM) time. Sorting a word takes maximum O(MLogM) time. So
sorting N words takes O(NMLogM) time. step 3 takes O(MNLogN) Sorting array of words
takes NLogN comparisons. A comparison may take maximum O(M) time. So time to sort
array of words will be O(MNLogN).
Using hashmap
Here, we will sort each word, calculate its hashcode and then put it in a map where the key
will be hashcode generated after sorting. The value of the map will be a list containing all
the words which have same hashcode after sorting.
Lastly, we will print all values from the hashmap where size of values will be greater than 1.
import java.util.*;
public class FindAnagrams {
private static void printAnagrams(String arr[])
{
HashMap<Integer, List<String> > map = new HashMap<>();
// loop over all words
for (int i = 0; i < arr.length; i++) {
// convert to char array, sort and
// then re-convert to string
String word = arr[i];
char[] letters = word.toCharArray();
Arrays.sort(letters);
String newWord = new String(letters);
// calculate hashcode of string
// after sorting
int n = newWord.hashCode();
if (map.containsKey(n)) {
849
Chapter 140. Given a sequence of words, print all anagrams together | Set 1
Output :
850
Chapter 140. Given a sequence of words, print all anagrams together | Set 1
Source
https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together/
851
Chapter 141
C++
852
Chapter 141. Given a sequence of words, print all anagrams together | Set 2
#include <ctype.h>
#define NO_OF_CHARS 26
// Structure to represent list node for indexes of words in
// the given sequence. The list nodes are used to connect
// anagrams at leaf nodes of Trie
struct IndexNode
{
int index;
struct IndexNode* next;
};
// Structure to represent a Trie Node
struct TrieNode
{
bool isEnd; // indicates end of word
struct TrieNode* child[NO_OF_CHARS]; // 26 slots each for 'a' to 'z'
struct IndexNode* head; // head of the index list
};
// A utility function to create a new Trie node
struct TrieNode* newTrieNode()
{
struct TrieNode* temp = new TrieNode;
temp->isEnd = 0;
temp->head = NULL;
for (int i = 0; i < NO_OF_CHARS; ++i)
temp->child[i] = NULL;
return temp;
}
/* Following function is needed for library function qsort(). Refer
http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */
int compare(const void* a, const void* b)
{ return *(char*)a - *(char*)b; }
/* A utility function to create a new linked list node */
struct IndexNode* newIndexNode(int index)
{
struct IndexNode* temp = new IndexNode;
temp->index = index;
temp->next = NULL;
return temp;
}
// A utility function to insert a word to Trie
853
Chapter 141. Given a sequence of words, print all anagrams together | Set 2
854
Chapter 141. Given a sequence of words, print all anagrams together | Set 2
printAnagramsUtil(root->child[i], wordArr);
}
// The main function that prints all anagrams together. wordArr[] is input
// sequence of words.
void printAnagramsTogether(char* wordArr[], int size)
{
// Create an empty Trie
struct TrieNode* root = NULL;
// Iterate through all input words
for (int i = 0; i < size; ++i)
{
// Create a buffer for this word and copy the word to buffer
int len = strlen(wordArr[i]);
char *buffer = new char[len+1];
strcpy(buffer, wordArr[i]);
// Sort the buffer
qsort( (void*)buffer, strlen(buffer), sizeof(char), compare );
// Insert the sorted buffer and its original index to Trie
insert(&root, buffer, i);
}
// Traverse the built Trie and print all anagrms together
printAnagramsUtil(root, wordArr);
}
// Driver program to test above functions
int main()
{
char* wordArr[] = {"cat", "dog", "tac", "god", "act", "gdo"};
int size = sizeof(wordArr) / sizeof(wordArr[0]);
printAnagramsTogether(wordArr, size);
return 0;
}
Java
855
Chapter 141. Given a sequence of words, print all anagrams together | Set 2
856
Chapter 141. Given a sequence of words, print all anagrams together | Set 2
{
root.isEnd = true;
root.head.add(index);
}
}
return root;
}
// This function traverses the built trie. When a leaf
// node is reached, all words connected at that leaf
// node are anagrams. So it traverses the list at leaf
// node and uses stored index to print original words
static void printAnagramsUtil(TrieNode root,
String wordArr[])
{
if (root == null)
return;
// If a lead node is reached, print all anagrams
// using the indexes stored in index linked list
if (root.isEnd)
{
// traverse the list
for(Integer pCrawl: root.head)
System.out.println(wordArr[pCrawl]);
}
for (int i = 0; i < NO_OF_CHARS; ++i)
printAnagramsUtil(root.child[i], wordArr);
}
// The main function that prints all anagrams together.
// wordArr[] is input sequence of words.
static void printAnagramsTogether(String wordArr[],
int size)
{
// Create an empty Trie
TrieNode root = null;
// Iterate through all input words
for (int i = 0; i < size; ++i)
{
// Create a buffer for this word and copy the
// word to buffer
char[] buffer = wordArr[i].toCharArray();
// Sort the buffer
Arrays.sort(buffer);
857
Chapter 141. Given a sequence of words, print all anagrams together | Set 2
// Insert the sorted buffer and its original
// index to Trie
root = insert(root, new String(buffer), i, 0);
}
// Traverse the built Trie and print all anagrms
// together
printAnagramsUtil(root, wordArr);
}
// Driver program to test above functions
public static void main(String args[])
{
String wordArr[] = {"cat", "dog", "tac", "god",
"act", "gdo"};
int size = wordArr.length;
printAnagramsTogether(wordArr, size);
}
}
// This code is contributed by Sumit Ghosh
Output:
cat
tac
act
dog
god
gdo
Improved By : reyaz_ahmed
Source
https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together-set-2/
858
Chapter 142
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.
859
Chapter 142. 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
860
Chapter 142. 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()
861
Chapter 142. 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++
862
Chapter 142. 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
863
Chapter 142. 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
864
Chapter 142. Given an array A[] and a number x, check for pair in A[] with sum as x
C#
865
Chapter 142. 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;
}
}
866
Chapter 142. Given an array A[] and a number x, check for pair in A[] with sum as x
PHP
867
Chapter 142. 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
?>
868
Chapter 142. Given an array A[] and a number x, check for pair in A[] with sum as x
Output :
869
Chapter 142. Given an array A[] and a number x, check for pair in A[] with sum as x
C++
Java
870
Chapter 142. 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
871
Chapter 142. Given an array A[] and a number x, check for pair in A[] with sum as x
C#
872
Chapter 142. 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/
873
Chapter 143
Input: arr[] = {{11, 20}, {30, 40}, {5, 10}, {40, 30}, {10, 5}}
Output: Following pairs have symmetric pairs
(30, 40)
(5, 10)
We strongly recommend you to minimize your browser and try this yourself
first.
A Simple Solution is to go through every pair, and check every other pair for symmetric.
This solution requires O(n2 ) time.
A Better Solution is to use sorting. Sort all pairs by first element. For every pair, do
binary search for second element in the given array, i.e., check if second element of this pair
exists as first element in array. If found, then compare first element of pair with second
element. Time Complexity of this solution is O(nLogn).
An Efficient Solution is to use Hashing. First element of pair is used as key and second
element is used as value. The idea is traverse all pairs one by one. For every pair, check
if its second element is in hash table. If yes, then compare the first element with value
of matched entry of hash table. If the value and the first element match, then we found
symmetric pairs. Else, insert first element as key and second element as value.
874
Chapter 143. Given an array of pairs, find all symmetric pairs in it
#include<bits/stdc++.h>
using namespace std;
// A C++ program to find all symmetric pairs in a given array of pairs
// Print all pairs that have a symmetric counterpart
void findSymPairs(int arr[][2], int row)
{
// Creates an empty hashMap hM
unordered_map<int, int> hM;
// Traverse through the given array
for (int i = 0; i < row; i++)
{
// First and second elements of current pair
int first = arr[i][0];
int sec = arr[i][1];
// If found and value in hash matches with first
// element of this pair, we found symmetry
if (hM.find(sec) != hM.end() && hM[sec] == first)
cout << "(" << sec << ", " << first << ")" <<endl;
else // Else put sec element of this pair in hash
hM[first] = sec;
}
}
// Drive method
int main()
{
int arr[5][2];
arr[0][0] = 11; arr[0][1] = 20;
arr[1][0] = 30; arr[1][1] = 40;
arr[2][0] = 5; arr[2][1] = 10;
arr[3][0] = 40; arr[3][1] = 30;
arr[4][0] = 10; arr[4][1] = 5;
findSymPairs(arr, 5);
}
//This is contributed by Chhavi
Java
875
Chapter 143. Given an array of pairs, find all symmetric pairs in it
import java.util.HashMap;
class SymmetricPairs {
// Print all pairs that have a symmetric counterpart
static void findSymPairs(int arr[][])
{
// Creates an empty hashMap hM
HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>();
// Traverse through the given array
for (int i = 0; i < arr.length; i++)
{
// First and second elements of current pair
int first = arr[i][0];
int sec = arr[i][1];
// Look for second element of this pair in hash
Integer val = hM.get(sec);
// If found and value in hash matches with first
// element of this pair, we found symmetry
if (val != null && val == first)
System.out.println("(" + sec + ", " + first + ")");
else // Else put sec element of this pair in hash
hM.put(first, sec);
}
}
// Drive method
public static void main(String arg[])
{
int arr[][] = new int[5][2];
arr[0][0] = 11; arr[0][1] = 20;
arr[1][0] = 30; arr[1][1] = 40;
arr[2][0] = 5; arr[2][1] = 10;
arr[3][0] = 40; arr[3][1] = 30;
arr[4][0] = 10; arr[4][1] = 5;
findSymPairs(arr);
}
}
Output:
876
Chapter 143. Given an array of pairs, find all symmetric pairs in it
Time Complexity of this solution is O(n) under the assumption that hash search and insert
methods work in O(1) time.
This article is contributed by Shivam Agrawal. 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/given-an-array-of-pairs-find-all-symmetric-pairs-in-it/
877
Chapter 144
Given two unsorted arrays, find all pairs whose sum is x - GeeksforGeeks
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays
whose sum is equal to x.
Examples:
Asked in : Amazon
A Naive approach is to simply run two loops and pick elements from both arrays. One
by one check that both elements sum is equal to given value x or not.
C++
878
Chapter 144. Given two unsorted arrays, find all pairs whose sum is x
#include<bits/stdc++.h>
using namespace std;
// Function to print all pairs in both arrays
// whose sum is equal to given value x
void findPairs(int arr1[], int arr2[], int n,
int m, int x)
{
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (arr1[i] + arr2[j] == x)
cout << arr1[i] << " "
<< arr2[j] << endl;
}
// Driver code
int main()
{
int arr1[] = {1, 2, 3, 7, 5, 4};
int arr2[] = {0, 7, 4, 3, 2, 1};
int n = sizeof(arr1)/sizeof(int);
int m = sizeof(arr2)/sizeof(int);
int x = 8;
findPairs(arr1, arr2, n, m, x);
return 0;
}
Java
879
Chapter 144. Given two unsorted arrays, find all pairs whose sum is x
// Driver code
public static void main(String[] args)
{
int arr1[] = {1, 2, 3, 7, 5, 4};
int arr2[] = {0, 7, 4, 3, 2, 1};
int x = 8;
findPairs(arr1, arr2, arr1.length, arr2.length, x);
}
}
// This code is contributed
// by sunnysingh
Python3
C#
880
Chapter 144. Given two unsorted arrays, find all pairs whose sum is x
using System;
class GFG
{
// Function to print all
// pairs in both arrays
// whose sum is equal to
// given value x
static void findPairs(int []arr1, int []arr2,
int n, int m, int x)
{
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (arr1[i] + arr2[j] == x)
Console.WriteLine(arr1[i] + " " +
arr2[j] );
}
// Driver code
static void Main()
{
int []arr1 = {1, 2, 3, 7, 5, 4};
int []arr2 = {0, 7, 4, 3, 2, 1};
int x = 8;
findPairs(arr1, arr2,
arr1.Length,
arr2.Length, x);
}
}
// This code is contributed
// by Sam007
PHP
<?php
// PHP program to find all pairs
// in both arrays whose sum is
// equal to given value x
// Function to print all pairs
// in both arrays whose sum is
// equal to given value x
function findPairs($arr1, $arr2,
$n, $m, $x)
{
for ($i = 0; $i < $n; $i++)
881
Chapter 144. Given two unsorted arrays, find all pairs whose sum is x
Output:
1 7
7 1
5 3
4 4
C++
882
Chapter 144. Given two unsorted arrays, find all pairs whose sum is x
Java
883
Chapter 144. Given two unsorted arrays, find all pairs whose sum is x
Output:
6 2
4 4
6 2
7 1
Source
https://www.geeksforgeeks.org/given-two-unsorted-arrays-find-pairs-whose-sum-x/
884
Chapter 145
885
Chapter 145. Graph representations using set and hash
Below is the code for adjacency list representation of an undirected graph using sets:
886
Chapter 145. Graph representations using set and hash
887
Chapter 145. Graph representations using set and hash
Output:
Pros: Queries like whether there is an edge from vertex u to vertex v can be done in O(log
V).
Cons:
888
Chapter 145. Graph representations using set and hash
#include <bits/stdc++.h>
using namespace std;
struct Graph {
int V;
unordered_set<int>* adjList;
};
// A utility function that creates a graph of
// V vertices
Graph* createGraph(int V)
{
Graph* graph = new Graph;
graph->V = V;
// Create an array of sets representing
// adjacency lists. Size of the array will be V
graph->adjList = new unordered_set<int>[V];
return graph;
}
// Adds an edge to an undirected graph
void addEdge(Graph* graph, int src, int dest)
{
// Add an edge from src to dest. A new
// element is inserted to the adjacent
// list of src.
graph->adjList[src].insert(dest);
// Since graph is undirected, add an edge
// from dest to src also
graph->adjList[dest].insert(src);
}
// A utility function to print the adjacency
// list representation of graph
void printGraph(Graph* graph)
{
for (int i = 0; i < graph->V; ++i) {
unordered_set<int> lst = graph->adjList[i];
cout << endl << "Adjacency list of vertex "
<< i << endl;
for (auto itr = lst.begin(); itr != lst.end(); ++itr)
cout << *itr << " ";
cout << endl;
}
889
Chapter 145. Graph representations using set and hash
}
// Searches for a given edge in the graph
void searchEdge(Graph* graph, int src, int dest)
{
auto itr = graph->adjList[src].find(dest);
if (itr == graph->adjList[src].end())
cout << endl << "Edge from " << src
<< " to " << dest << " not found."
<< endl;
else
cout << endl << "Edge from " << src
<< " to " << dest << " found."
<< endl;
}
// Driver code
int main()
{
// Create the graph given in the above figure
int V = 5;
struct Graph* graph = createGraph(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
// Print the adjacency list representation of
// the above graph
printGraph(graph);
// Search the given edge in the graph
searchEdge(graph, 2, 1);
searchEdge(graph, 0, 3);
return 0;
}
Output :
890
Chapter 145. Graph representations using set and hash
4 3 2 0
Pros:
• Queries like whether there is an edge from vertex u to vertex v can be done in O(1).
• Adding an edge takes O(1).
Cons:
Note : adjacency matrix representation is the most optimized for edge search, but
space requirements of adjacency matrix are comparatively high for big sparse graphs. More-
over adjacency matrix has other disadvantages as well like BFS and DFS become costly as
we can’t quickly get all adjacent of a node.
Source
https://www.geeksforgeeks.org/graph-representations-using-set-hash/
891
Chapter 146
S.length = T.length
and
S[i] = T[i] + K for
1 <= i <= S.length for a constant integer K
For example strings {acd, dfg, wyz, yab, mop} are shifted versions of each other.
Output : a x
acd dfg wyz yab mop
bdfh moqs
All shifted strings are grouped together.
We can see a pattern among string of one group, the difference between consecutive charac-
ters for all character of string are equal. As in above example take acd, dfg and mop
a c d -> 2 1
d f g -> 2 1
m o p -> 2 1
Since the differences are same, we can use this to identify strings that belong to same group.
The idea is to form a string of differences as key. If a string with same difference string is
892
Chapter 146. Group Shifted String
found, then this string also belongs to same group. For example, above three strings have
same difference string, that is “21”.
In below implementation, we add ‘a’ to every difference and store 21 as “ba”.
893
Chapter 146. Group Shifted String
Output:
a x
acd dfg wyz yab mop
bdfh moqs
Source
https://www.geeksforgeeks.org/group-shifted-string/
894
Chapter 147
Simple Solution is to use nested loops. The outer loop traverses array elements one by
one. The inner loop checks if this is first occurrence, if yes, then the inner loop prints it
and all other occurrences.
C++
895
Chapter 147. Group multiple occurrence of array elements ordered by first occurrence
Python3
896
Chapter 147. Group multiple occurrence of array elements ordered by first occurrence
Output:
4 4 4 6 6 9 9 2 3 10
897
Chapter 147. Group multiple occurrence of array elements ordered by first occurrence
……….a) Get its count and print the element ‘count’ times.
……….b) Delete the element from BST.
Time Complexity of the above solution is O(nLogn).
Hashing based Method: We can also use hashing. The idea is to replace Binary Search
Tree with a Hash Map in above algorithm.
Below is Implementation of hashing based solution.
Java
898
Chapter 147. Group multiple occurrence of array elements ordered by first occurrence
}
}
}
// Driver method to test above method
public static void main (String[] args)
{
int arr[] = {10, 5, 3, 10, 10, 4, 1, 3};
orderedGroup(arr);
}
}
Output:
10 10 10 5 3 3 4 1
Time Complexity of the above hashing based solution is Θ(n) under the assumption that
insert, search and delete operations on HashMap take O(1) time.
Below is a related problem for strings.
Group all occurrences of characters according to first appearance
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.
Improved By : Smitha Dinesh Semwal
Source
https://www.geeksforgeeks.org/group-multiple-occurrence-of-array-elements-ordered-by-first-occurrence/
899
Chapter 148
The idea is to use hashing. We generate a key for all words. The key contains all unique
character (Size of key is at most 26 for lower case alphabets). We store indexes of words
as values for a key. Once we have filled all keys and values in hash table, we can print the
result by traversing the table.
900
Chapter 148. Group words with same set of characters
C++
901
Chapter 148. Group words with same set of characters
}
}
// Driver program to test above function
int main()
{
string words[] = { "may", "student", "students", "dog",
"studentssess", "god", "cat", "act", "tab",
"bat", "flow", "wolf", "lambs", "amy", "yam",
"balms", "looped", "poodle"};
int n = sizeof(words)/sizeof(words[0]);
wordsWithSameCharSet(words, n);
return 0;
}
Java
902
Chapter 148. Group words with same set of characters
{
// Stores indexes of all words that have same
// set of unique characters.
//unordered_map <string, vector <int> > Hash;
HashMap<String, ArrayList<Integer>> Hash = new HashMap<>();
// Traverse all words
for (int i=0; i<n; i++)
{
String key = getKey(words[i]);
// if the key is already in the map
// then get its corresponding value
// and update the list and put it in the map
if(Hash.containsKey(key))
{
ArrayList<Integer> get_al = Hash.get(key);
get_al.add(i);
Hash.put(key, get_al);
}
// if key is not present in the map
// then create a new list and add
// both key and the list
else
{
ArrayList<Integer> new_al = new ArrayList<>();
new_al.add(i);
Hash.put(key, new_al);
}
}
// print all words that have the same unique character set
for (Entry<String, ArrayList<Integer>> it : Hash.entrySet())
{
ArrayList<Integer> get =it.getValue();
for (Integer v:get)
System.out.print( words[v] + ", ");
System.out.println();
}
}
// Driver program to test above function
public static void main(String args[])
{
String words[] = { "may", "student", "students", "dog",
"studentssess", "god", "cat", "act", "tab",
"bat", "flow", "wolf", "lambs", "amy", "yam",
903
Chapter 148. Group words with same set of characters
Python
904
Chapter 148. Group words with same set of characters
Output:
looped, poodle,
lambs, balms,
flow, wolf,
tab, bat,
may, amy, yam,
student, students, studentssess,
dog, god,
cat, act,
Source
https://www.geeksforgeeks.org/print-words-together-set-characters/
905
Chapter 149
1. We want to use a good hash function to ensure that the keys are well distributed. If
they are not well distributed, then we would get a lot of collision and the speed to
find an element would decline.
906
Chapter 149. Hash Table vs STL Map
2. No matter how good hash function is, we will still have collisions, so we need a method
for handling them. this often means chaining via a linked list, but it’s not the only
way.
3. We may also wish to implement methods to dynamically increase or decrease the
hash table size depending on capacity. For example, when the ratio of the number
of elements to the table size exceeds a certain threshold, we may wish to increase
the hash table size. This would mean creating a new hash table and transferring the
entries from the old table to the new table. Because this is an expensive operation,
we want to be careful to not do it too often.
STL Map
The container map is an associative container included in the standard library of C++. The
definition of this class is in the header file “map” of the namespace std.
STL Map Internal Implementation:
It’s implemented as a self-balancing red-black tree. Probably the two most common self bal-
ancing trees are red-black tree and AVL trees. To balance the tree after an insertion/update
both algorithms use the notion of rotations where the nodes of the tree are rotated to per-
form the re-balancing. While in both algorithms the insert/delete operations are O(log n),
in the case of Red-Black tree re-balancing rotation is an O(1) operation while with AVL this
is a O(log n) operation, making the RB tree more efficient in this aspect of the re-balancing
sage and one of the possible reasons that is more commonly used.
Differences between hash table and STL map
1. Null Keys : STL Map allows one null key and multiple null values whereas hash
table doesn’t allow any null key or value.
2. Thread synchronization : Map is generally preferred over hash table if thread
synchronization is not needed. Hash table is synchronized.
3. Thread safe: STL Maps are not thread safe whereas Hashmaps are thread safe and
can be shared with many threads.
4. Value Order : In STL map, values are stored in sorted order whereas in hash table
values are not stored in sorted order
5. Searching Time : You can use STL Map or binary tree for smaller data( Although
it takes O(log n) time, the number of inputs may be small enough to make this time
negligible) and for large amount of data, hash table is preferred.
Related articles
Source
https://www.geeksforgeeks.org/hash-table-vs-stl-map/
907
Chapter 150
If you want a sorted Set then it is better to add elements to HashSet and then convert it
into TreeSet rather than creating a TreeSet and adding elements to it.
908
Chapter 150. HashSet vs TreeSet in Java
HashSet example
Output:
HashSet contains:
practice
geeks
for
contribute
TreeSet example
909
Chapter 150. HashSet vs TreeSet in Java
Output:
TreeSet contains:
contribute
for
geeks
practice
Source
https://www.geeksforgeeks.org/hashset-vs-treeset-in-java/
910
Chapter 151
Hashing in Java
911
Chapter 151. Hashing in Java
912
Chapter 151. Hashing in Java
// If this is first occurrence of element
// Insert the element
if (hmap.get(arr[i]) == null) {
hmap.put(arr[i], 1);
}
// If elements already exists in hash map
// Increment the count of element by 1
else {
hmap.put(arr[i], ++c);
}
}
// Print HashMap
System.out.println(hmap);
}
// Driver method to test above method
public static void main(String[] args)
{
int arr[] = { 10, 34, 5, 10, 3, 5, 10 };
createHashMap(arr);
}
}
Output:
3. With the help of LinkedHashMap (Similar to HashMap, but keeps order of elements)
913
Chapter 151. Hashing in Java
System.out.println(lhm);
System.out.println("Getting value for key 'one': "
+ lhm.get("one"));
System.out.println("Size of the map: " + lhm.size());
System.out.println("Is map empty? " + lhm.isEmpty());
System.out.println("Contains key 'two'? "+
lhm.containsKey("two"));
System.out.println("Contains value 'practice.geeks"
+"forgeeks.org'? "+ lhm.containsValue("practice"+
".geeksforgeeks.org"));
System.out.println("delete element 'one': " +
lhm.remove("one"));
System.out.println(lhm);
}
}
Output:
914
Chapter 151. Hashing in Java
Output:
5. With the help of HashSet (Similar to HashMap, but maintains only keys, not pair)
915
Chapter 151. Hashing in Java
h.add("Australia");
h.add("South Africa");
h.add("India"); // adding duplicate elements
// Displaying the HashSet
System.out.println(h);
// Checking if India is present or not
System.out.println("\nHashSet contains India or not:"
+ h.contains("India"));
// Removing items from HashSet using remove()
h.remove("Australia");
// Printing the HashSet
System.out.println("\nList after removing Australia:" + h);
// Iterating over hash set items
System.out.println("\nIterating over list:");
Iterator<String> i = h.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
Output:
6. With the help of LinkedHashSet (Similar to LinkedHashMap, but maintains only keys,
not pair)
916
Chapter 151. Hashing in Java
Output:
Size of LinkedHashSet = 5
Original LinkedHashSet:[A, B, C, D, E]
Removing D from LinkedHashSet: true
Trying to Remove Z which is not present: false
Checking if A is present=true
Updated LinkedHashSet: [A, B, C, E]
Source
https://www.geeksforgeeks.org/hashing-in-java/
917
Chapter 152
We can think of using the following data structures to maintain information about different
phone numbers.
For arrays and linked lists, we need to search in a linear fashion, which can be costly in
practice. If we use arrays and keep the data sorted, then a phone number can be searched
in O(Logn) time using Binary Search, but insert and delete operations become costly as we
have to maintain sorted order.
With balanced binary search tree, we get moderate search, insert and delete times. All
of these operations can be guaranteed to be in O(Logn) time.
Another solution that one can think of is to use a direct access table where we make a
big array and use phone numbers as index in the array. An entry in array is NIL if phone
number is not present, else the array entry stores pointer to records corresponding to phone
number. Time complexity wise this solution is the best among all, we can do all operations
in O(1) time. For example to insert a phone number, we create a record with details of
given phone number, use phone number as index and store the pointer to the created record
in table.
918
Chapter 152. Hashing | Set 1 (Introduction)
This solution has many practical limitations. First problem with this solution is extra space
required is huge. For example if phone number is n digits, we need O(m * 10n ) space for
table where m is size of a pointer to record. Another problem is an integer in a programming
language may not store n digits.
Due to above limitations Direct Access Table cannot always be used. Hashing is the
solution that can be used in almost all such situations and performs extremely well compared
to above data structures like Array, Linked List, Balanced BST in practice. With hashing
we get O(1) search time on average (under reasonable assumptions) and O(n) in worst case.
Hashing is an improvement over Direct Access Table. The idea is to use hash function that
converts a given phone number or any other key to a smaller number and uses the small
number as index in a table called hash table.
Hash Function: A function that converts a given big phone number to a small practical
integer value. The mapped integer value is used as an index in hash table. In simple terms,
a hash function maps a big number or string to a small integer that can be used as index
in hash table.
A good hash function should have following properties
1) Efficiently computable.
2) Should uniformly distribute the keys (Each table position equally likely for each key)
For example for phone numbers a bad hash function is to take first three digits. A better
function is consider last three digits. Please note that this may not be the best hash function.
There may be better ways.
Hash Table: An array that stores pointers to records corresponding to a given phone
number. An entry in hash table is NIL if no existing phone number has hash function value
equal to the index for the entry.
Collision Handling: Since a hash function gets us a small number for a big key, there is
possibility that two keys result in same value. The situation where a newly inserted key
maps to an already occupied slot in hash table is called collision and must be handled using
some collision handling technique. Following are the ways to handle collisions:
• Chaining:The idea is to make each cell of hash table point to a linked list of records
that have same hash function value. Chaining is simple, but requires additional mem-
ory outside the table.
• Open Addressing: In open addressing, all elements are stored in the hash table itself.
Each table entry contains either a record or NIL. When searching for an element, we
one by one examine table slots until the desired element is found or it is clear that the
element is not in the table.
Next Posts:
Separate Chaining for Collision Handling
Open Addressing for Collision Handling
References:
MIT Video Lecture
919
Chapter 152. Hashing | Set 1 (Introduction)
Source
https://www.geeksforgeeks.org/hashing-set-1-introduction/
920
Chapter 153
921
Chapter 153. Hashing | Set 2 (Separate Chaining)
922
Chapter 153. Hashing | Set 2 (Separate Chaining)
Next Post:
Open Addressing for Collision Handling
References:
http://courses.csail.mit.edu/6.006/fall09/lecture_notes/lecture05.pdf
Source
https://www.geeksforgeeks.org/hashing-set-2-separate-chaining/
923
Chapter 154
924
Chapter 154. Hashing | Set 3 (Open Addressing)
Let us consider a simple hash function as “key mod 7” and sequence of keys as 50, 700, 76,
85, 92, 73, 101.
Clustering: The main problem with linear probing is clustering, many consecutive elements
form groups and it starts taking time to find a free slot or to search an element.
b) Quadratic Probing We look for i2 ‘th slot in i’th iteration.
c)Double Hashing We use another hash function hash2(x) and look for i*hash2(x) slot in
i’th rotation.
925
Chapter 154. Hashing | Set 3 (Open Addressing)
926
Chapter 154. Hashing | Set 3 (Open Addressing)
References:
http://courses.csail.mit.edu/6.006/fall11/lectures/lecture10.pdf
https://www.cse.cuhk.edu.hk/irwin.king/_media/teaching/csc2100b/tu6.pdf
Improved By : PulkitGoel2
Source
https://www.geeksforgeeks.org/hashing-set-3-open-addressing/
927
Chapter 155
1->2->3->4
If we are at 3 and there is a need to remove it, then 2 need to be linked with 4
and as from 3, 2 can’t be accessed as it is singly linked list. So, the list has to
be traversed again i.e O(n), but if we have doubly linked list i.e.
1234
928
Chapter 155. Hashtables Chaining with Doubly Linked Lists
929
Chapter 155. Hashtables Chaining with Doubly Linked Lists
930
Chapter 155. Hashtables Chaining with Doubly Linked Lists
top[hash_val] = entry->prev;
top[hash_val]->next = NULL;
delete entry;
entry = top[hash_val];
}
}
entry = entry->next;
}
cout << "Element was successfully removed at the key "
<< key << endl;
}
// inserting method
void add(int key, int value)
{
// Applying hashFunc to find
// index for given key
int hash_val = HashFunc(key);
hash_node* entry = hashtable[hash_val];
// if key has no value stored
if (entry == NULL) {
// creating new node
entry = new hash_node;
entry->val = value;
entry->key = key;
entry->next = NULL;
entry->prev = NULL;
hashtable[hash_val] = entry;
top[hash_val] = entry;
}
// if some values are present
else {
// traversing till the end of
// the list
while (entry != NULL)
entry = entry->next;
// creating the new node
entry = new hash_node;
entry->val = value;
entry->key = key;
entry->next = NULL;
entry->prev = top[hash_val];
top[hash_val]->next = entry;
top[hash_val] = entry;
}
931
Chapter 155. Hashtables Chaining with Doubly Linked Lists
cout << "Value " << value << " was successfully"
" added at key " << key << endl;
}
};
// Driver Code
int main()
{
HashMap hash;
hash.add(4, 5);
hash.find(4);
hash.remove(4);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/hashtables-chaining-with-doubly-linked-lists/
932
Chapter 156
We strongly recommend to minimize your browser and try this yourself first.
There are plenty of methods to solve this problem, it’s a good test to check how many
solutions you can guess.
Method 1 (Simple)
Iterate through every element of first set and search it in other set, if any element is found,
return false. If no element is found, return tree. Time complexity of this method is O(mn).
Following is implementation of above idea.
C++
933
Chapter 156. How to check if two given sets are disjoint?
#include<iostream>
using namespace std;
// Returns true if set1[] and set2[] are disjoint, else false
bool areDisjoint(int set1[], int set2[], int m, int n)
{
// Take every element of set1[] and search it in set2
for (int i=0; i<m; i++)
for (int j=0; j<n; j++)
if (set1[i] == set2[j])
return false;
// If no element of set1 is present in set2
return true;
}
// Driver program to test above function
int main()
{
int set1[] = {12, 34, 11, 9, 3};
int set2[] = {7, 2, 1, 5};
int m = sizeof(set1)/sizeof(set1[0]);
int n = sizeof(set2)/sizeof(set2[0]);
areDisjoint(set1, set2, m, n)? cout << "Yes" : cout << " No";
return 0;
}
Java
934
Chapter 156. How to check if two given sets are disjoint?
return true;
}
// Driver program to test above function
public static void main(String[] args)
{
disjoint1 dis = new disjoint1();
int set1[] = { 12, 34, 11, 9, 3 };
int set2[] = { 7, 2, 1, 5 };
boolean result = dis.aredisjoint(set1, set2);
if (result)
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Rishabh Mahrsee
Python
Output :
935
Chapter 156. How to check if two given sets are disjoint?
Yes
C++
936
Chapter 156. How to check if two given sets are disjoint?
Java
937
Chapter 156. How to check if two given sets are disjoint?
Python
Output :
Yes
938
Chapter 156. How to check if two given sets are disjoint?
#include<bits/stdc++.h>
using namespace std;
/* C++ program to check if two sets are distinct or not */
// This function prints all distinct elements
bool areDisjoint(int set1[], int set2[], int n1, int n2)
{
// Creates an empty hashset
set<int> myset;
// Traverse the first set and store its elements in hash
for (int i = 0; i < n1; i++)
myset.insert(set1[i]);
// Traverse the second set and check if any element of it
// is already in hash or not.
for (int i = 0; i < n2; i++)
if (myset.find(set2[i]) != myset.end())
return false;
return true;
}
// Driver method to test above method
int main()
939
Chapter 156. How to check if two given sets are disjoint?
{
int set1[] = {10, 5, 3, 4, 6};
int set2[] = {8, 7, 9, 3};
int n1 = sizeof(set1) / sizeof(set1[0]);
int n2 = sizeof(set2) / sizeof(set2[0]);
if (areDisjoint(set1, set2, n1, n2))
cout << "Yes";
else
cout << "No";
}
//This article is contributed by Chhavi
JAVA
940
Chapter 156. How to check if two given sets are disjoint?
}
}
Output:
No
Time complexity of the above implementation is O(m+n) under the assumption that hash
set operations like add() and contains() work in O(1) time.
This article is contributed by Rajeev. 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/check-two-given-sets-disjoint/
941
Chapter 157
Well, many must be wondering that if the database is exposed to the hacker then
what can be done? The hacker has access to all the information. WRONG!! There are
many ways through which the process of retrieving password from the database can be
made cumbersome for the hacker. Even then the developers tend to ignore the basic
guidelines and store the passwords in plain text.There are over 30% websites which store
your passwords in plain text (including some reputed sites also). If the website is storing
your password in plain text then no matter how strong password you choose, you are not
safe!
One might also think that if not plain text then we must encrypt the password and
then store. It is also a terrible idea. Encryption functions provide one-one mapping
between input and output and they are always reversible. If the hacker gets the key, he will
942
Chapter 157. How to store a password in database?
be able to decrypt the passwords. The better way would be to use a one way cryptographic
hash function. Hash function provides a many-one mapping between input and output and
it is practically impossible to reverse a output. A good cryptographic hash function has
lesser number of Collisions (i.e for different input values to the function it is difficult to get
the same output). Collisions cannot be completely avoided because of pigeonhole principle.
For hashing passwords we can assume that the hash function will generate unique output
i.e for no two different passwords we will get a same hash value.
Some of the popular cryptographic hash functions are MD5 and SHA1. Instead of
storing plain text password in the database one way is to store the hash of the password.
You might be thinking that if we cannot get the actual password back from the hash
then how are we going to verify the credentials that the user entered? It’s simple,
apply the same hash function on the password which user entered and then compare it
with the hash stored in the database. If both hashes match then the user is authenti-
cated (since hash of same input will give same output). Now if the attacker is able to get
database access, he will be only able to view the hashed output and not the actual password.
Using cryptographic hash function is better than storing plain text pass-
word.
Hackers are smart guys and once they came to know that developers are storing
hashed passwords, they pre-computed hash of large number of words (from a popular word
list or dictionary words). They created a table of words and their corresponding hashes.
This table is known as Rainbow Table and it is readily available online. They can use this
table to reverse lookup the actual password by comparing the hashes obtained from the
database. Hence it is very important to have a strong password since the possibility of
your password appearing in the word list becomes less.
Simply storing the hash of a password is not going to help anymore. Processing power has
increased drastically with the introduction of GPUs and CUDA, OpenCL libraries. A fast
GPU can generate millions of MD5/SHA1 hashes in one second. Hence a hacker can easily
generate large number of hashes by brute-forcing various possible combinations and can
compare it with the hashes stored in the database to extract the actual password.
Don’t loose hope! There is still something that developers can do to keep your pass-
943
Chapter 157. How to store a password in database?
words away from prying eyes of the hackers. Make the passwords delicious by adding some
salt to them! Yeah, right..! Add a salt. A salt is random data that is concatenated with
your password before sending it as the input of the hashing function.
For example :
If your password is abc and the salt is !ZaP0#8, the result of hashFunction(‘abc!ZaP0#8’)
will be stored in the database instead of hashFunction(‘abc’).
Hence the rainbow table attacks won’t be effective now as the probability that rain-
bow table contains hash of ‘abc!ZaP0#8’ is meager (because generally rainbow tables
are constructed from common words, dictionary words etc). Salt is not stored in the
database and only present in the application configuration file which is not accessible to
outer world. Gaining access to the source files is difficult than gaining access to the database.
The above salting method is static. We have one fixed salt for all the passwords.
To authenticate the user, first concatenate the fixed salt to the user supplied input
(password) and then pass the value to the hashing function and compare it with the
value stored in the database. However this approach is still vulnerable to brute-force and
if the attacker is able to get the static salt he can use the old attack methodology by
concatenating the salt in every word.
A better approach would be to use a dynamic salt. For each user a new salt is gen-
erated by cryptographically strong random string generator. The password entered by user
is concatenated with a random generated salt as well as a static salt. The concatenated
string is passed as the input of hashing function. The result obtained is stored in database.
Dynamic salt is required to be stored in the database since it is different for different users.
When the user is to be authenticated, first the value of dynamic salt for that user is fetched
from the database, it is concatenated with user supplied input and the static salt. The
result is compared with the hash stored in the database.
If the database is compromised the hacker will not only get your password hashes
but also the dynamic salt used. You might be wondering then what is the advantage of
dynamic salt over static salt if attacker has dynamic salt? Even if the attacker has dynamic
salt he needs to create a new hash-table (or rainbow table) for each and every user present
in the database (as per dynamic salt). This is a lot more expensive operation than creating
just one table for all the users.
The above approach is quite good to slow down a hacker. However it is recommended to
use algorithms like bcrypt and scrypt instead of MD5/SHA1. Bcrypt is a hashing algorithm
based on Blowfish. It requires you to specify a cost/work factor. The work factor makes the
overall process slower and hence time taken to generate hash-table would increase multiple
times.
References :
https://nakedsecurity.sophos.com/2013/11/20/serious-security-how-to-store-your-users-passwords-safely/
944
Chapter 157. How to store a password in database?
Source
https://www.geeksforgeeks.org/store-password-database/
945
Chapter 158
Implementing our Own Hash Table with Separate Chaining in Java - GeeksforGeeks
Every data structure has its own special characteristics for example a BST is used when
quick searching of an element (in log(n)) is required. A heap or a priority queue is used
when the minimum or maximum element needs to be fetched in constant time. Similarly a
hash table is used to fetch, add and remove an element in constant time. It is necessary for
anyone to be clear with the working of a hash table before moving on to the implementation
aspect. So here is a brief background on the working of hash table and also it should be
noted that we will be using Hash Map and Hash Table terminology interchangeably though
in Java HashTables are thread safe while HashMaps are not.
The code we are going to implement is available at Link 1 and Link2
But it is strongly recommended that one must read this blog completely and try and decipher
the nitty gritty of what goes into implementing a hash map and then try to write the code
yourself.
Background
Every hash-table stores data in the form of (key, value) combination. Interestingly every
key is unique in a Hash Table but values can repeat which means values can be same for
different keys present in it. Now as we observe in an array to fetch a value we provide the
position/index corresponding to the value in that array. In a Hash Table, instead of an
index we use a key to fetch the value corresponding to that key. Now the entire process is
described below
Every time a key is generated. The key is passed to a hash function. Every hash function
has two parts a Hash code and a Compressor.
Hash code is an Integer number (random or nonrandom). In Java every Object has its
own hash code. We will use the hash code generated by JVM in our hash function and to
946
Chapter 158. Implementing our Own Hash Table with Separate Chaining in Java
compress the hash code we modulo(%) the hash code by size of the hash table. So modulo
operator is compressor in our implementation.
The entire process ensures that for any key, we get an integer position within the size of the
Hash Table to insert the corresponding value.
So the process is simple, user gives a (key, value) pair set as input and based on the value
generated by hash function an index is generated to where the value corresponding to the
particular key is stored. So whenever we need to fetch a value corresponding to a key that
is just O(1).
This picture stops being so rosy and perfect when the concept of hash collision is introduced.
Imagine for different key values same block of hash table is allocated now where do the
previously stored values corresponding to some other previous key go. We certainly can’t
replace it .That will be disastrous! To resolve this issue we will use Separate Chaining
Technique, Please note there are other open addressing techniques like double hashing and
linear probing whose efficiency is almost same as to that of separate chaining and you can
read more about them at Link 1 Link 2 Link3
Now what we do is make a linked list corresponding to the particular bucket of the Hash
Table, to accommodate all the values corresponding to different keys who map to the same
bucket.
Now there may be a scenario that all the keys get mapped to the same bucket and we have
a linked list of n(size of hash table) size from one single bucket, with all the other buckets
empty and this is the worst case where a hash table acts a linked list and searching is
O(n).So what do we do ?
Load Factor
If n be the total number of buckets we decided to fill initially say 10 and let’s say 7 of them
got filled now, so the load factor is 7/10=0.7.
947
Chapter 158. Implementing our Own Hash Table with Separate Chaining in Java
In our implementation whenever we add a key value pair to the Hash Table we check
the load factor if it is greater than 0.7 we double the size of our hash table.
Implementation
Hash Node Data Type
We will try to make a generic map without putting any restrictions on the data type of the
key and the value . Also every hash node needs to know the next node it is pointing to in
the linked list so a next pointer is also required.
The functions we plan to keep in our hash map are
• get(K key) : returns the value corresponding to the key if the key is present in HT
(Hast Table)
• getSize() : return the size of the HT
• add() : adds new valid key, value pair to the HT, if already present updates the value
• remove() : removes the key, value pair
• isEmpty() : returns true if size is zero
Every Hash Map must have an array list/linked list with an initial size and a bucket size
which gets increased by unity every time a key, value pair is added and decreased by unity
every time a node is deleted
A Helper Function is implemented to get the index of the key, to avoid redundancy in
other functions like get, add and remove. This function uses the in built java function to
generate a hash code and we compress the hash code by the size of the HT so that the index
is within the range of the size of the HT
get()
The get function just takes a key as an input and returns the corresponding value if the key
is present in the table otherwise returns null. Steps are:
remove()
• Fetch the index corresponding to the input key using the helper function
• The traversal of linked list similar like in get() but what is special here is that one
needs to remove the key along with finding it and two cases arise
• If the key to be removed is present at the head of the linked list
• If the key to be removed is not present at head but somewhere else
948
Chapter 158. Implementing our Own Hash Table with Separate Chaining in Java
add()
Now to the most interesting and challenging function of this entire implementation.It is
interesting because we need to dynamically increase the size of our list when load factor is
above the value we specified.
• Just like remove steps till traversal and adding and two cases (addition at head spot
or non-head spot) remain the same.
• Towards the end if load factor is greater than 0.7
• We double the size of the array list and then recursively call add function on existing
keys because in our case hash value generated uses the size of the array to compress
the inbuilt JVM hash code we use ,so we need to fetch new indices for the existing
keys. This is very important to understand please re read this paragraph till you get
a hang of what is happening in the add function.
Java does in its own implementation of Hash Table uses Binary Search Tree if linked list
corresponding to a particular bucket tend to get too long.
949
Chapter 158. Implementing our Own Hash Table with Separate Chaining in Java
950
Chapter 158. Implementing our Own Hash Table with Separate Chaining in Java
}
// If key was not there
if (head == null)
return null;
// Reduce size
size--;
// Remove key
if (prev != null)
prev.next = head.next;
else
bucketArray.set(bucketIndex, head.next);
return head.value;
}
// Returns value for a key
public V get(K key)
{
// Find head of chain for given key
int bucketIndex = getBucketIndex(key);
HashNode<K, V> head = bucketArray.get(bucketIndex);
// Search key in chain
while (head != null)
{
if (head.key.equals(key))
return head.value;
head = head.next;
}
// If key not found
return null;
}
// Adds a key value pair to hash
public void add(K key, V value)
{
// Find head of chain for given key
int bucketIndex = getBucketIndex(key);
HashNode<K, V> head = bucketArray.get(bucketIndex);
// Check if key is already present
while (head != null)
{
if (head.key.equals(key))
951
Chapter 158. Implementing our Own Hash Table with Separate Chaining in Java
{
head.value = value;
return;
}
head = head.next;
}
// Insert key in chain
size++;
head = bucketArray.get(bucketIndex);
HashNode<K, V> newNode = new HashNode<K, V>(key, value);
newNode.next = head;
bucketArray.set(bucketIndex, newNode);
// If load factor goes beyond threshold, then
// double hash table size
if ((1.0*size)/numBuckets >= 0.7)
{
ArrayList<HashNode<K, V>> temp = bucketArray;
bucketArray = new ArrayList<>();
numBuckets = 2 * numBuckets;
size = 0;
for (int i = 0; i < numBuckets; i++)
bucketArray.add(null);
for (HashNode<K, V> headNode : temp)
{
while (headNode != null)
{
add(headNode.key, headNode.value);
headNode = headNode.next;
}
}
}
}
// Driver method to test Map class
public static void main(String[] args)
{
Map<String, Integer>map = new Map<>();
map.add("this",1 );
map.add("coder",2 );
map.add("this",4 );
map.add("hi",5 );
System.out.println(map.size());
System.out.println(map.remove("this"));
System.out.println(map.remove("this"));
System.out.println(map.size());
952
Chapter 158. Implementing our Own Hash Table with Separate Chaining in Java
System.out.println(map.isEmpty());
}
}
Output :
3
4
null
2
false
Source
https://www.geeksforgeeks.org/implementing-our-own-hash-table-with-separate-chaining-in-java/
953
Chapter 159
Implementing own Hash Table with Open Addressing Linear Probing in C++ - Geeks-
forGeeks
Prerequisite – Hashing Introduction, Implementing our Own Hash Table with Separate
Chaining in Java
In Open Addressing, all elements are stored in the hash table itself. So at any point, size
of table must be greater than or equal to total number of keys (Note that we can increase
table size by copying old data if needed).
• Insert(k) – Keep probing until an empty slot is found. Once an empty slot is found,
insert k.
• Search(k) – Keep probing until slot’s key doesn’t become equal to k or an empty
slot is reached.
• Delete(k) – Delete operation is interesting. If we simply delete a key, then search
may fail. So slots of deleted keys are marked specially as “deleted”.
Here, to mark a node deleted we have used dummy node with key and value -1.
Insert can insert an item in a deleted slot, but search doesn’t stop at a deleted slot.
The entire process ensures that for any key, we get an integer position within the size of the
Hash Table to insert the corresponding value.
So the process is simple, user gives a (key, value) pair set as input and based on the value
generated by hash function an index is generated to where the value corresponding to the
particular key is stored. So whenever we need to fetch a value corresponding to a key that
is just O(1).
954
Chapter 159. Implementing own Hash Table with Open Addressing Linear Probing in C++
Code –
#include<bits/stdc++.h>
using namespace std;
//template for generic type
template<typename K, typename V>
//Hashnode class
class HashNode
{
public:
V value;
K key;
//Constructor of hashnode
HashNode(K key, V value)
{
this->value = value;
this->key = key;
}
};
//template for generic type
template<typename K, typename V>
955
Chapter 159. Implementing own Hash Table with Open Addressing Linear Probing in C++
956
Chapter 159. Implementing own Hash Table with Open Addressing Linear Probing in C++
//if new node to be inserted increase the current size
if(arr[hashIndex] == NULL || arr[hashIndex]->key == -1)
size++;
arr[hashIndex] = temp;
}
//Function to delete a key value pair
V deleteNode(int key)
{
// Apply hash function to find index for given key
int hashIndex = hashCode(key);
//finding the node with given key
while(arr[hashIndex] != NULL)
{
//if node found
if(arr[hashIndex]->key == key)
{
HashNode<K,V> *temp = arr[hashIndex];
//Insert dummy node here for further use
arr[hashIndex] = dummy;
// Reduce size
size--;
return temp->value;
}
hashIndex++;
hashIndex %= capacity;
}
//If not found return null
return NULL;
}
//Function to search the value for a given key
V get(int key)
{
// Apply hash function to find index for given key
int hashIndex = hashCode(key);
//finding the node with given key
while(arr[hashIndex] != NULL)
{
//if node found return its value
if(arr[hashIndex]->key == key)
957
Chapter 159. Implementing own Hash Table with Open Addressing Linear Probing in C++
return arr[hashIndex]->value;
hashIndex++;
hashIndex %= capacity;
}
//If not found return null
return NULL;
}
//Return current size
int sizeofMap()
{
return size;
}
//Return true if size is 0
bool isEmpty()
{
return size == 0;
}
//Function to display the stored key value pairs
void display()
{
for(int i=0 ; i<capacity ; i++)
{
if(arr[i] != NULL && arr[i]->key != -1)
cout << "key = " << arr[i]->key
<<" value = "<< arr[i]->value << endl;
}
}
};
//Driver method to test map class
int main()
{
HashMap<int, int> *h = new HashMap<int, int>;
h->insertNode(1,1);
h->insertNode(2,2);
h->insertNode(2,3);
h->display();
cout << h->sizeofMap() <<endl;
cout << h->deleteNode(2) << endl;
cout << h->sizeofMap() <<endl;
cout << h->isEmpty() << endl;
cout << h->get(2);
return 0;
958
Chapter 159. Implementing own Hash Table with Open Addressing Linear Probing in C++
Output –
key = 1 value = 1
key = 2 value = 3
2
3
1
0
0
Source
https://www.geeksforgeeks.org/implementing-hash-table-open-addressing-linear-probing-cpp/
959
Chapter 160
960
Chapter 160. Index Mapping (or Trivial Hashing) with negatives allowed
961
Chapter 160. Index Mapping (or Trivial Hashing) with negatives allowed
{
for (int i = 0; i < n; i++) {
if (a[i] >= 0)
has[a[i]][0] = 1;
else
has[abs(a[i])][1] = 1;
}
}
// Driver code
int main()
{
int a[] = { -1, 9, -5, -8, -5, -2 };
int n = sizeof(a)/sizeof(a[0]);
insert(a, n);
int X = -5;
if (search(X) == true)
cout << "Present";
else
cout << "Not Present";
return 0;
}
Output:
Present
Improved By : fsociety_|_
Source
https://www.geeksforgeeks.org/index-mapping-or-trivial-hashing-with-negatives-allowed/
962
Chapter 161
1. int hash
2. K key
3. V value
4. Node next
Now we will see how this works. First we will see the hashing process.
Hashing
Hashing is a process of converting an object into integer form by using the method hash-
Code(). Its necessary to write hashCode() method properly for better performance of
HashMap. Here I am taking key of my own class so that I can override hashCode() method
to show different scenarios. My Key class is
963
Chapter 161. Internal Working of HashMap in Java
this.key = key;
}
@Override
public int hashCode()
{
return (int)key.charAt(0);
}
@Override
public boolean equals(Object obj)
{
return key.equals((String)obj);
}
}
Here overrided hashCode() method returns the first character’s ASCII value as hash code.
So whenever the first character of key is same, the hash code will be same. You should not
approach this criteria in your program. It is just for demo purpose. As HashMap also allows
null key, so hash code of null will always be 0.
hashCode() method
hashCode() method is used to get the hash Code of an object. hashCode() method of object
class returns the memory reference of object in integer form. Definition of hashCode()
method is public native hashCode(). It indicates the implementation of hashCode() is
native because there is not any direct method in java to fetch the reference of object. It is
possible to provide your own implementation of hashCode().
In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index.
equals() method
equals method is used to check that 2 objects are equal or not. This method is provided by
Object class. You can override this in your class to provide your own implementation.
HashMap uses equals() to compare the key whether the are equal or not. If equals() method
return true, they are equal otherwise not equal.
Buckets
A bucket is one element of HashMap array. It is used to store nodes. Two or more nodes can
have the same bucket. In that case link list structure is used to connect the nodes. Buckets
are different in capacity. A relation between bucket and capacity is as follows:
A single bucket can have more than one nodes, it depends on hashCode() method. The
better your hashCode() method is, the better your buckets will be utilized.
Index Calculation in Hashmap
Hash code of key may be large enough to create an array. hash code generated may be
in the range of integer and if we create arrays for such a range, then it will easily cause
964
Chapter 161. Internal Working of HashMap in Java
where n is number of buckets or the size of array. In our example, I will consider n as default
size that is 16.
HashMap :
Steps:
Integer value = 20
Node next = null
}
4. Place this object at index 6, if no other object is presented there.
• Inserting another Key-Value Pair: Now, putting other pair that is,
965
Chapter 161. Internal Working of HashMap in Java
Steps:
Steps:
966
Chapter 161. Internal Working of HashMap in Java
map.get(new Key("sachin"));
Steps:
map.get(new Key("vaibhav"));
Steps:
967
Chapter 161. Internal Working of HashMap in Java
1. Time complexity is almost constant for put and get method until rehashing is not
done.
2. In case of collision, i.e. index of two or more nodes are same, nodes are joined by link
list i.e. second node is referenced by first node and third by second and so on.
3. If key given already exist in HashMap, the value is replaced with new value.
4. hash code of null key is 0.
5. When getting an object with its key, the linked list is traversed until the key matches
or null is found on next field.
Improved By : ShubhamDeshmukh
Source
https://www.geeksforgeeks.org/internal-working-of-hashmap-java/
968
Chapter 162
Inverted Index
hello (1, 1)
everyone (1, 2)
this (2, 1)
article (2, 2)
is (2, 3); (3, 2)
based (2, 4)
on (2, 5)
inverted (2, 6)
index (2, 7)
which (3, 1)
hashmap (3, 3)
like (3, 4)
data (3, 5)
structure (3, 6)
The word “hello” is in document 1 (“hello everyone”) starting at word 1, so has an entry
(1, 1) and word “is” is in document 2 and 3 at ‘3rd’ and ‘2nd’ positions respectively (here
969
Chapter 162. Inverted Index
Example:
Words Document
ant doc1
demo doc2
world doc1, doc2
• Inverted index is to allow fast full text searches, at a cost of increased processing when
a document is added to the database.
• It is easy to develop.
• It is the most popular data structure used in document retrieval systems, used on a
large scale for example in search engines.
• Large storage overhead and high maintaenance costs on update, delete and insert.
Source
https://www.geeksforgeeks.org/inverted-index/
970
Chapter 163
• A vector of integer pairs has been used to represent the cache, where each pair consists
of the block number and the number of times it has been used. The vector is ordered
in the form of a min-heap, which allows us to access the least frequently used block in
constant time.
• A hashmap has been used to store the indices of the cache blocks which allows searching
in constant time.
971
Chapter 163. LFU (Least Frequently Used) Cache Implementation
972
Chapter 163. LFU (Least Frequently Used) Cache Implementation
++v[i].second;
heapify(v, m, i, n);
}
// Function to Insert a new node in the heap
void insert(vector<pair<int, int> >& v,
unordered_map<int, int>& m, int value, int& n)
{
if (n == v.size()) {
m.erase(v[0].first);
cout << "Cache block " << v[0].first
<< " removed.\n";
v[0] = v[--n];
heapify(v, m, 0, n);
}
v[n++] = make_pair(value, 1);
m.insert(make_pair(value, n - 1));
int i = n - 1;
// Insert a node in the heap by swapping elements
while (i && v[parent(i)].second > v[i].second) {
m[v[i].first] = parent(i);
m[v[parent(i)].first] = i;
swap(v[i], v[parent(i)]);
i = parent(i);
}
cout << "Cache block " << value << " inserted.\n";
}
// Function to refer to the block value in the cache
void refer(vector<pair<int, int> >& cache, unordered_map<int,
int>& indices, int value, int& cache_size)
{
if (indices.find(value) == indices.end())
insert(cache, indices, value, cache_size);
else
increment(cache, indices, indices[value], cache_size);
}
// Driver Code
int main()
{
int cache_max_size = 4, cache_size = 0;
vector<pair<int, int> > cache(cache_max_size);
unordered_map<int, int> indices;
refer(cache, indices, 1, cache_size);
refer(cache, indices, 2, cache_size);
973
Chapter 163. LFU (Least Frequently Used) Cache Implementation
Output:
Source
https://www.geeksforgeeks.org/lfu-least-frequently-used-cache-implementation/
974
Chapter 164
This problem can be solved easily by the concept ofLIS where each next greater element
differ from earlier one by 1. But this will take O(n^2) time complexity.
With the use of hashing we can finding the size of longest increasing sequence with consec-
utive integers in time complexity of O(n).
We create a hash table.. Now for each element arr[i], we perform hash[arr[i]] = hash[arr[i]
– 1] + 1. So, for every element we know longest consecutive increasing subsequence ending
with it. Finally we return maximum value from hash table.
975
Chapter 164. Largest increasing subsequence of consecutive integers
Output:
LIS_size = 5
LIS : 2 3 4 5 6
976
Chapter 164. Largest increasing subsequence of consecutive integers
Source
https://www.geeksforgeeks.org/largest-increasing-subsequence-of-consecutive-integers/
977
Chapter 165
Input : 313551
Output : 531135
Explanations : 531135 is the largest number
which is a palindrome, 135531, 315513 and other
numbers can also be formed but we need the highest
of all of the palindromes.
Input : 331
Output : 313
Input : 3444
Output : Pallindrome cannot be formed
Naive Approach : The naive approach will be to try all the permutations possible, and
print the largest of such combinations which is a palindrome.
Efficient Approach : An efficient approach will be to use Greedy algorithm. Since the
number is large, store the number in a string. Store the count of occurrences of every digit
in the given number in a map. Check if it is possible to form a palindrome or not. If the
digits of the given number can be rearranged to form a palindrome, then apply the greedy
approach to obtain the number. Check for the occurrence of every digit (9 to 0), and place
978
Chapter 165. Largest palindromic number by permuting digits
every available digit at front and back. Initially, the front pointer will be at index 0,
as the largest digit will be placed at first to make the number a large one. With
every step, move the front pointer 1 position ahead. If the digit occurs an odd number of
times, then place one digit in the middle and rest of the even number of digits at
front and back. Keep repeating the process (map[digit]/2) number of times for a single
digit. After placing a particular digit which occurs an even number of times at the front
and back, move the front pointer one step ahead. The placing is done till map[digit] is 0.
The char array will have the largest palindromic number possible after completion of the
placing of digits greedily.
In the worst case, the time complexity will be O(10 * (length of string/2)), in case the
number consists of a same digit at every position.
Below is the implementation of the above idea :
979
Chapter 165. Largest palindromic number by permuting digits
980
Chapter 165. Largest palindromic number by permuting digits
Output:
531135
Source
https://www.geeksforgeeks.org/largest-palindromic-number-permuting-digits/
981
Chapter 166
Method 1 (Simple)
A simple method is to use two nested loops. The outer loop picks a starting point i. The
inner loop considers all subarrays starting from i. If size of a subarray is greater than
maximum size so far, then update the maximum size.
In the below code, 0s are considered as -1 and sum of all values from i to j is calculated. If
sum becomes 0, then size of this subarray is compared with largest size so far.
982
Chapter 166. Largest subarray with equal number of 0s and 1s
#include <stdio.h>
// This function Prints the starting and ending
// indexes of the largest subarray with equal
// number of 0s and 1s. Also returns the size
// of such subarray.
int findSubArray(int arr[], int n)
{
int sum = 0;
int maxsize = -1, startindex;
// Pick a starting point as i
for (int i = 0; i < n-1; i++)
{
sum = (arr[i] == 0)? -1 : 1;
// Consider all subarrays starting from i
for (int j = i+1; j < n; j++)
{
(arr[j] == 0)? (sum += -1): (sum += 1);
// If this is a 0 sum subarray, then
// compare it with maximum size subarray
// calculated so far
if (sum == 0 && maxsize < j-i+1)
{
maxsize = j - i + 1;
startindex = i;
}
}
}
if (maxsize == -1)
printf("No such subarray");
else
printf("%d to %d", startindex, startindex+maxsize-1);
return maxsize;
}
/* Driver program to test above functions*/
int main()
{
int arr[] = {1, 0, 0, 1, 0, 1, 1};
983
Chapter 166. Largest subarray with equal number of 0s and 1s
Java
class LargestSubArray
{
// This function Prints the starting and ending
// indexes of the largest subarray with equal
// number of 0s and 1s. Also returns the size
// of such subarray.
int findSubArray(int arr[], int n)
{
int sum = 0;
int maxsize = -1, startindex = 0;
int endindex = 0;
// Pick a starting point as i
for (int i = 0; i < n - 1; i++)
{
sum = (arr[i] == 0) ? -1 : 1;
// Consider all subarrays starting from i
for (int j = i + 1; j < n; j++)
{
if(arr[j] == 0)
sum += -1;
else
sum += 1;
// If this is a 0 sum subarray, then
// compare it with maximum size subarray
// calculated so far
if (sum == 0 && maxsize < j - i + 1)
{
maxsize = j - i + 1;
startindex = i;
}
}
}
984
Chapter 166. Largest subarray with equal number of 0s and 1s
endindex = startindex+maxsize-1;
if (maxsize == -1)
System.out.println("No such subarray");
else
System.out.println(startindex+" to "+endindex);
return maxsize;
}
/* Driver program to test the above functions */
public static void main(String[] args)
{
LargestSubArray sub;
sub = new LargestSubArray();
int arr[] = {1, 0, 0, 1, 0, 1, 1};
int size = arr.length;
sub.findSubArray(arr, size);
}
}
Python3
985
Chapter 166. Largest subarray with equal number of 0s and 1s
C#
986
Chapter 166. Largest subarray with equal number of 0s and 1s
sum = (arr[i] == 0) ? -1 : 1;
// Consider all subarrays starting from i
for (int j = i + 1; j < n; j++)
{
if(arr[j] == 0)
sum += -1;
else
sum += 1;
// If this is a 0 sum subarray, then
// compare it with maximum size subarray
// calculated so far
if (sum == 0 && maxsize < j - i + 1)
{
maxsize = j - i + 1;
startindex = i;
}
}
}
endindex = startindex+maxsize-1;
if (maxsize == -1)
Console.WriteLine("No such subarray");
else
Console.WriteLine(startindex+" to "+endindex);
return maxsize;
}
// Driver program
public static void Main()
{
int []arr = {1, 0, 0, 1, 0, 1, 1};
int size = arr.Length;
findSubArray(arr, size);
}
}
// This code is contributed by Sam007
Output:
0 to 5
987
Chapter 166. Largest subarray with equal number of 0s and 1s
988
Chapter 166. Largest subarray with equal number of 0s and 1s
int maxsize = -1, startindex;
// Create an auxiliary array sunmleft[].
// sumleft[i] will be sum of array
// elements from arr[0] to arr[i]
int sumleft[n];
// For min and max values in sumleft[]
int min, max;
int i;
// Fill sumleft array and get min and max
// values in it. Consider 0 values in arr[]
// as -1
sumleft[0] = ((arr[0] == 0)? -1: 1);
min = arr[0]; max = arr[0];
for (i=1; i<n; i++)
{
sumleft[i] = sumleft[i-1] + ((arr[i] == 0)?
-1: 1);
if (sumleft[i] < min)
min = sumleft[i];
if (sumleft[i] > max)
max = sumleft[i];
}
// Now calculate the max value of j - i such
// that sumleft[i] = sumleft[j]. The idea is
// to create a hash table to store indexes of all
// visited values.
// If you see a value again, that it is a case of
// sumleft[i] = sumleft[j]. Check if this j-i is
// more than maxsize.
// The optimum size of hash will be max-min+1 as
// these many different values of sumleft[i] are
// possible. Since we use optimum size, we need
// to shift all values in sumleft[] by min before
// using them as an index in hash[].
int hash[max-min+1];
// Initialize hash table
for (i=0; i<max-min+1; i++)
989
Chapter 166. Largest subarray with equal number of 0s and 1s
hash[i] = -1;
for (i=0; i<n; i++)
{
// Case 1: when the subarray starts from
// index 0
if (sumleft[i] == 0)
{
maxsize = i+1;
startindex = 0;
}
// Case 2: fill hash table value. If already
// filled, then use it
if (hash[sumleft[i]-min] == -1)
hash[sumleft[i]-min] = i;
else
{
if ((i - hash[sumleft[i]-min]) > maxsize)
{
maxsize = i - hash[sumleft[i]-min];
startindex = hash[sumleft[i]-min] + 1;
}
}
}
if (maxsize == -1)
printf("No such subarray");
else
printf("%d to %d", startindex, startindex+maxsize-1);
return maxsize;
}
/* Driver program to test above functions */
int main()
{
int arr[] = {1, 0, 0, 1, 0, 1, 1};
int size = sizeof(arr)/sizeof(arr[0]);
findSubArray(arr, size);
return 0;
}
C++/STL
990
Chapter 166. Largest subarray with equal number of 0s and 1s
991
Chapter 166. Largest subarray with equal number of 0s and 1s
hM[sum + n] = i;
}
for (int i = 0; i < n; i++)
arr[i] = (arr[i] == -1)? 0: 1;
printf("%d to %d\n", ending_index-max_len+1, ending_index);
return max_len;
}
// Driver method
int main()
{
int arr[] = {1, 0, 0, 1, 0, 1, 1};
int n = sizeof(arr) / sizeof(arr[0]);
maxLen(arr, n);
return 0;
}
// This code is contributed by Aditya Goel
Java
import java.util.HashMap;
class LargestSubArray1
{
// Returns largest subarray with equal number of 0s and 1s
int maxLen(int arr[], int n)
{
// Creates an empty hashMap hM
HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>();
int sum = 0; // Initialize sum of elements
int max_len = 0; // Initialize result
int ending_index = -1;
int start_index = 0;
for (int i = 0; i < n; i++)
{
arr[i] = (arr[i] == 0) ? -1 : 1;
}
992
Chapter 166. Largest subarray with equal number of 0s and 1s
// Traverse through the given array
for (int i = 0; i < n; i++)
{
// Add current element to sum
sum += arr[i];
// To handle sum=0 at last index
if (sum == 0)
{
max_len = i + 1;
ending_index = i;
}
// If this sum is seen before, then update max_len
// if required
if (hM.containsKey(sum + n))
{
if (max_len < i - hM.get(sum + n))
{
max_len = i - hM.get(sum + n);
ending_index = i;
}
}
else // Else put this sum in hash table
hM.put(sum + n, i);
}
for (int i = 0; i < n; i++)
{
arr[i] = (arr[i] == -1) ? 0 : 1;
}
int end = ending_index - max_len + 1;
System.out.println(end + " to " + ending_index);
return max_len;
}
/* Driver program to test the above functions */
public static void main(String[] args)
{
LargestSubArray1 sub = new LargestSubArray1();
993
Chapter 166. Largest subarray with equal number of 0s and 1s
Output:
0 to 5
Source
https://www.geeksforgeeks.org/largest-subarray-with-equal-number-of-0s-and-1s/
994
Chapter 167
A simple solution is to iterate through all elements of given array. For every number,
check if it is Fibonacci or not. If yes, add it to the result.
Below is an efficient solution based on hashing.
C++
995
Chapter 167. Largest subset whose all elements are Fibonacci numbers
Java
996
Chapter 167. Largest subset whose all elements are Fibonacci numbers
class GFG
{
// Prints largest subset of an array whose
// all elements are fibonacci numbers
public static void findFibSubset(Integer[] x)
{
Integer max = Collections.max(Arrays.asList(x));
List<Integer> fib = new ArrayList<Integer>();
List<Integer> result = new ArrayList<Integer>();
// Generate all Fibonacci numbers
// till max and store them
Integer a = 0;
Integer b = 1;
while (b < max){
Integer c = a + b;
a=b;
b=c;
fib.add(c);
}
// Now iterate through all numbers and
// quickly check for Fibonacci
for (Integer i = 0; i < x.length; i++){
if(fib.contains(x[i])){
result.add(x[i]);
}
}
System.out.println(result);
}
// Driver code
public static void main(String args[])
{
Integer[] a = {4, 2, 8, 5, 20, 1, 40, 13, 23};
findFibSubset(a);
}
}
// This code is contributed by prag93
Output:
2 8 5 1 13
Reference :
https://www.careercup.com/question?id=5154130839470080
Improved By : prag93
997
Chapter 167. Largest subset whose all elements are Fibonacci numbers
Source
https://www.geeksforgeeks.org/largest-subset-whose-all-elements-are-fibonacci-numbers/
998
Chapter 168
A naive approach is to take every element and iterate and compare its last occurrence
with other elements. This requires two nested loops, and will take O(n*n) time.
999
Chapter 168. Last seen array element (last appearance is earliest)
An efficient approach is to use hashing. We store every elements index where it last
occurred, and then iterate through all the possible elements and print the element with
the least least index stored occurrence, as that will be the one which was last seen while
traversing from left to right.
Output:
1000
Chapter 168. Last seen array element (last appearance is earliest)
Source
https://www.geeksforgeeks.org/last-seen-array-element-last-appearance-earliest/
1001
Chapter 169
Method 1: The problem could be solved using the concept of finding the longest bitonic
subsequence. The only condition that needs to be maintained is that the adjacents should
have a difference of 1 only. It has a time complexity of O(n2 ).
Method 2 (Efficient Approach): The idea is to create two hash maps inc and dcr
having tuples in the form (ele, len), where len denotes the length of the longest increasing
subsequence ending with the element ele in map inc and length of the longest decreasing
subsequence starting with element ele in map dcr respectively. Also create two arrays
len_inc[] and len_dcr[] where len_inc[i] represents the length of the largest increasing
subsequence ending with element arr[i] and len_dcr[i] represents the length of the largest
1002
Chapter 169. Length of longest strict bitonic subsequence
decreasing subsequence starting with element arr[i]. Now, for each element arr[i] we can
find the length of the value (arr[i]-1) if it exists in the hash table inc. Let this value be
v (initially v will be 0). Now, the length of longest increasing subsequence ending with
arr[i] would be v+1. Update this length along with the element arr[i] in the hash table
inc and in the array len_inc[] at respective index i. Now, traversing the array from right
to left we can similarly fill the hash table dcr and array len_dcr[] for longest decreasing
subsequence. Finally, for each element arr[i] we calculate (len_inc[i] + len_dcr[i] – 1)
and return the maximum value.
Note: Here increasing and decreasing subsequences only mean that the difference between
adjacent elements is 1 only.
1003
Chapter 169. Length of longest strict bitonic subsequence
Output:
1004
Chapter 169. Length of longest strict bitonic subsequence
Source
https://www.geeksforgeeks.org/length-longest-strict-bitonic-subsequence/
1005
Chapter 170
The idea is similar to previous post. In the previous post, we checked whether maximum
value minus minimum value is equal to ending index minus starting index or not. Since
duplicate elements are allowed, we also need to check if the subarray contains duplicate
elements or not. For example, the array {12, 14, 12} follows the first property, but numbers
in it are not contiguous elements.
To check duplicate elements in a subarray, we create a hash set for every subarray and if we
find an element already in hash, we don’t consider the current subarray.
Following is the implementation of the above idea.
C++
1006
Chapter 170. Length of the largest subarray with contiguous elements | Set 2
1007
Chapter 170. Length of the largest subarray with contiguous elements | Set 2
int main ()
{
int arr[] = {10, 12, 12, 10, 10, 11, 10};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Length of the longest contiguous"
<< " subarray is " << findLength(arr, n);
}
// This article is contributed by Chhavi
Java
1008
Chapter 170. Length of the largest subarray with contiguous elements | Set 2
// We have already cheched for duplicates, now check
// for other property and update max_len if needed
if (mx-mn == j-i)
max_len = Math.max(max_len, mx-mn+1);
}
}
return max_len; // Return result
}
// Driver method to test above method
public static void main (String[] args)
{
int arr[] = {10, 12, 12, 10, 10, 11, 10};
System.out.println("Length of the longest contiguous subarray is " +
findLength(arr));
}
}
C#
1009
Chapter 170. Length of the largest subarray with contiguous elements | Set 2
Output:
Time complexity of the above solution is O(n2 ) under the assumption that hash set opera-
1010
Chapter 170. Length of the largest subarray with contiguous elements | Set 2
Source
https://www.geeksforgeeks.org/length-largest-subarray-contiguous-elements-set-2/
1011
Chapter 171
A simple solution is to use two nested loops to generate every substring. And a third loop
to count number of 0s and 1s in current substring. Time complexity of this would be O(n3 )
An efficient solution is to use hashing.
1) Traverse string and keep track of counts of 1s and 0s as count_1 and count_0 respectively.
2) See if current difference between two counts has appeared before (We use hashing to
store all differences and first index where a difference appears). If yes, then substring from
previous appearance and current index has same number of 0s and 1s.
C++
1012
Chapter 171. Length of the longest substring with equal 1s and 0s
// Returns length of the longest substring
// with equal number of zeros and ones.
int stringLen(string str)
{
// Create a map to store differences
// between counts of 1s and 0s.
map<int, int> m;
// Initially difference is 0.
m[0] = -1;
int count_0 = 0, count_1 = 0;
int res = 0;
for (int i=0; i<str.size(); i++)
{
// Keeping track of counts of
// 0s and 1s.
if (str[i] == '0')
count_0++;
else
count_1++;
// If difference between current counts
// already exists, then substring between
// previous and current index has same
// no. of 0s and 1s. Update result if this
// substring is more than current result.
if (m.find(count_1 - count_0) != m.end())
res = max(res, i - m[count_1 - count_0]);
// If current difference is seen first time.
else
m[count_1 - count_0] = i;
}
return res;
}
// driver function
int main()
{
string str = "101001000";
cout << "Length of longest balanced"
" sub string = ";
cout << stringLen(str);
return 0;
}
1013
Chapter 171. Length of the longest substring with equal 1s and 0s
Python3
1014
Chapter 171. Length of the longest substring with equal 1s and 0s
# This code is contributed by "Sharad_Bhardwaj"
Output:
Source
https://www.geeksforgeeks.org/length-of-the-longest-substring-with-equal-1s-and-0s/
1015
Chapter 172
Examples:
Input : "AABBBCBB"
Output : 5
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
1016
Chapter 172. Length of the smallest sub-string consisting of maximum distinct characters
1017
Chapter 172. Length of the smallest sub-string consisting of maximum distinct characters
Output:
Method 2 (Efficient)
Please refer Smallest window that contains all characters of string itself for implementation
and more details.
Asked In : DailyHunt
Source
https://www.geeksforgeeks.org/length-smallest-sub-string-consisting-maximum-distinct-characters/
1018
Chapter 173
Method(Brute force)
Iteratively check if their exist any pair or not
C++
1019
Chapter 173. Linked List Pair Sum
1020
Chapter 173. Linked List Pair Sum
/* Use push() to construct linked list*/
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
push(&head, 18);
push(&head, 47);
push(&head, 16);
push(&head, 12);
push(&head, 14);
/* function to print the result*/
bool res = check_pair_sum(head, 26);
if (res == false)
cout << "NO PAIR EXIST";
return 0;
}
Output:
14 12
Time complexity:O(n*n)
Method 2 (using hashing)
1. Take a hashtable and mark all element with zero
2. Iteratively mark all the element as 1 in hashtable which are present in linked list
3. Iteratively find sum-current element of linked list is present in hashtable or not
C++
1021
Chapter 173. Linked List Pair Sum
1022
Chapter 173. Linked List Pair Sum
push(&head, 1);
push(&head, 18);
push(&head, 47);
push(&head, 16);
push(&head, 12);
push(&head, 14);
/* function to print the result*/
bool res = check_pair_sum(head, 26);
if (res == false)
cout << "NO PAIR EXIST";
return 0;
}
Output:
14 12
Source
https://www.geeksforgeeks.org/linked-list-pair-sum/
1023
Chapter 174
1. K is converted into a small integer (called its hash code) using a hash function.
2. The hash code is used to find an index (hashCode % arrSize) and the entire linked list
at that index(Separate chaining) is first searched for the presence of the K already.
3. If found, it’s value is updated and if not, the K-V pair is stored as a new node in the
list.
• For the first step, time taken depends on the K and the hash function.
For example, if the key is a string “abcd”, then it’s hash function may depend on the
length of the string. But for very large values of n, the number of entries into the map,
length of the keys is almost negligible in comparison to n so hash computation can be
considered to take place in constant time, i.e, O(1).
• For the second step, traversal of the list of K-V pairs present at that index needs
to be done. For this, the worst case may be that all the n entries are at the same
index. So, time complexity would be O(n). But, enough research has been done to
make hash functions uniformly distribute the keys in the array so this almost never
happens.
• So, on an average, if there are n entries and b is the size of the array there would be
n/b entries on each index. This value n/b is called the load factor that represents
the load that is there on our map.
• This Load Factor needs to be kept low, so that number of entries at one index is less
and so is the complexity almost constant, i.e., O(1).
As the name suggests, rehashing means hashing again. Basically, when the load factor
increases to more than its pre-defined value (default value of load factor is 0.75), the com-
plexity increases. So to overcome this, the size of the array is increased (doubled) and all
the values are hashed again and stored in the new double sized array to maintain a low load
factor and low complexity.
1024
Chapter 174. Load Factor and Rehashing
Why rehashing?
Rehashing is done because whenever key value pairs are inserted into the map, the load
factor increases, which implies that the time complexity also increases as explained above.
This might not give the required time complexity of O(1).
Hence, rehash must be done, increasing the size of the bucketArray so as to reduce the load
factor and the time complexity.
• For each addition of a new entry to the map, check the load factor.
• If it’s greater than its pre-defined value (or default value of 0.75 if not given), then
Rehash.
• For Rehash, make a new array of double the previous size and make it the new buck-
etarray.
• Then traverse to each element in the old bucketArray and call the insert() for each so
as to insert it into the new larger bucket array.
1025
Chapter 174. Load Factor and Rehashing
1026
Chapter 174. Load Factor and Rehashing
}
head = head.next;
}
// new node with the K and V
MapNode<K, V> newElementNode = new MapNode<K, V>(key, value);
// The head node at the index
head = buckets.get(bucketInd);
// the new node is inserted
// by making it the head
// and it's next is the previous head
newElementNode.next = head;
buckets.set(bucketInd, newElementNode);
System.out.println("Pair(" + key + ", " + value + ") inserted successfully.\n");
// Incrementing size
// as new K-V pair is added to the map
size++;
// Load factor calculated
double loadFactor = (1.0 * size) / numBuckets;
System.out.println("Current Load factor = " + loadFactor);
// If the load factor is > 0.75, rehashing is done
if (loadFactor > DEFAULT_LOAD_FACTOR) {
System.out.println(loadFactor + " is greater than " + DEFAULT_LOAD_FACTOR);
System.out.println("Therefore Rehashing will be done.\n");
// Rehash
rehash();
System.out.println("New Size of Map: " + numBuckets + "\n");
}
System.out.println("Number of pairs in the Map: " + size);
System.out.println("Size of Map: " + numBuckets + "\n");
}
private void rehash()
{
System.out.println("\n***Rehashing Started***\n");
1027
Chapter 174. Load Factor and Rehashing
1028
Chapter 174. Load Factor and Rehashing
Output:
HashMap created
Number of pairs in the Map: 0
Size of Map: 5
Default Load Factor : 0.75
1029
Chapter 174. Load Factor and Rehashing
Size of Map: 5
Current HashMap:
key = 1, val = Geeks
Current HashMap:
key = 1, val = Geeks
key = 2, val = forGeeks
Current HashMap:
key = 1, val = Geeks
key = 2, val = forGeeks
key = 3, val = A
***Rehashing Started***
1030
Chapter 174. Load Factor and Rehashing
***Rehashing Ended***
Current HashMap:
key = 1, val = Geeks
key = 2, val = forGeeks
key = 3, val = A
key = 4, val = Computer
Current HashMap:
key = 1, val = Geeks
key = 2, val = forGeeks
key = 3, val = A
key = 4, val = Computer
key = 5, val = Portal
Source
https://www.geeksforgeeks.org/load-factor-and-rehashing/
1031
Chapter 175
Longest Consecutive
Subsequence
Input: arr[] = {36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42}
Output: 5
The subsequence 36, 35, 33, 34, 32 is the longest subsequence
of consecutive elements.
One Solution is to first sort the array and find the longest subarray with consecutive
elements. Time complexity of this solution is O(nLogn). Thanks to Hao.W for suggesting
this solution.
We can solve this problem in O(n) time using an Efficient Solution. The idea is to use
Hashing. We first insert all elements in a Hash. Then check all the possible starts of
consecutive subsequences. Below is complete algorithm.
1032
Chapter 175. Longest Consecutive Subsequence
1033
Chapter 175. Longest Consecutive Subsequence
}
return ans;
}
// Driver program
int main()
{
int arr[] = {1, 9, 3, 10, 4, 20, 2};
int n = sizeof arr/ sizeof arr[0];
cout << "Length of the Longest contiguous subsequence is "
<< findLongestConseqSubseq(arr, n);
return 0;
}
Java
1034
Chapter 175. Longest Consecutive Subsequence
if (ans<j-arr[i])
ans = j-arr[i];
}
}
return ans;
}
// Testing program
public static void main(String args[])
{
int arr[] = {1, 9, 3, 10, 4, 20, 2};
int n = arr.length;
System.out.println("Length of the Longest consecutive subsequence is " +
findLongestConseqSubseq(arr,n));
}
}
// This code is contributed by Aakash Hasija
Python
1035
Chapter 175. Longest Consecutive Subsequence
ans=max(ans, j-arr[i])
return ans
# Driver function
if __name__=='__main__':
n = 7
arr = [1, 9, 3, 10, 4, 20, 2]
print "Length of the Longest contiguous subsequence is ",
print findLongestConseqSubseq(arr, n)
# Contributed by: Harshit Sidhwa
Output:
Time Complexity: At first look, time complexity looks more than O(n). If we take a
closer look, we can notice that it is O(n) under the assumption that hash insert and search
take O(1) time. The function S.find() inside the while loop is called at most twice for every
element. For example, consider the case when all array elements are consecutive. In this
case, the outer find is called for every element, but we go inside the if condition only for the
smallest element. Once we are inside the if condition, we call find() one more time for every
other element.
Thanks to Gaurav Ahirwar for above solution.
Source
https://www.geeksforgeeks.org/longest-consecutive-subsequence/
1036
Chapter 176
Naive Approach: A normal approach will be to iterate for every element and find out
the longest increasing subsequence. For any particular element, find the length of the
subsequence starting from that element. Print the longest length of the subsequence thus
formed. The time complexity of this approach will be O(n2 ).
Dynamic Programming Approach: Let DP[i] store the length of the longest subse-
quence which ends with A[i]. For every A[i], if A[i]-1 is present in the array before i-th
index, then A[i] will add to the increasing subsequence which has A[i]-1. Hence DP[i] =
DP[ index(A[i]-1) ] + 1. If A[i]-1 is not present in the array before i-th index, then
DP[i]=1 since the A[i] element forms a subsequence which starts with A[i]. Hence the
relation for DP[i] is:
1037
Chapter 176. Longest Increasing consecutive subsequence
else:
DP[i] = 1
1038
Chapter 176. Longest Increasing consecutive subsequence
Output:
Source
https://www.geeksforgeeks.org/longest-increasing-consecutive-subsequence/
1039
Chapter 177
Longest string in non-decreasing order of ASCII code and in arithmetic progression - Geeks-
forGeeks
Given a non-empty string S of uppercase alphabets of length L and the task is to find the
longest string from the given string with characters arranged in descending order of their
ASCII code and in arithmetic progression such that the common difference should be as low
as possible and the characters of the string to be of higher ASCII value.
Note : The string contains minimum three different characters.
Examples:
Input : S = “ABCPQR”
Output : “RQP”
Two strings of maximum length are possible – “CBA” and “RPQ”. But since
the string should be of higher ASCII value hence, the output is “RPQ”.
Input : S = “ADGJPRT”
Output : “JGDA”
1040
Chapter 177. Longest string in non-decreasing order of ASCII code and in arithmetic
progression
Also, at every updation of these two parameters, starting character of the string or arithmetic
progression sequence must also be updated.
Below is the implementation of above approach:
C++
1041
Chapter 177. Longest string in non-decreasing order of ASCII code and in arithmetic
progression
Java
1042
Chapter 177. Longest string in non-decreasing order of ASCII code and in arithmetic
progression
import java.lang.*;
public class GFG {
// Function to find the longest String
static String findLongestString(String S)
{
// Stores the maximum length of required string
int maxLen = 0;
// Stores the optimal starting character of
// required string or arithmetic progression sequence
int bestStartChar = 0;
// Stores the optimal i.e. minimum common difference
// of required string
int minCommonDifference = Integer.MAX_VALUE;
HashMap <Character, Boolean> hm = new HashMap
<Character, Boolean>();
for (int i = 0; i < S.length(); i++)
hm.put(S.charAt(i), true);
// Iterate over the loop in non decreasing order
for (int startChar = 'Z'; startChar > 'A'; startChar--) {
// Process further only if current character
// exists in the given string
if (hm.containsKey((char)startChar)) {
// Iterate over all possible common differences
// of AP sequence and update maxLen accordingly
for (int currDiff = 1; currDiff <= 12; currDiff++) {
int currLen = 1;
// Iterate over the characters at any interval
// of current common difference
for (int ch = startChar - currDiff; ch >= 'A';
ch -= currDiff) {
if (hm.containsKey((char)ch))
currLen++;
else
break;
}
// Update maxLen and other parameters if the currLen
// is greater than maxLen or if the current
// difference is smaller than minCommonDifference
if (currLen > maxLen || (currLen == maxLen
1043
Chapter 177. Longest string in non-decreasing order of ASCII code and in arithmetic
progression
Output:
JGDA
Time Complexity : O(|S| + 26*12*26), where |S| is the size of the string.
Improved By : Nishant Tanwar
Source
https://www.geeksforgeeks.org/longest-string-in-non-decreasing-order-of-ascii-code-and-in-arithmetic-progression/
1044
Chapter 178
Naive Approach: Consider the sum of all the sub-arrays and return the length of the
longest sub-array having sum ‘k’. Time Complexity is of O(n^2).
Efficient Approach: Following are the steps:
1045
Chapter 178. Longest sub-array having sum k
4. Return maxLen.
1046
Chapter 178. Longest sub-array having sum k
// Driver Code
int main()
{
int arr[] = {10, 5, 2, 7, 1, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 15;
cout << "Length = "
<< lenOfLongSubarr(arr, n, k);
return 0;
}
Output:
Length = 4
Source
https://www.geeksforgeeks.org/longest-sub-array-sum-k/
1047
Chapter 179
1048
Chapter 179. Longest subarray having count of 1s one more than count of 0s
1049
Chapter 179. Longest subarray having count of 1s one more than count of 0s
int arr[] = { 0, 1, 1, 0, 0, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Length = "
<< lenOfLongSubarr(arr, n);
return 0;
}
Output:
Length = 5
Source
https://www.geeksforgeeks.org/longest-subarray-count-1s-one-count-0s/
1050
Chapter 180
1. Find the maximum sum contiguous subarray. Let this sum be maxSum.
2. Find the length of the longest subarray having sum equal to maxSum. Refer this
post.
1051
Chapter 180. Longest subarray having maximum sum
1052
Chapter 180. Longest subarray having maximum sum
}
// required maximum length
return maxLen;
}
// function to find the length of the longest
// subarray having maximum sum
int lenLongSubarrWithMaxSum(int arr[], int n)
{
int maxSum = maxSubArraySum(arr, n);
return lenOfLongSubarrWithGivenSum(arr, n, maxSum);
}
// Driver program to test above
int main()
{
int arr[] = { 5, -2, -1, 3, -4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Length of longest subarray having maximum sum = "
<< lenLongSubarrWithMaxSum(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/longest-subarray-having-maximum-sum/
1053
Chapter 181
A naive approach will be to be traverse in the array and use hashing for every sub-arrays,
and check for the longest sub-array possible with no more than K distinct elements.
An efficient approach is to use the concept of two pointers where we maintain a hash to
count for occurrences of elements. We start from the beginning and keep a count of distinct
elements till the number exceeds k. Once it exceeds K, we start decreasing the count of
the elements in the hash from where the sub-array started and reduce our length as the
sub-arrays gets decreased so the pointer moves to the right. We keep removing elements till
we again get k distinct elements. We continue this process till we again have more than k
1054
Chapter 181. Longest subarray not having more than K distinct elements
distinct elements and keep the left pointer constant till then. We update our start and end
according to that if the new sub-array length is more than the previous one.
1055
Chapter 181. Longest subarray not having more than K distinct elements
}
// print the longest sub-segment
for (int i = start; i <= end; i++)
cout << a[i] << " ";
}
// driver program to test the above function
int main()
{
int a[] = { 6, 5, 1, 2, 3, 2, 1, 4, 5 };
int n = sizeof(a) / sizeof(a[0]);
int k = 3;
longest(a, n, k);
return 0;
}
Output:
1 2 3 2 1
Source
https://www.geeksforgeeks.org/longest-subarray-not-k-distinct-elements/
1056
Chapter 182
Method 1 (Naive Approach): Consider all the subarrays and return the length of the
subarray with sum divisible by k and has the longest length.
Time Complexity: O(n2 ).
Method 2 (Efficient Approach): Create an array mod_arr[] where mod_arr[i] stores
(sum(arr[0]+arr[1]..+arr[i]) % k). Create a hash table having tuple as (ele, idx),
where ele represents an element of mod_arr[] and idx represents the element’s index of
first occurrence in mod_arr[]. Now, traverse mod_arr[] from i = 0 to n and follow the
steps given below.
1057
Chapter 182. Longest subarray with sum divisible by k
1058
Chapter 182. Longest subarray with sum divisible by k
else
// if true, then update 'max'
if (max < (i - um[mod_arr[i]]))
max = i - um[mod_arr[i]];
}
// required length of longest subarray with
// sum divisible by 'k'
return max;
}
// Driver program to test above
int main()
{
int arr[] = {2, 7, 6, 1, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout << "Length = "
<< longSubarrWthSumDivByK(arr, n, k);
return 0;
}
Java
1059
Chapter 182. Longest subarray with sum divisible by k
1060
Chapter 182. Longest subarray with sum divisible by k
Output:
Length = 3
Source
https://www.geeksforgeeks.org/longest-subarray-sum-divisible-k/
1061
Chapter 183
Longest subsequence such that difference between adjacents is one | Set 2 - GeeksforGeeks
Given an array of size n. The task is to find the longest subsequence such that difference
between adjacents is one. Time Complexity of O(n) is required.
Examples:
Method 1: Previously an approach having time complexity of O(n2 ) have been discussed
in this post.
Method 2 (Efficient Approach): The idea is to create a hash map having tuples in
the form (ele, len), where len denotes the length of the longest subsequence ending with
the element ele. Now, for each element arr[i] we can find the length of the values arr[i]-1
and arr[i]+1 in the hash table and consider the maximum among them. Let this maximum
value be max. Now, the length of longest subsequence ending with arr[i] would be max+1.
Update this length along with the element arr[i] in the hash table. Finally, the element
having the maximum length in the hash table gives the longest length subsequence.
1062
Chapter 183. Longest subsequence such that difference between adjacents is one | Set 2
1063
Chapter 183. Longest subsequence such that difference between adjacents is one | Set 2
// Driver program to test above
int main()
{
int arr[] = {1, 2, 3, 4, 5, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Longest length subsequence = "
<< longLenSub(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/longest-subsequence-difference-adjacents-one-set-2/
1064
Chapter 184
Input : 1010
Output : 3
Substring 101 has 1 occuring more number of times than 0.
Input : 101100
Output : 5
Substring 10110 has 1 occuring more number of times than 0.
A simple solution is to one by one consider all the substrings and check if that substring
has count of 1 more than 0. If count is more than compare its length with maximum length
substring found till now. Time complexity of this solution is O(n^2).
An efficient solution is to use hashing. The idea is to find sum of string traversed until
now. Add 1 to the result if current character is ‘1’ else subtract 1. Now the problem reduces
to finding largest subarray having sum greater than zero. To find largest subarray having
sum greater than zero, we check the value of sum. If sum is greater than zero, then largest
subarray with sum greater than zero is arr[0..i]. If sum is less than zero, then find size of
subarray arr[j+1..i], where j is index upto which sum of subarray arr[0..j] is sum -1 and j <
i and compare that size with largest subarray size found so far. To find index j, store values
of sum for arr[0..j] in hash table for all 0 <= j <= i. There might be possibility that a given
value of sum repeats. In that case store only first index for which that sum is obtained as it
is required to get length of largest subarray and that is obtained from first index occurrence.
Below is the implementation of above approach:
1065
Chapter 184. Longest substring with count of 1s more than 0s
1066
Chapter 184. Longest substring with count of 1s more than 0s
}
}
// Make entry for this sum value in hash
// table if this value is not present.
if (prevSum.find(sum) == prevSum.end())
prevSum[sum] = i;
}
return maxlen;
}
// Driver code
int main()
{
string bin = "1010";
cout << findLongestSub(bin);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/longest-substring-with-count-of-1s-more-than-0s/
1067
Chapter 185
Input : GeeksForGeeks
Output : e39b9c178b2c9be4e99b141d956c6ff6
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
// Java program to calculate MD5 hash value
public class MD5 {
1068
Chapter 185. MD5 hash in Java
Output:
Your HashCode Generated by MD5 is: e39b9c178b2c9be4e99b141d956c6ff6
References:
Java Docs for MessageDigest
Source
https://www.geeksforgeeks.org/md5-hash-in-java/
1069
Chapter 186
Note: A number is in majority in an array if it occurs more than half times of the size of
an array.
Examples:
1070
Chapter 186. Majority element in a circular array of 0’s and 1’s
Approach:
1. First of all, iterate over the circular array and count the total number of 1’s in each
of p subarray(of size q).
2. Store this number into another array (of size p).
3. If in this case, 1 is in majority then, print yes.
4. Else take another set by moving the previous set’s index 1 unit either increasing or
decreasing it, and keep track of only those indices which are new in given set and
update number of 1’s in the array.
5. Repeat the 2nd and 3rd step.
We will repeat q times if there is no majority of 1 found until that, the answer would be
NO, else ( like in the previous example case ) the answer would be 1.
Since at the maximum, we can repeat this process q times and each time we are tracking
only two elements in each of p subarray.
Explanation:
In given example-1, we will divide circular subarray as [indices] => {1, 2, 3}, {4, 5, 6}, {7,
8, 9} and store number of 1’s in another array which are [1, 2, 1] in subarrays respectively.
Taking another set in example 1 by increasing 1 unit so set will be {2, 3, 4}, {5, 6, 7}, {8,
9, 1} now in set 1 only change is inclusion of element 4 and removal of element 1, we will
only track these so updated number of 1’s will be 2, 2, 0.
Below is the implementation of above approach:
C++
1071
Chapter 186. Majority element in a circular array of 0’s and 1’s
while (k < p) {
int one = 0;
for (int j = start; j < ends; j++) {
if (a[j] == 1) {
one++;
}
}
// starting index of next subarray
start = ends;
// ending index of next subarray
ends = ends + q;
// storing 1's
arr[k] = one;
k++;
}
start = 0;
ends = q;
// variable to keep a check
// if 1 is in majority or not
bool found = 0;
// In this case, we are repeating
// the task of calculating
// total number of 1's backward
while (ends > 0) {
// to store the total number of 1's
int dist_one = 0;
// Check if 1 is in majority in
// this subarray
for (int i = 0; i < p; i++)
if (arr[i] > q / 2)
dist_one++;
// If 1 is in majority return
if (dist_one > p / 2) {
found = 1;
cout << "Yes" << endl;
return;
}
1072
Chapter 186. Majority element in a circular array of 0’s and 1’s
1073
Chapter 186. Majority element in a circular array of 0’s and 1’s
{
int p = 3, q = 3;
int n = p * q;
bool a[] = { 0, 0, 1, 1, 0, 1, 1, 0, 0 };
// circular array of given size
majority(a, p, q, n);
return 0;
}
Java
1074
Chapter 186. Majority element in a circular array of 0’s and 1’s
// ending index of next subarray
ends = ends + q;
// storing 1's
arr[k] = one;
k++;
}
start = 0;
ends = q;
// variable to keep a check
// if 1 is in majority or not
boolean found = false;
// In this case, we are repeating
// the task of calculating
// total number of 1's backward
while (ends > 0) {
// to store the total number of 1's
int dist_one = 0;
// Check if 1 is in majority in
// this subarray
for (int i = 0; i < p; i++)
if (arr[i] > q / 2)
dist_one++;
// If 1 is in majority return
if (dist_one > p / 2) {
found = true;
System.out.println( "Yes" );
return;
}
// shifting starting index of
// subarray by 1 unit leftwards
start--;
// shifting ending index of
// subarray by 1 unit leftwards
ends--;
// to ensure it is a valid index
// ( array is circular) -1 index means
1075
Chapter 186. Majority element in a circular array of 0’s and 1’s
1076
Chapter 186. Majority element in a circular array of 0’s and 1’s
}
}
// This code is Contributed by tufan_gupta2000
Output:
Yes
Improved By : tufan_gupta2000
Source
https://www.geeksforgeeks.org/majority-element-in-a-circular-array-of-0s-and-1s/
1077
Chapter 187
Input : 1->2->3->4->5->1->1->1->NULL
Output : 1
Explanation 1 occurs 4 times
Input :10->23->11->9->54->NULL
Output :NO majority element
Method 1(simple)
Run two loops starting from head and count frequency of each element iteratively. Print the
element whose frequency is greater than or equal to n/2. In this approach time complexity
will be O(n*n) where n is the number of nodes in the linked list.
C++
1078
Chapter 187. Majority element in a linked list
1079
Chapter 187. Majority element in a linked list
/* Driver program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
// create linked
push(&head, 1);
push(&head, 1);
push(&head, 1);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
int res = majority(head);
if (res != (-1))
cout << "Majority element is " << res;
else
cout << "No majority element";
return 0;
}
C++
1080
Chapter 187. Majority element in a linked list
1081
Chapter 187. Majority element in a linked list
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
int res = majority(head);
if (res != (-1))
cout << "majority element is " << res;
else
cout << "NO majority elemenet";
return 0;
}
majority element is 1
Source
https://www.geeksforgeeks.org/majority-element-in-a-linked-list/
1082
Chapter 188
If we take a closer look at this problem, we can observe that the problem reduces to finding
intersection of two sets.
A simple solution is iterate through every element of first set and for every element,
check if it is present in second set. If present, increment count of elements to be removed.
1083
Chapter 188. Make two sets disjoint by removing minimum elements
C++
Java
1084
Chapter 188. Make two sets disjoint by removing minimum elements
C#
1085
Chapter 188. Make two sets disjoint by removing minimum elements
PHP
<?php
// PHP simple program to find
// total elements to be removed
// to make two sets disjoint.
// Function for find minimum
// elements to be removed from
// both sets so that they become disjoint
function makeDisjoint( $set1, $set2, $n, $m)
{
$result = 0;
1086
Chapter 188. Make two sets disjoint by removing minimum elements
Output :
1087
Chapter 188. Make two sets disjoint by removing minimum elements
// table
unordered_set <int> s;
for (int i = 0; i < n; i++)
s.insert(set1[i]);
// We need to remove all those elements from
// set2 which are in set1.
int result = 0;
for (int i = 0; i < m; i++)
if (s.find(set2[i]) != s.end())
result++;
return result;
}
// Driver code
int main()
{
int set1[] = {20, 21, 22};
int set2[] = {22, 23, 24, 25, 20};
int n = sizeof(set1)/sizeof(set1[0]);
int m = sizeof(set2)/sizeof(set2[1]);
cout << makeDisjoint(set1, set2, n, m);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/make-two-sets-disjoint-removing-minimum-elements/
1088
Chapter 189
Approach : We create an auxiliary array of size 2*n and store the elements of 2nd array
in auxiliary array, and then we will store elements of 1st array in it. After that we will
sort auxiliary array in decreasing order. To keep the order of elements according to input
arrays we will use hash table. We will store 1st n largest unique elements of auxiliary array
in hash table. Now we traverse the second array and store that elements of second array
in auxiliary array that are present in hash table. Similarly we will traverse first array and
store the elements that are present in hash table. In this way we get n unique and largest
elements from both the arrays in auxiliary array while keeping the order of appearance of
elements same.
Below is the implementation of above approach :
1089
Chapter 189. Maximize elements using another array
1090
Chapter 189. Maximize elements using another array
// if arr2 element is present in hash,
// store it in arr3
if (hash.find(arr2[i]) != hash.end()) {
arr3[k++] = arr2[i];
hash.erase(arr2[i]);
}
}
// store that elements of arr1 in arr3
// that are present in hash
for (int i = 0; i < n; i++) {
// if arr1 element is present in hash,
// store it in arr3
if (hash.find(arr1[i]) != hash.end()) {
arr3[k++] = arr1[i];
hash.erase(arr1[i]);
}
}
// copying 1st n elements of arr3 to arr1
for (int i = 0; i < n; i++)
arr1[i] = arr3[i];
}
// Function to print array elements
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver Code
int main()
{
int array1[] = { 7, 4, 8, 0, 1 };
int array2[] = { 9, 7, 2, 3, 6 };
int size = sizeof(array1) / sizeof(array1[0]);
maximizeArray(array1, array2, size);
printArray(array1, size);
}
Output:
9 7 6 4 8
1091
Chapter 189. Maximize elements using another array
Source
https://www.geeksforgeeks.org/maximize-elements-using-another-array/
1092
Chapter 190
A simple solution is to run two loops. For every subarray find all distinct elements and
print maximum unique element.
An efficient solution is to use sliding window technique. We maintain two structures in
every window.
1) A hash table to store counts of all elements in current window.
2) A self balancing BST (implemented using set in C++ STL and TreeSet in Java). The
idea is to quickly find maximum element and update maximum element.
We process first K-1 elements and store their counts in hash table. We also store unique
elements in set. Now we one by one process last element of every window. If current element
is unique, we add it to set. We also increase its count. After processing last element, we
1093
Chapter 190. Maximum Unique Element in every subarray of size K
print maximum from set. Before starting next iteration, we remove first element of previous
window.
1094
Chapter 190. Maximum Unique Element in every subarray of size K
if (Count[x] == 0)
Myset.erase(x);
}
}
// Driver code
int main()
{
int a[] = { 1, 2, 2, 3, 3 };
int n = sizeof(a) / sizeof(a[0]);
int k = 3;
find_max(a, n, k);
return 0;
}
Output:
1
3
2
Source
https://www.geeksforgeeks.org/maximum-unique-element-every-subarray-size-k/
1095
Chapter 191
Method 1 (Sorting)
The task basically reduces to finding two pairs of equal values in array. If there are more
than two pairs, then pick the two pairs with maximum values. A simple solution is to do
following.
1) Sort the given array.
2) Traverse array from largest to smallest value and return two pairs with maximum values.
C++
1096
Chapter 191. Maximum area rectangle by picking four sides from array
// function for finding max area
int findArea(int arr[], int n)
{
// sort array in non-increasing order
sort(arr, arr + n, greater<int>());
// Initialize two sides of rectangle
int dimension[2] = { 0, 0 };
// traverse through array
for (int i = 0, j = 0; i < n - 1 && j < 2; i++)
// if any element occurs twice
// store that as dimension
if (arr[i] == arr[i + 1])
dimension[j++] = arr[i++];
// return the product of dimensions
return (dimension[0] * dimension[1]);
}
// driver function
int main()
{
int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findArea(arr, n);
return 0;
}
Java
1097
Chapter 191. Maximum area rectangle by picking four sides from array
// traverse through array
for (int i = 0, j = 0; i < n - 1 && j < 2;
i++)
// if any element occurs twice
// store that as dimension
if (arr[i] == arr[i + 1])
dimension[j++] = arr[i++];
// return the product of dimensions
return (dimension[0] * dimension[1]);
}
// driver function
public static void main(String args[])
{
Integer arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };
int n = arr.length;
System.out.println(findArea(arr, n));
}
}
// This code is contributed by Sumit Ghosh
Python3
1098
Chapter 191. Maximum area rectangle by picking four sides from array
PHP
<?php
// PHP program for finding maximum area possible
// of a rectangle
// function for finding max area
function findArea($arr, $n)
{
// sort array in non-
// increasing order
rsort($arr);
// Initialize two sides
// of rectangle
$dimension = array( 0, 0 );
// traverse through array
for( $i = 0, $j = 0; $i < $n - 1 &&
$j < 2; $i++)
// if any element occurs twice
// store that as dimension
if ($arr[$i] == $arr[$i + 1])
$dimension[$j++] = $arr[$i++];
// return the product
1099
Chapter 191. Maximum area rectangle by picking four sides from array
// of dimensions
return ($dimension[0] *
$dimension[1]);
}
// Driver Code
$arr = array(4, 2, 1, 4, 6, 6, 2, 5);
$n =count($arr);
echo findArea($arr, $n);
// This code is contributed by anuj_67.
?>
Output:
24
Method 2 (Hashing)
The idea is to insert all first occurrences of elements in a hash set. For second occurrences,
keep track of maximum two values.
C++
1100
Chapter 191. Maximum area rectangle by picking four sides from array
// If this is second (or more) occurrence,
// update first and second maximum values.
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second)
second = arr[i];
}
// return the product of dimensions
return (first * second);
}
// driver function
int main()
{
int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findArea(arr, n);
return 0;
}
Java
1101
Chapter 191. Maximum area rectangle by picking four sides from array
}
// If this is second (or more)
// occurrence, update first and
// second maximum values.
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second)
second = arr[i];
}
// return the product of dimensions
return (first * second);
}
// driver function
public static void main(String args[])
{
int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 };
int n = arr.length;
System.out.println(findArea(arr, n));
}
}
// This code is contributed by Sumit Ghosh
Output:
24
Source
https://www.geeksforgeeks.org/maximum-area-rectangle-picking-four-sides-array/
1102
Chapter 192
Maximum array from two given arrays keeping order same - GeeksforGeeks
Given two same sized arrays A[] and B[] (both arrays contain distinct elements individually
but may have some common elements), task is to form a third (or result) array of same size.
The result array should have maximum n elements from both array. It should have chosen
elements of A[] first, then chosen elements of B[] in same order as they appear in original
arrays. If there are common elements, then only one element should be present in res[] and
priority should be given to A[].
Examples:
Input : A[] = [ 9 7 2 3 6 ]
B[] = [ 7 4 8 0 1 ]
Output : res[] = [9 7 6 4 8]
res[] has maximum n elements of both A[]
and B[] such that elements of A[] appear
first (in same order), then elements of B[].
Also 7 is common and priority is given to
A's 7.
Input : A[] = [ 6 7 5 3 ]
B[] = [ 5 6 2 9 ]
Output : res[] = [ 6 7 5 9 ]
1) Create copies of both arrays and sort the copies in decreasing order.
2) Use a hash to pick unique n maximum elements of both arrays, giving priority to A[].
3) Initialize result array as empty.
4) Traverse through A[], copy those elements of A[] that are present in the hash. This is
done to keep order of elements same.
1103
Chapter 192. Maximum array from two given arrays keeping order same
5) Repeat step 4 for B[]. This time we only consider those elements that are not present in
A[] (Do not appear twice in hash).
Below c++ implementation of above idea.
1104
Chapter 192. Maximum array from two given arrays keeping order same
Output:
9 7 6 4 8
Source
https://www.geeksforgeeks.org/maximum-array-from-two-given-arrays-keeping-order-same/
1105
Chapter 193
The idea is to use hashing. We traverse through the array and for every element, we check
if it is the starting element of its sequence. If yes then by incrementing its value we search
the set and increment the length. By repeating this for all elements, we can find the lengths
of all consecutive sets in array. Finally we return length of the largest set.
1106
Chapter 193. Maximum consecutive numbers present in an array
Output:
1107
Chapter 193. Maximum consecutive numbers present in an array
Source
https://www.geeksforgeeks.org/maximum-consecutive-numbers-present-array/
1108
Chapter 194
Maximum difference between first and last indexes of an element in array - GeeksforGeeks
Given an array of n integers. The task is to find the difference of first and last index of each
distinct element so as to maximize the difference.
Examples:
Input : {2, 1, 3, 4, 2, 1, 5, 1, 7}
Output : 6
Element 1 has its first index = 1
and last index = 7
Difference = 7 - 1 = 6
Other elements have a smaller first and last
index difference
Input : {2, 2, 1, 1, 8, 8, 3, 5, 3}
Output : 2
Maximum difference is for indexes of element 3.
A simple approach is to run two loops and find the difference for each element and
accordingly update the max_diff. It has a time complexity of O(n2 ) and the approach also
needs to keep track of the elements that have been visited so that difference for them is not
calculated unnecessarily.
An efficient approach uses hashing. It has the following steps.
1109
Chapter 194. Maximum difference between first and last indexes of an element in array
2. For each distinct element map its first and last index in the hash table.
3. Traverse the hash table and calculate the first and last index difference for each ele-
ment.
4. Accordingly update the max_diff.
In the following implementation unordered_map has been used for hashing as the range of
integers is not known.
C++
1110
Chapter 194. Maximum difference between first and last indexes of an element in array
{
// difference of last and first index
// of each element
diff = (itr->second).l - (itr->second).f;
// update 'max_dff'
if (max_diff < diff)
max_diff = diff;
}
// required maximum difference
return max_diff;
}
// Driver program to test above
int main()
{
int arr[] = {2, 1, 3, 4, 2, 1, 5, 1, 7};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum Difference = "
<<maxDifference(arr, n);
return 0;
}
Java
1111
Chapter 194. Maximum difference between first and last indexes of an element in array
public static void main(String[] args) {
int arr[]={2, 1, 3, 4, 2, 1, 5, 1, 7};
System.out.println("Maximum Difference= "+ maxDiffIndices(arr));
}
private static int maxDiffIndices(int[] arr) {
int n = arr.length;
int maxDiffIndex = 0;
Map<Integer, Element> map = new HashMap<Integer, Element>();
for (int i = 0; i < n; i++) {
if (map.containsKey(arr[i])) {
Element e = map.get(arr[i]);
e.second = i;
} else {
Element e = new Element();
e.first = i;
map.put(arr[i], e);
}
}
for (Map.Entry<Integer, Element> entry : map.entrySet()) {
Element e = entry.getValue();
if ((e.second - e.first) > maxDiffIndex)
maxDiffIndex = e.second - e.first;
}
return maxDiffIndex;
}
}
Output:
Maximum Difference = 6
Source
https://www.geeksforgeeks.org/maximum-difference-first-last-indexes-element-array/
1112
Chapter 195
Maximum difference between frequency of two elements such that element having greater
frequency is also greater - GeeksforGeeks
Given an array of n positive integers with many repeating elements. The task is to find
maximum difference between the frequency of any two different elements, such that the
element with greater frequency is also greater in value than the second integer.
Examples:
Input : arr[] = { 3, 1, 3, 2, 3, 2 }.
Output : 2
Frequency of 3 = 3.
Frequency of 2 = 2.
Frequency of 1 = 1.
Here difference of frequency of element 3 and 1 is = 3 - 1 = 2.
Also 3 > 1.
1113
Chapter 195. Maximum difference between frequency of two elements such that element
having greater frequency is also greater
1114
Chapter 195. Maximum difference between frequency of two elements such that element
having greater frequency is also greater
Output:
1115
Chapter 195. Maximum difference between frequency of two elements such that element
having greater frequency is also greater
Output:
Source
https://www.geeksforgeeks.org/maximum-difference-between-frequency-of-two-elements-such-that-element-having-
1116
Chapter 196
A simple solution for this problem is to one by one pick each element from array and
find its first and last occurence in array and take difference of first and last occurence for
maximum distance. Time complexity for this approach is O(n2 ).
An efficient solution for this problem is to use hashing. The idea is to traverse input
array and store index of first occurrence in a hash map. For every other occurrence, find
the difference between index and the first index stored in hash map. If difference is more
than result so far, then update the result.
Below are implementations of the idea. The C++ implementation uses unordered_map in
C++.
C++
1117
Chapter 196. Maximum distance between two occurrences of same element in array
Python
1118
Chapter 196. Maximum distance between two occurrences of same element in array
Output:
10
Time complexity : O(n) under the assumption that unordered_map’s search and insert
operations take O(1) time.
Source
https://www.geeksforgeeks.org/maximum-distance-two-occurrences-element-array/
1119
Chapter 197
1120
Chapter 197. Maximum distinct elements after removing k elements
#include <bits/stdc++.h>
using namespace std;
// function to find maximum distinct elements
// after removing k elements
int maxDistinctNum(int arr[], int n, int k)
{
// 'um' implemented as hash table to store
// frequency of each element
unordered_map<int, int> um;
// priority_queue 'pq' implemented as
// max heap
priority_queue<int> pq;
// storing frequency of each element in 'um'
for (int i = 0; i < n; i++)
um[arr[i]]++;
// inserting frequency of each element in 'pq'
for (auto it = um.begin(); it != um.end(); it++)
pq.push(it->second);
while (k--) {
// get the top element of 'pq'
int temp = pq.top();
// remove top element from 'pq'
pq.pop();
// decrement the popped element by 1
temp--;
// if true, then push the element in 'pq'
if (temp != 0)
pq.push(temp);
}
// required maximum distinct elements
return ((int)pq.size());
}
// Driver program to test above
int main()
{
int arr[] = { 5, 7, 5, 5, 1, 2, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
1121
Chapter 197. Maximum distinct elements after removing k elements
int k = 3;
cout << "Maximum distinct elements = "
<< maxDistinctNum(arr, n, k);
return 0;
}
Output:
Time Complexity: O(k*logd), where d is the number of distinct elements in the given array.
Source
https://www.geeksforgeeks.org/maximum-distinct-elements-removing-k-elements/
1122
Chapter 198
Input : zACaAbbaazzC
Output : The maximum count = 3
Input : edxedxxxCQiIVmYEUtLi
Output : The maximum count = 1
• Declare an array of size 26 where each index of the array represents a character in
English alphabet
• Iterate the string over its complete length
• For each lowercase character, increment the index of the corresponding array by 1.
• For each uppercase character, iterate the array and count the number of positions
having value greater than zero.
• If this count is greater than the maximum count, update the maximum counter and
initialize the array by 0.
C++
1123
Chapter 198. Maximum distinct lowercase alphabets between two uppercase
1124
Chapter 198. Maximum distinct lowercase alphabets between two uppercase
// If character is in lowercase
if (str[i] >= 'a' && str[i] <= 'z')
count[str[i] - 'a']++;
}
return maxCount;
}
// Driver function
int main()
{
string str = "zACaAbbaazzC";
cout << maxLower(str);
return 0;
}
Python3
1125
Chapter 198. Maximum distinct lowercase alphabets between two uppercase
Output:
Method 2 (Using Hash Table):In this method, we extensively use the C++ STL con-
tainer unordered_set.
Below is the implementation of above method :
1126
Chapter 198. Maximum distinct lowercase alphabets between two uppercase
// Function which computes the
// maximum number of distinct
// lowercase alphabets between
// two uppercase alphabets
int maxLower(string str)
{
int n = str.length();
// Ignoring lowercase characters in the
// beginning.
int i = 0;
for (; i < n; i++) {
if (str[i] >= 'A' && str[i] <= 'Z') {
i++;
break;
}
}
// We start from next of first capital letter
// and traverse through remaining character.
int maxCount = 0;
unordered_set<int> s;
for (; i < n; i++) {
// If character is in uppercase,
if (str[i] >= 'A' && str[i] <= 'Z') {
// Update maximum count if lowercase
// character before this is more.
maxCount = max(maxCount, (int)s.size());
// clear the set
s.clear();
}
// If character is in lowercase
if (str[i] >= 'a' && str[i] <= 'z')
s.insert(str[i]);
}
return maxCount;
}
// Driver function
int main()
{
string str = "zACaAbbaazzC";
1127
Chapter 198. Maximum distinct lowercase alphabets between two uppercase
Output:
Time complexity :
Improved By : aganjali10
Source
https://www.geeksforgeeks.org/maximum-distinct-lowercase-alphabets-two-uppercase/
1128
Chapter 199
Input: RRRKRRKKRRKKK
Output: 5
If we take R’s at indexes 0, 1, 2, 4, 5 and K’s at indexes 6, 7, 10, 11, 12
then we get a maximum subsequence of the form R^N K^N, where N = 5.
Input: KKKKRRRRK
Output: 1
If we take R at index 4( or 5 or 6 or 7) and K at index 8
then we get the desired subsequence with N = 1.
Approach:
1129
Chapter 199. Maximum length subsequence possible of the form R^N K^N
Java
1130
Chapter 199. Maximum length subsequence possible of the form R^N K^N
C#
1131
Chapter 199. Maximum length subsequence possible of the form R^N K^N
// Driver code
static public void Main(String []srgs)
{
String s = "RKRRRKKRRKKKKRR";
int n = find(s);
Console.WriteLine(n);
}
}
// This code is contributed
// by Arnab Kundu
Output:
Source
https://www.geeksforgeeks.org/maximum-length-subsequence-possible-of-the-form-rn-kn/
1132
Chapter 200
Method 1: Previously an approach having time complexity of O(n2 ) have been discussed
in this post.
Method 2 (Efficient Approach): The idea is to create a hash map having tuples in the
form (ele, len), where len denotes the length of the longest subsequence ending with the
element ele. Now, for each element arr[i] we can find the length of the values arr[i]-1, arr[i]
and arr[i]+1 in the hash table and consider the maximum among them. Let this maximum
1133
Chapter 200. Maximum length subsequence with difference between adjacent elements as
either 0 or 1 | Set 2
value be max. Now, the length of longest subsequence ending with arr[i] would be max+1.
Update this length along with the element arr[i] in the hash table. Finally, the element
having the maximum length in the hash table gives the maximum length subsequence.
1134
Chapter 200. Maximum length subsequence with difference between adjacent elements as
either 0 or 1 | Set 2
// update maximum length
if (maxLen < um[arr[i]])
maxLen = um[arr[i]];
}
// required maximum length subsequence
return maxLen;
}
// Driver program to test above
int main()
{
int arr[] = {2, 5, 6, 3, 7, 6, 5, 8};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum length subsequence = "
<< maxLenSub(arr, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/maximum-length-subsequence-difference-adjacent-elements-either-0-1-set-2/
1135
Chapter 201
Maximum number of characters between any two same character in a string - GeeksforGeeks
Given a string, find the maximum number of characters between any two same character in
the string. If no character repeats, print -1.
Approach 1 (Simple): Use two nested loops. The outer loop picks character from left to
right, the inner loop finds farthest occurrence and keeps track of maximum.
C++
1136
Chapter 201. Maximum number of characters between any two same character in a string
// same character
#include <bits/stdc++.h>
using namespace std;
int maximumChars(string& str)
{
int n = str.length();
int res = -1;
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
if (str[i] == str[j])
res = max(res, abs(j - i - 1));
return res;
}
// Driver code
int main()
{
string str = "abba";
cout << maximumChars(str);
return 0;
}
Java
1137
Chapter 201. Maximum number of characters between any two same character in a string
System.out.println(maximumChars(str));
}
}
// This code is contributed by vt_m.
C#
Output:
1138
Chapter 201. Maximum number of characters between any two same character in a string
C++
1139
Chapter 201. Maximum number of characters between any two same character in a string
return 0;
}
Java
1140
Chapter 201. Maximum number of characters between any two same character in a string
C#
1141
Chapter 201. Maximum number of characters between any two same character in a string
// Driver code
static public void Main ()
{
string str = "abba";
Console.WriteLine(maximumChars(str));
}
}
// This code is contributed by vt_m.
Output:
Source
https://www.geeksforgeeks.org/maximum-number-characters-two-character-string/
1142
Chapter 202
1143
Chapter 202. Maximum number of chocolates to be distributed equally among k students
an element of (sum[i] % k) and idx represents the element’s index of first occurrence
when array sum[] is being traversed from left to right. Now traverse sum[] from i = 0 to
n and follow the steps given below.
1144
Chapter 202. Maximum number of chocolates to be distributed equally among k students
// finding current remainder
curr_rem = sum[i] % k;
// if true then sum(0..i) is divisible
// by k
if (curr_rem == 0) {
// update 'maxSum'
if (maxSum < sum[i])
maxSum = sum[i];
}
// if value 'curr_rem' not present in 'um'
// then store it in 'um' with index of its
// first occurrence
else if (um.find(curr_rem) == um.end())
um[curr_rem] = i;
else
// if true, then update 'max'
if (maxSum < (sum[i] - sum[um[curr_rem]]))
maxSum = sum[i] - sum[um[curr_rem]];
}
// required maximum number of chocolates to be
// distributed equally among 'k' students
return (maxSum / k);
}
// Driver program to test above
int main()
{
int arr[] = { 2, 7, 6, 1, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout << "Maximum number of chocolates: "
<< maxNumOfChocolates(arr, n, k);
return 0;
}
Java
1145
Chapter 202. Maximum number of chocolates to be distributed equally among k students
1146
Chapter 202. Maximum number of chocolates to be distributed equally among k students
Python3
1147
Chapter 202. Maximum number of chocolates to be distributed equally among k students
maxSum = sm[i]
elif (not curr_rem in um) :
um[curr_rem] = i
elif (maxSum < (sm[i] - sm[um[curr_rem]])):
maxSum = sm[i] - sm[um[curr_rem]]
return maxSum//k
# Driver program to test above
arr = [ 2, 7, 6, 1, 4, 5 ]
n, k = len(arr), 3
print("Maximum number of chocolates: " +
str(maxNumOfChocolates(arr, n, k)))
# This code is contributed by Ansu Kumari
C#
// C# implementation to find
// the maximum number of
// chocolates to be distributed
// equally among k students
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the
// maximum number of
// chocolates to be distributed
// equally among k students
static int maxNumOfChocolates(int []arr,
int n, int k)
{
// Hash table
Dictionary <int, int> um =
new Dictionary<int, int>();
// 'sum[]' to store cumulative
// sum, where sum[i] =
// sum(arr[0]+..arr[i])
int[] sum = new int[n];
int curr_rem;
// To store sum of sub-array
// having maximum sum
int maxSum = 0;
1148
Chapter 202. Maximum number of chocolates to be distributed equally among k students
// Building up 'sum[]'
sum[0] = arr[0];
for (int i = 1; i < n; i++)
sum[i] = sum[i - 1] + arr[i];
// Traversing 'sum[]'
for (int i = 0; i < n; i++)
{
// Finding current
// remainder
curr_rem = sum[i] % k;
// If true then sum(0..i)
// is divisible by k
if (curr_rem == 0)
{
// update 'maxSum'
if (maxSum < sum[i])
maxSum = sum[i];
}
// If value 'curr_rem' not
// present in 'um' then store
// it in 'um' with index of
// its first occurrence
else if (!um.ContainsKey(curr_rem))
um.Add(curr_rem , i);
else
// If true, then
// update 'max'
if (maxSum < (sum[i] -
sum[um[curr_rem]]))
maxSum = sum[i] -
sum[um[curr_rem]];
}
// Required maximum number
// of chocolates to be
// distributed equally
// among 'k' students
return (maxSum / k);
}
// Driver Code
1149
Chapter 202. Maximum number of chocolates to be distributed equally among k students
Output :
Source
https://www.geeksforgeeks.org/maximum-number-chocolates-distributed-equally-among-k-students/
1150
Chapter 203
In the previous article, if there are more than one characters occurring the maximum number
of time, then any of the characters is returned. In this post, the lexicographically smallest
character of all the characters is returned.
Approach: Declare a freq[26] array which is used as a hash table to store the frequencies of
each character in the input string. Iterate in the string and increase the count of freq[s[i]] for
every character.T raverse the freq[] array from left to right and keep track of the character
having the maximum frequency so far. The value at freq[i] represents the frequency of
character (i + ‘a’).
Below is the implementation of the above approach:
1151
Chapter 203. Maximum occurring character in an input string | Set-2
Output:
1152
Chapter 203. Maximum occurring character in an input string | Set-2
Source
https://www.geeksforgeeks.org/maximum-occurring-character-in-an-input-string-set-2/
1153
Chapter 204
Before solving this question we have to take care of some given conditions and they are
listed as:
• While building up the subsets, take care that no subset should contain repetitive
elements. And for this we can conclude that all such elements whose frequency are
1154
Chapter 204. Maximum possible difference of two subsets of an array
2, going to be part of both subsets and hence overall they don’t have any impact on
difference of subset sum. So, we can easily ignore them.
• For making the difference of sum of elements of both subset maximum we have to make
subset in such a way that all positive elements belongs to one subset and negative ones
to other subset.
if isSingleOccurance == true
if (arr[i] > 0)
SubsetSum_1 += arr[i];
else
SubsetSum_2 += arr[i];
return abs(SubsetSum_1 - SubsetSum2)
C++
1155
Chapter 204. Maximum possible difference of two subsets of an array
break;
}
}
if (isSingleOccurance) {
if (arr[i] > 0)
SubsetSum_1 += arr[i];
else
SubsetSum_2 += arr[i];
}
}
return abs(SubsetSum_1 - SubsetSum_2);
}
// driver program
int main()
{
int arr[] = { 4, 2, -3, 3, -2, -2, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum Difference = " << maxDiff(arr, n);
return 0;
}
Java
1156
Chapter 204. Maximum possible difference of two subsets of an array
}
}
if (isSingleOccurance)
{
if (arr[i] > 0)
SubsetSum_1 += arr[i];
else
SubsetSum_2 += arr[i];
}
}
return Math.abs(SubsetSum_1 - SubsetSum_2);
}
// driver program
static public void main (String[] args)
{
int []arr = { 4, 2, -3, 3, -2, -2, 8 };
int n = arr.length;
System.out.println("Maximum Difference = "
+ maxDiff(arr, n));
}
}
// This code is contributed by vt_m.
Python3
1157
Chapter 204. Maximum possible difference of two subsets of an array
arr[i] = arr[j] = 0
break
if (isSingleOccurance == True) :
if (arr[i] > 0) :
SubsetSum_1 += arr[i]
else :
SubsetSum_2 += arr[i]
return abs(SubsetSum_1 - SubsetSum_2)
# Driver Code
arr = [4, 2, -3, 3, -2, -2, 8]
n = len(arr)
print ("Maximum Difference = {}"
. format(maxDiff(arr, n)))
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
1158
Chapter 204. Maximum possible difference of two subsets of an array
}
if (isSingleOccurance)
{
if (arr[i] > 0)
SubsetSum_1 += arr[i];
else
SubsetSum_2 += arr[i];
}
}
return Math.Abs(SubsetSum_1 - SubsetSum_2);
}
// driver program
static public void Main ()
{
int []arr = { 4, 2, -3, 3, -2, -2, 8 };
int n = arr.Length;
Console.WriteLine("Maximum Difference = "
+ maxDiff(arr, n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP find maximum difference
// of subset sum
// function for maximum subset diff
function maxDiff($arr, $n)
{
$SubsetSum_1 = 0;
$SubsetSum_2 = 0;
for ($i = 0; $i <= $n - 1; $i++)
{
$isSingleOccurance = true;
for ($j = $i + 1; $j <= $n - 1; $j++)
{
// if frequency of any element is two
// make both equal to zero
if ($arr[$i] == $arr[$j])
{
1159
Chapter 204. Maximum possible difference of two subsets of an array
$isSingleOccurance = false;
$arr[$i] = $arr[$j] = 0;
break;
}
}
if ($isSingleOccurance)
{
if ($arr[$i] > 0)
$SubsetSum_1 += $arr[$i];
else
$SubsetSum_2 += $arr[$i];
}
}
return abs($SubsetSum_1 - $SubsetSum_2);
}
// Driver Code
$arr = array(4, 2, -3, 3, -2, -2, 8);
$n = sizeof($arr);
echo "Maximum Difference = " , maxDiff($arr, $n);
// This code is contributed by nitin mittal
?>
Output:
Maximum Difference = 20
1160
Chapter 204. Maximum possible difference of two subsets of an array
C++
Java
1161
Chapter 204. Maximum possible difference of two subsets of an array
// function for maximum subset diff
static int maxDiff(int []arr, int n)
{
int result = 0;
// sort the array
Arrays.sort(arr);
// calculate the result
for (int i = 0; i < n - 1; i++)
{
if (arr[i] != arr[i + 1])
result += Math.abs(arr[i]);
else
i++;
}
// check for last element
if (arr[n - 2] != arr[n - 1])
result += Math.abs(arr[n - 1]);
// return result
return result;
}
// driver program
static public void main (String[] args)
{
int[] arr = { 4, 2, -3, 3, -2, -2, 8 };
int n = arr.length;
System.out.println("Maximum Difference = "
+ maxDiff(arr, n));
}
}
// This code is contributed by vt_m.
C#
1162
Chapter 204. Maximum possible difference of two subsets of an array
PHP
<?php
// PHP find maximum difference of subset sum
// function for maximum subset diff
function maxDiff( $arr, $n)
{
$result = 0;
// sort the array
1163
Chapter 204. Maximum possible difference of two subsets of an array
sort($arr);
// calculate the result
for ( $i = 0; $i < $n - 1; $i++)
{
if ($arr[$i] != $arr[$i + 1])
$result += abs($arr[$i]);
else
$i++;
}
// check for last element
if ($arr[$n - 2] != $arr[$n - 1])
$result += abs($arr[$n - 1]);
// return result
return $result;
}
// Driver Code
$arr = array( 4, 2, -3, 3, -2, -2, 8 );
$n = count($arr);
echo "Maximum Difference = "
, maxDiff($arr, $n);
// This code is contributed by anuj_67.
?>
Output:
Maximum Difference = 20
1164
Chapter 204. Maximum possible difference of two subsets of an array
#include <bits/stdc++.h>
using namespace std;
// function for maximum subset diff
int maxDiff(int arr[], int n)
{
unordered_map<int, int> hashPositive;
unordered_map<int, int> hashNegative;
int SubsetSum_1 = 0, SubsetSum_2 = 0;
// construct hash for positive elements
for (int i = 0; i <= n - 1; i++)
if (arr[i] > 0)
hashPositive[arr[i]]++;
// calculate subset sum for positive elements
for (int i = 0; i <= n - 1; i++)
if (arr[i] > 0 && hashPositive[arr[i]] == 1)
SubsetSum_1 += arr[i];
// construct hash for negative elements
for (int i = 0; i <= n - 1; i++)
if (arr[i] < 0)
hashNegative[abs(arr[i])]++;
// calculate subset sum for negative elements
for (int i = 0; i <= n - 1; i++)
if (arr[i] < 0 &&
hashNegative[abs(arr[i])] == 1)
SubsetSum_2 += arr[i];
return abs(SubsetSum_1 - SubsetSum_2);
}
// driver program
int main()
{
int arr[] = { 4, 2, -3, 3, -2, -2, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum Difference = " << maxDiff(arr, n);
return 0;
}
Output:
Maximum Difference = 20
1165
Chapter 204. Maximum possible difference of two subsets of an array
Source
https://www.geeksforgeeks.org/maximum-possible-difference-two-subsets-array/
1166
Chapter 205
Maximum possible sum of a window in an array such that elements of same window in other
array are unique - GeeksforGeeks
Given two arrays A and B of equal number of elements. Task is to find the maximum sum
possible of a window in array B such that elements of same window in A[] are unique.
Examples:
Input : A = [0, 1, 2, 3, 0, 1, 4]
B = [9, 8, 1, 2, 3, 4, 5]
Output : sum = 20
The maximum sum possible in B[] such that
all corresponding elements in A[] are unique
is (9+8+1+2) = 20.
Input : A = [0, 1, 2, 0, 2]
B = [5, 6, 7, 8, 2]
Output :sum = 21
A simple solution is to consider all subarrays of B[]. For every subarray, check if elements
same subarray in A[] are distinct or not. If distinct, then compare sum with result and
update result.
Time complexity of this solution is O(n2 )
An efficient solution is to use hashing.
1167
Chapter 205. Maximum possible sum of a window in an array such that elements of same
window in other array are unique
C++
1168
Chapter 205. Maximum possible sum of a window in an array such that elements of same
window in other array are unique
mp.insert(A[i]);
curr_sum += B[i];
// Update result if current
// sum is more.
result = max(result, curr_sum);
}
return result;
}
// Driver code
int main()
{
int A[] = { 0, 1, 2, 3, 0, 1, 4 };
int B[] = { 9, 8, 1, 2, 3, 4, 5 };
int n = sizeof(A)/sizeof(A[0]);
cout << returnMaxSum(A, B, n);
return 0;
}
Java
1169
Chapter 205. Maximum possible sum of a window in an array such that elements of same
window in other array are unique
{
// Remove all duplicate
// instances of A[i] in
// current window.
while (mp.contains(A[i]))
{
mp.remove(A[curr_begin]);
curr_sum -= B[curr_begin];
curr_begin++;
}
// Add current instance of A[i]
// to map and to current sum.
mp.add(A[i]);
curr_sum += B[i];
// Update result if current
// sum is more.
result = Integer.max(result, curr_sum);
}
return result;
}
//Driver Code to test above method
public static void main(String[] args)
{
int A[] = { 0, 1, 2, 3, 0, 1, 4 };
int B[] = { 9, 8, 1, 2, 3, 4, 5 };
int n = A.length;
System.out.println(returnMaxSum(A, B, n));
}
}
// This code is contributed by Sumit Ghosh
Output:
20
Time complexity of this solution is O(n). Note that every element of array is inserted and
removed at most once from array.
Source
https://www.geeksforgeeks.org/maximum-possible-sum-window-array-elements-window-array-unique/
1170
Chapter 206
Naive Method:
The idea is to try all index sums from 0 to sum of sizes. For every sum, check if there are
pairs with given sum. Once we find one or more pairs, we print them and return.
#include <bits/stdc++.h>
using namespace std;
1171
Chapter 206. Minimum Index Sum for Common Elements of Two Lists
// Function to print common strings with minimum index sum
void find(vector<string> list1, vector<string> list2)
{
vector<string> res; // resultant list
int max_possible_sum = list1.size() + list2.size() - 2;
// iterating over sum in ascending order
for (int sum = 0; sum <= max_possible_sum ; sum++)
{
// iterating over one list and check index
// (Corresponding to given sum) in other list
for (int i = 0; i <= sum; i++)
// put common strings in resultant list
if (i < list1.size() &&
(sum - i) < list2.size() &&
list1[i] == list2[sum - i])
res.push_back(list1[i]);
// if common string found then break as we are
// considering index sums in increasing order.
if (res.size() > 0)
break;
}
// print the resultant list
for (int i = 0; i < res.size(); i++)
cout << res[i] << " ";
}
// Driver code
int main()
{
// Creating list1
vector<string> list1;
list1.push_back("GeeksforGeeks");
list1.push_back("Udemy");
list1.push_back("Coursera");
list1.push_back("edX");
// Creating list2
vector<string> list2;
list2.push_back("Codecademy");
list2.push_back("Khan Academy");
list2.push_back("GeeksforGeeks");
find(list1, list2);
1172
Chapter 206. Minimum Index Sum for Common Elements of Two Lists
return 0;
}
Output:
GeeksforGeeks
Time Complexity : O((l1 +l2 )2 *x), where l1 and l2 are the lengths of list1 and list2
respectively and x refers to string length.
Auxiliary Space : O(l*x), where x refers to length of resultant list and l is length of
maximum size word.
Using Hash:
1. Traverse over the list1 and create an entry for index each element of list1 in a Hash
Table.
2. Traverse over list2 and for every element, check if the same element already exists as
a key in the map. If so, it means that the element exists in both the lists.
3. Find out the sum of indices corresponding to common element in the two lists. If this
sum is lesser than the minimum sum obtained till now, update the resultant list.
4. If the sum is equal to the minimum sum obtained till now, put an extra entry corre-
sponding to the element in list2 in the resultant list.
Source
https://www.geeksforgeeks.org/minimum-index-sum-common-elements-two-lists/
1173
Chapter 207
Input : arr[] = {1 4 5 3 7}
Output : 1
We need to replace 7 with 2 to satisfy
condition hence minimum changes is 1.
Input : arr[] = {8 55 22 1 3 22 4 5}
Output :3
We insert all elements in a hash table. We then iterate from 1 to N and check whether the
element in present in hash table. If it is not present than increment count. Final value of
count will be the minimum changes required.
C++
1174
Chapter 207. Minimum array element changes to make its elements 1 to N
Python 3
# Count minimum changes to
# make array from 1 to n
def countChanges(arr, n):
# it will contain all initial
# elements of array for log(n)
# complexity searching
s = []
# Inserting all elements in a list
for i in range(n):
s.append(arr[i])
# Finding elements to be changed
count = 0
for i in range(1, n + 1) :
if i not in s:
count += 1
return count
# Driver Code
if __name__ == “__main__”:
1175
Chapter 207. Minimum array element changes to make its elements 1 to N
Source
https://www.geeksforgeeks.org/minimum-array-element-changes-to-make-its-elements-1-to-n/
1176
Chapter 208
Input : "geks"
Output : cost: 4
Explanation:
appending 'g' cost 1, string "g"
appending 'e' cost 1, string "ge"
appending 'k' cost 1, string "gek"
appending 's' cost 1, string "geks"
Hence, Total cost to construct "geks" is 4
Input : "abab"
Output : cost: 2
Explanation:
Appending 'a' cost 1, string "a"
Appending 'b' cost 1, string "ab"
Appending "ab" cost nothing as it
is substring of intermediate.
Hence, Total cost to construct "abab" is 2
1177
Chapter 208. Minimum cost to construct a string
which is also a sub-string in the intermediate string, if there is then append it at no cost
and if not then append it at the cost of 1 unit per character.
In the above example when intermediate string was “ab” and we need to construct “abab”
then remaining string was “ab”. Hence there is a sub-string in remaining string which is
also a sub-string of intermediate string (i.e. “ab”) and therefore cost us nothing.
Better Approach: We will use hashing technique, to maintain that whether we have seen
a character or not. If we have seen the character, then there is no cost to append the
character and if not, then it cost us 1 unit.
Now in this approach we take one character at a time and not a string. This is because if
“ab” is substring of “abab”, so is ‘a’ and ‘b’ alone and hence make no difference.
This also leads us to the conclusion that the cost to construct a string is never more than
26 in case the string contains all the alphabets (a-z).
1178
Chapter 208. Minimum cost to construct a string
Output:
Source
https://www.geeksforgeeks.org/minimum-cost-construct-string/
1179
Chapter 209
In this problem we need to minimize the delete operations. The approach is simple, we
count frequency of each element in array, then find the frequency of most frequent element
in count array. Let this frequence be max_freq. To get the minimum number of elements
to be deleted from array calculate n – max_freq where n is number of elements in given
array.
1180
Chapter 209. Minimum delete operations to make all elements of array same
Output:
Source
https://www.geeksforgeeks.org/minimum-delete-operations-make-elements-array/
1181
Chapter 210
If we observe carefully, our problem reduces to calculating characters with odds and even
counts. Below are the possible cases,
1. If the characters present in the string have only even counts then the answer will be
1 as we can rearrange the entire string to form a palindrome.
2. If there is only one character with odd count, then also the answer will be 1 as we can
rearrange the entire string to form a palindrome.
1182
Chapter 210. Minimum equal palindromic cuts with rearrangements allowed
3. If there is more than one character with odd count, then we will create two separate
list of characters – one for odd characters and one for even characters. Now, if we
notice that if a character has odd count then if we subtract 1 from it, the count will
become even. So we will insert the element with odd counts only once in the odd list.
We will insert the elements with even counts (evenCount/2) times, i.e. half of their
count in the even list. Now our problem is to uniformly distribute the even count
elements among odd count elements to form palindromes of equal length. Suppose the
list of even count characters is even and odd count characters is odd. If even.size() is
divisible by odd.size() our answer will be odd.size() otherwise we will transfer elements
from even list to odd list until even.size() is divisible by odd.size().
1183
Chapter 210. Minimum equal palindromic cuts with rearrangements allowed
}
}
for (auto itr = m.begin(); itr!=m.end(); itr++)
{
if (itr->second%2==0)
{
// add even count characters half of their
// count to the even list so that we can
// simply repeat the even list on both
// sides of an odd char to generate a
// palindrome
for (int i=0;i<(itr->second)/2;i++)
even.push_back(itr->first);
}
}
// if there is no odd count characters or
// only 1 odd count character, return 1
if (odd.size() <= 1)
return 1;
else
{
// Move some characters from even list over
// to odd list to make palindrome work
while (odd.size() > 0 && even.size() > 0 &&
even.size() % odd.size() != 0)
{
odd.push_back(even.back());
odd.push_back(even.back());
even.pop_back();
}
return odd.size();
}
}
// driver code
int main()
{
string str = "aabaac";
cout << minPalindromeCuts(str);
return 0;
}
Output:
1184
Chapter 210. Minimum equal palindromic cuts with rearrangements allowed
Source
https://www.geeksforgeeks.org/minimum-equal-palindromic-cuts-with-rearrangements-allowed/
1185
Chapter 211
Input : geeksforgeeks
Output : 2
geeksforgeeks can be changed as:
geeksroforskeeg
geeksorfroskeeg
and many more
Input : aabbc
Output : 0
aabbc can be changed as:
abcba
bacab
A palindromic string can have one odd character only when length of string is odd otherwise
all characters occur even number of times. So, we have to find characters which occur odd
times in a string.
The idea is to count occurrence of each character in a string. As palindromic string can
have one character which occur odd times so number of insertion will be one less then count
1186
Chapter 211. Minimum insertions to form a palindrome with permutations allowed
of characters which occur odd times. And if string is already palindrome, we do not need
to add any character so result will be 0.
C++
1187
Chapter 211. Minimum insertions to form a palindrome with permutations allowed
return 0;
}
Java
1188
Chapter 211. Minimum insertions to form a palindrome with permutations allowed
}
}
C#
1189
Chapter 211. Minimum insertions to form a palindrome with permutations allowed
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/minimum-insertions-to-form-a-palindrome-with-permutations-allowed/
1190
Chapter 212
*
We insert locations of all obstacles in a hash table. We also find maximum value of obstacle.
Then we try all possible jump sizes from 1 to maximum. If any jump size leads to a obstacle,
we do not consider that jump.
1191
Chapter 212. Minimum length of jumps to avoid given array of obstacles
public class obstacle {
static int avoidObstacles(int[] obs)
{
// Insert all array elements in a hash table
// and find the maximum value in the array
HashSet<Integer> hs = new HashSet<Integer>();
int max = obs[0];
for (int i=0; i<obs.length; i++)
{
hs.add(obs[i]);
max = Math.max(max, obs[i]);
}
// checking for every possible length which
// yield us solution
for (int i = 1; i <= max; i++) {
int j;
for (j = i; j <= max; j = j + i) {
// if there is obstacle, break the loop.
if (hs.contains(j))
break;
}
// If above loop did not break
if (j > max)
return i;
}
return max+1;
}
// Driver Code
public static void main(String[] args)
{
int a[] = new int[] { 5, 3, 6, 7, 9 };
int b = avoidObstacles(a);
System.out.println(b);
}
}
Output:
1192
Chapter 212. Minimum length of jumps to avoid given array of obstacles
Source
https://www.geeksforgeeks.org/minimum-length-of-jumps-to-avoid-given-array-of-obstacles/
1193
Chapter 213
Input : arr[] = { 2, 2, 1, 3, 3, 3}
m = 3
Output : 1
Remove 1 and both 2's.So, only 3 will be
left that's why distinct id is 1.
Input : arr[] = { 2, 4, 1, 5, 3, 5, 1, 3}
m = 2
Output : 3
Remove 2 and 4 completely. So, remaining ids
are 1, 3 and 5 i.e. 3
1194
Chapter 213. Minimum number of distinct elements after removing m items
1195
Chapter 213. Minimum number of distinct elements after removing m items
cout << distinctIds(arr, n, m);
return 0;
}
Java
1196
Chapter 213. Minimum number of distinct elements after removing m items
Output:
Source
https://www.geeksforgeeks.org/minimum-number-of-distinct-elements-after-removing-m-items/
1197
Chapter 214
We can solve this problem by observing the pattern of movement when visiting the stops.
If we want to take the shortest path from one point to another point then we will move in
either one or max two directions i.e. it is always possible to reach the other point following
maximum two directions and if more than two directions are used then that path won’t be
shortest, for example, path LLURD can be replaced with LLL only, so to find minimum
number of stops in the path, we will loop over the characters of the path and maintain a
map of directions taken till now. If at any index we found both ‘L’ as well as ‘R’ or we
found both ‘U’ as well as ‘D’ then there must be a stop at current index, so we will increase
the stop count by one and we will clear the map for next segment.
Total time complexity of the solution will be O(N)
1198
Chapter 214. Minimum number of stops from given path
1199
Chapter 214. Minimum number of stops from given path
Output:
Source
https://www.geeksforgeeks.org/minimum-number-stops-given-path/
1200
Chapter 215
We basically need to find the most frequent element in the array. The result is equal to the
frequency of the most frequent element.
A simple solution is to run two nested loops to count frequency of every element and
return the frequency of the most frequent element. Time complexity of this solution is
O(n2 ).
A better solution is to first sort the array and then start count number of repetitions of
elements in an iterative manner as all repetition of any number lie beside the number itself.
By this method you can find the maximum frequency or repetition by simply traversing
the sorted array. This approach will cost O(nlogn) time complexity
1201
Chapter 215. Minimum number of subsets with distinct elements
C++
1202
Chapter 215. Minimum number of subsets with distinct elements
Java
1203
Chapter 215. Minimum number of subsets with distinct elements
}
/* This code is contributed by Sagar Shukla */
Python3
1204
Chapter 215. Minimum number of subsets with distinct elements
C#
1205
Chapter 215. Minimum number of subsets with distinct elements
}
}
/* This code is contributed by Vt_m */
Output :
1206
Chapter 215. Minimum number of subsets with distinct elements
Output :
Source
https://www.geeksforgeeks.org/minimum-number-subsets-distinct-elements/
1207
Chapter 216
For making all elements equal you can select a target value and then you can make all
elements equal to that. Now, for converting a single element to target value you can perform
a single operation only once. In this manner you can achieve your task in maximum of n
operations but you have to minimize this number of operation and for this your selection of
target is very important because if you select a target whose frequency in array is x then
you have to perform only n-x more operations as you have already x elements equal to your
target value. So, finally our task is reduced to finding element with maximum frequency.
This can be achieved by different means such as iterative method in O(n^2), sorting in
1208
Chapter 216. Minimum operation to make all elements equal in array
C++
Java
1209
Chapter 216. Minimum operation to make all elements equal in array
{
// Insert all elements in hash.
HashMap<Integer, Integer> hash = new HashMap<Integer,
Integer>();
for (int i=0; i<n; i++)
if(hash.containsKey(arr[i]))
hash.put(arr[i], hash.get(arr[i])+1);
else hash.put(arr[i], 1);
// find the max frequency
int max_count = 0;
Set<Integer> s = hash.keySet();
for (int i : s)
if (max_count < hash.get(i))
max_count = hash.get(i);
// return result
return (n - max_count);
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {1, 5, 2, 1, 3, 2, 1};
int n = arr.length;
System.out.print(minOperation(arr, n));
}
}
// This code is contributed by Arnav Kr. Mandal.
Output:
Source
https://www.geeksforgeeks.org/minimum-operation-make-elements-equal-array/
1210
Chapter 217
A simple solution is to run two loops. The outer loop picks all elements one by one. The
inner loop finds frequency of the picked element and compares with the maximum so far.
Time complexity of this solution is O(n2 )
A better solution is to do sorting. We first sort the array, then linearly traverse the array.
C++
1211
Chapter 217. Most frequent element in an array
Java
1212
Chapter 217. Most frequent element in an array
Arrays.sort(arr);
// find the max frequency using linear
// traversal
int max_count = 1, res = arr[0];
int curr_count = 1;
for (int i = 1; i < n; i++)
{
if (arr[i] == arr[i - 1])
curr_count++;
else
{
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is most frequent
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[n - 1];
}
return res;
}
// Driver program
public static void main (String[] args) {
int arr[] = {1, 5, 2, 1, 3, 2, 1};
int n = arr.length;
System.out.println(mostFrequent(arr,n));
}
}
// This code is contributed by Akash Singh.
Python3
1213
Chapter 217. Most frequent element in an array
C#
1214
Chapter 217. Most frequent element in an array
PHP
1215
Chapter 217. Most frequent element in an array
<?php
// PHP program to find the
// most frequent element
// in an array.
function mostFrequent( $arr, $n)
{
// Sort the array
sort($arr);
sort($arr , $n);
// find the max frequency
// using linear traversal
$max_count = 1;
$res = $arr[0];
$curr_count = 1;
for ($i = 1; $i < $n; $i++)
{
if ($arr[$i] == $arr[$i - 1])
$curr_count++;
else
{
if ($curr_count > $max_count)
{
$max_count = $curr_count;
$res = $arr[$i - 1];
}
$curr_count = 1;
}
}
// If last element
// is most frequent
if ($curr_count > $max_count)
{
$max_count = $curr_count;
$res = $arr[$n - 1];
}
return $res;
}
// Driver Code
{
$arr = array(1, 5, 2, 1, 3, 2, 1);
$n = sizeof($arr) / sizeof($arr[0]);
echo mostFrequent($arr, $n);
1216
Chapter 217. Most frequent element in an array
return 0;
}
// This code is contributed by nitin mittal
?>
Output :
C++
1217
Chapter 217. Most frequent element in an array
int arr[] = { 1, 5, 2, 1, 3, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << mostFrequent(arr, n);
return 0;
}
Java
1218
Chapter 217. Most frequent element in an array
}
return res;
}
// Driver code
public static void main (String[] args) {
int arr[] = {1, 5, 2, 1, 3, 2, 1};
int n = arr.length;
System.out.println(mostFrequent(arr, n));
}
}
// This code is contributed by Akash Singh.
C#
1219
Chapter 217. Most frequent element in an array
foreach (KeyValuePair<int,
int> pair in hp)
{
if (min_count < pair.Value)
{
res = pair.Key;
min_count = pair.Value;
}
}
return res;
}
// Driver code
static void Main ()
{
int []arr = new int[]{1, 5, 2,
1, 3, 2, 1};
int n = arr.Length;
Console.Write(mostFrequent(arr, n));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output:
Source
https://www.geeksforgeeks.org/frequent-element-array/
1220
Chapter 218
A simple solution is to run two loops and count occurrences of every word. Time com-
plexity of this solution is O(n * n * MAX_WORD_LEN).
An efficient solution is to use Trie data structure. The idea is simple first we will insert
in trie. In trie, we keep counts of words ending at a node. We do preorder traversal and
compare count present at each node and find the maximum occurring word
1221
Chapter 218. Most frequent word in an array of strings
string key;
int cnt;
unordered_map<char, Trie*> map;
};
/* Function to return a new Trie node */
Trie* getNewTrieNode()
{
Trie* node = new Trie;
node->cnt = 0;
return node;
}
/* function to insert a string */
void insert(Trie*& root, string &str)
{
// start from root node
Trie* temp = root;
for (int i=0; i<str.length(); i++) {
char x = str[i];
/*a new node if path doesn't exists*/
if (temp->map.find(x) == temp->map.end())
temp->map[x] = getNewTrieNode();
// go to next node
temp = temp->map[x];
}
// store key and its count in leaf nodes
temp->key = str;
temp->cnt += 1;
}
/* function for preorder traversal */
bool preorder(Trie* temp, int& maxcnt, string& key)
{
if (temp == NULL)
return false;
for (auto it : temp->map) {
/*leaf node will have non-zero count*/
if (maxcnt < it.second->cnt) {
key = it.second->key;
maxcnt = it.second->cnt;
1222
Chapter 218. Most frequent word in an array of strings
}
// recurse for current node children
preorder(it.second, maxcnt, key);
}
}
void mostFrequentWord(string arr[], int n)
{
// Insert all words in a Trie
Trie* root = getNewTrieNode();
for (int i = 0; i < n; i++)
insert(root, arr[i]);
// Do preorder traversal to find the
// most frequent word
string key;
int cnt = 0;
preorder(root, cnt, key);
cout << "The word that occurs most is : "
<< key << endl;
cout << "No of times: " << cnt << endl;
}
// Driver code
int main()
{
// given set of keys
string arr[] = {"geeks", "for", "geeks", "a",
"portal", "to", "learn", "can", "be",
"computer", "science", "zoom", "yup",
"fire", "in", "be", "data", "geeks"};
int n = sizeof(arr) / sizeof(arr[0]);
mostFrequentWord(arr, n);
return 0;
}
Output:
1223
Chapter 218. Most frequent word in an array of strings
Another efficient solution is to use hashing. Please refer Find winner of an election
where votes are represented as candidate names for details.
Source
https://www.geeksforgeeks.org/frequent-word-array-strings/
1224
Chapter 219
Since the elements are as large as 10^9 we cannot use direct index table.
One solution is to sort both multisets and compare them one by one.
1225
Chapter 219. Multiset Equivalence Problem
Output:
No
A better solution is to use hashing. We create two empty hash tables (implemented using
unordered_map in C++). We first insert all items of first multimap in first table and all
items of second multiset in second table. Now we check if both hash tables contain same
items and frequencies or not.
1226
Chapter 219. Multiset Equivalence Problem
// Now we check if both unordered_maps
// are same of not.
for (auto x : m1) {
if (m2.find(x.first) == m2.end() ||
m2[x.first] != x.second)
return false;
}
return true;
}
// Driver code
int main()
{
vector<int> a({ 7, 7, 5 }), b({ 7, 7, 5 });
if (areSame(a, b))
cout << "Yes\n";
else
cout << "No\n";
return 0;
}
Output:
Yes
Time complexity : O(n) under the assumption that unordered_map find() and insert()
operations work in O(1) time.
Source
https://www.geeksforgeeks.org/multiset-equivalence-problem/
1227
Chapter 220
1228
Chapter 220. Next Greater Frequency Element
Naive approach:
A simple hashing technique is to use values as index is be used to store frequency of each
element. Create a list suppose to store frequency of each number in the array. (Single
traversal is required). Now use two loops.
The outer loop picks all the elements one by one.
The inner loop looks for the first element whose frequency is greater than the frequency of
current element.
If a greater frequency element is found then that element is printed, otherwise -1 is printed.
Time complexity : O(n*n)
Efficient approach:
We can use hashing and stack data structure to efficiently solve for many cases. A simple
hashing technique is to use values as index and frequency of each element as value. We use
stack data structure to store position of elements in the array.
1229
Chapter 220. Next Greater Frequency Element
print("List empty")
return []
# stack data structure to store the position
# of array element
stack = [0]*n
# freq is a dictionary which maintains the
# frequency of each element
freq = {}
for i in a:
freq[a[i]] = 0
for i in a:
freq[a[i]] += 1
# res to store the value of next greater
# frequency element for each element
res = [0]*n
# initialize top of stack to -1
top = -1
# push the first position of array in the stack
top += 1
stack[top] = 0
# now iterate for the rest of elements
for i in range(1, n):
''' If the frequency of the element which is
pointed by the top of stack is greater
than frequency of the current element
then push the current position i in stack'''
if (freq[a[stack[top]]] > freq[a[i]]):
top += 1
stack[top] = i
else:
''' If the frequency of the element which
is pointed by the top of stack is less
than frequency of the current element, then
pop the stack and continuing popping until
the above condition is true while the stack
is not empty'''
while (top>-1 and freq[a[stack[top]]] < freq[a[i]]):
res[stack[top]] = a[i]
top -= 1
1230
Chapter 220. Next Greater Frequency Element
# now push the current element
top+=1
stack[top] = i
'''After iterating over the loop, the remaining
position of elements in stack do not have the
next greater element, so print -1 for them'''
while (top > -1):
res[stack[top]] = -1
top -= 1
# return the res list containing next
# greater frequency element
return res
# Driver program to test the function
print(NFG([1,1,2,3,4,2,1],7))
Output:
Source
https://www.geeksforgeeks.org/next-greater-frequency-element/
1231
Chapter 221
Non-Repeating Element
Input : -1 2 -1 3 2
Output : 3
Explanation : The first number that does not
repeat is : 3
Input : 9 4 9 6 7 4
Output : 6
A Simple Solution is to use two loops. The outer loop picks elements one by one and
inner loop checks if the element is present more than once or not.
C++
1232
Chapter 221. Non-Repeating Element
return arr[i];
}
return -1;
}
// Driver code
int main()
{
int arr[] = { 9, 4, 9, 6, 7, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << firstNonRepeating(arr, n);
return 0;
}
Java
Python3
1233
Chapter 221. Non-Repeating Element
C#
1234
Chapter 221. Non-Repeating Element
int n = arr.Length;
Console.Write(firstNonRepeating(arr, n));
}
}
// This code is contributed by Anant Agarwal.
PHP
<?php
// Simple PHP program to find first non-
// repeating element.
function firstNonRepeating($arr, $n)
{
for ($i = 0; $i < $n; $i++)
{
$j;
for ($j = 0; $j< $n; $j++)
if ($i != $j && $arr[$i] == $arr[$j])
break;
if ($j == $n)
return $arr[$i];
}
return -1;
}
// Driver code
$arr = array(9, 4, 9, 6, 7, 4);
$n = sizeof($arr) ;
echo firstNonRepeating($arr, $n);
// This code is contributed by ajit
?>
Output:
1235
Chapter 221. Non-Repeating Element
Output:
1236
Chapter 221. Non-Repeating Element
Output:
7 6
Improved By : jit_t
Source
https://www.geeksforgeeks.org/non-repeating-element/
1237
Chapter 222
1238
Chapter 222. Non-overlapping sum of two sets
Output:
39
Source
https://www.geeksforgeeks.org/overlapping-sum-two-array/
1239
Chapter 223
Number of Counterclockwise
shifts to make a string
palindrome
Naive Approach: A naive approach is to one by one shift character of the given string
counter-clockwise cyclically and check if the string is palindrome or not.
Better Approach: A better approach is to append the string with itself and iterate from
the first character to the last character of the given string. The substring from i to i+n
(where i is in range [0,n-1]) in the appended string will be the string obtained after every
1240
Chapter 223. Number of Counterclockwise shifts to make a string palindrome
counterclockwise shift. Check for the substring if it is palindrome or not. The number of
shift operations will be i.
Below is the implementation of above approach:
1241
Chapter 223. Number of Counterclockwise shifts to make a string palindrome
// Check if current shifted string
// is palindrome or not
if (isPalindrome(str, left, right))
break;
// If string is not palindrome
// then increase count of number
// of shifts by 1.
cnt++;
left++;
right++;
}
return cnt;
}
// Driver code.
int main()
{
string str = "bccbbaab";
cout << CyclicShifts(str);
return 0;
}
Output:
Iterate for all the substrings and check for if it is a palindrome or not using the hash function
stated above and the cumulative hash technique.
1242
Chapter 223. Number of Counterclockwise shifts to make a string palindrome
1243
Chapter 223. Number of Counterclockwise shifts to make a string palindrome
// Hash value of string str[0..i] is stored in
// preval[i].
for (i = 1; i <= 2 * n; i++) {
preval[i] = ((preval[i - 1] * 31) % mod +
(str[i - 1] - 'a')) % mod;
}
// Hash value of string str[i..n-1] is stored
// in suffval[i].
for (i = 2 * n; i > 0; i--) {
suffval[i] = ((suffval[i + 1] * 31) % mod +
(str[i - 1] - 'a')) % mod;
}
// Characters in string str[0..i] is present
// at position [(n-1-i)..(n-1)] in reversed
// string. If hash value of both are same
// then string is palindrome else not.
for (i = 1; i <= n; i++) {
// Hash value of shifted string starting at
// index i and ending at index i+n-1.
val1 = (preval[i + n - 1] -
((po[n] * preval[i - 1]) % mod)) % mod;
if (val1 < 0)
val1 += mod;
// Hash value of corresponding string when
// reversed starting at index i+n-1 and
// ending at index i.
val2 = (suffval[i] - ((po[n] * suffval[i + n])
% mod)) % mod;
if (val2 < 0)
val2 += mod;
// If both hash value are same then current
// string str[i..(i+n-1)] is palindrome.
// Else increase the shift count.
if (val1 != val2)
cnt++;
else
break;
}
return cnt;
}
1244
Chapter 223. Number of Counterclockwise shifts to make a string palindrome
// Driver code.
int main()
{
string str = "bccbbaab";
cout << CyclicShifts(str);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-of-counterclockwise-shifts-to-make-a-string-palindrome/
1245
Chapter 224
Number of GP (Geometric
Progression) subsequences of
size 3
A naive approach is to use three nested for loops and check for every subsequence with
length 3 and keep a count of the subsequences. The complexity is O(n3 ).
An efficient approach is to solve the problem for fixed middle element of progression. This
means that if we fix element a[i] as middle, then it must be multiple of r, and a[i]/r and a[i]*r
must be present. We count number of occurrences of a[i]/r and a[i]*r and then multiply the
counts. To do this, we can use concept of hashing where we store the count of all possible
1246
Chapter 224. Number of GP (Geometric Progression) subsequences of size 3
elements in two hash maps, one indicating the number of elements in the left and the other
indicating the number of elements to the right.
Below is the c++ implementation of the above approach
1247
Chapter 224. Number of GP (Geometric Progression) subsequences of size 3
Output:
Source
https://www.geeksforgeeks.org/number-gp-geometric-progression-subsequences-size-3/
1248
Chapter 225
A naive approach is to iterate for every query from index to end, and find out the number
of next greater elements to the right. This won’t be efficient enough as we run two nested
loops .
Time complexity: O(n) to answer a query.
Auxiliary space: O(1)
Better approach is to store the next greater index of every element and run a loop for
every query that iterates from index and keeping the increasing counter as j = next[i]. This
will avoid checking all elements and will directly jump to the next greater element of every
element. But this won’t be efficient enough in cases like 1 2 3 4 5 6, where the next greater
elements are sequentially increasing, ending it up in taking O(n) for every query.
Time complexity : O(n) to answer a query.
Auxiliary space : O(n) for next greater element.
1249
Chapter 225. Number of NGEs to the right
Efficient approach is to store the next greater elements index using next greater element
in a next[] array. Then create a dp[] array that starts from n-2, as n-1th index will have
no elements to its right and dp[n-1] = 0. While traversing from back we use dynamic
programming to count the number of elements to the right where we use memoization as
dp[next[i]] which gives us a count of the numbers to the right of the next greater element of
the current element, hence we add 1 to it. If next[i]=-1 then we do not have any element to
the right hence dp[i]=0. dp[index] stores the count of the number of next greater elements
to the right.
Below is the c++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// array to store the next greater element index
void fillNext(int next[], int a[], int n)
{
// use of stl stack in c++
stack<int> s;
// push the 0th index to the stack
s.push(0);
// traverse in the loop from 1-nth index
for (int i = 1; i < n; i++) {
// iterate till loop is empty
while (!s.empty()) {
// get the topmost index in the stack
int cur = s.top();
// if the current element is greater
// then the top index-th element, then
// this will be the next greatest index
// of the top index-th element
if (a[cur] < a[i]) {
// initialize the cur index position's
// next greatest as index
next[cur] = i;
// pop the cur index as its greater
// element has been found
s.pop();
}
// if not greater then break
else
1250
Chapter 225. Number of NGEs to the right
break;
}
// push the i index so that its next greatest
// can be found
s.push(i);
}
// iterate for all other index left inside stack
while (!s.empty()) {
int cur = s.top();
// mark it as -1 as no element in greater
// then it in right
next[cur] = -1;
s.pop();
}
}
// function to count the number of next greater numbers to the right
void count(int a[], int dp[], int n)
{
// initializes the next array as 0
int next[n];
memset(next, 0, sizeof(next));
// calls the function to pre-calculate
// the next greatest element indexes
fillNext(next, a, n);
for (int i = n - 2; i >= 0; i--) {
// if the i-th element has no next
// greater element to right
if (next[i] == -1)
dp[i] = 0;
// Count of next greater numbers to right.
else
dp[i] = 1 + dp[next[i]];
}
}
// answers all queries in O(1)
int answerQuery(int dp[], int index)
{
1251
Chapter 225. Number of NGEs to the right
Output:
2
0
3
Source
https://www.geeksforgeeks.org/number-nges-right/
1252
Chapter 226
Input : m = 1, c = 1, arr[] = [ 1, 2, 3, 4, 2 ]
Output : 5 ordered points
Explanation : The equation of the line with given slope and intercept is : y
= x + 1. The Number of pairs (i, j), for which (arri , arrj ) satisfies the above
equation of the line are : (1, 2), (1, 5), (2, 3), (3, 4), (5, 3).
Input : m = 2, c = 1, arr[] = [ 1, 2, 3, 4, 2, 5 ]
Output : 3 ordered points
Source
https://www.geeksforgeeks.org/number-ordered-points-pair-satisfying-line-equation/
C++
1253
Chapter 226. Number of ordered points pair satisfying line equation
1254
Chapter 226. Number of ordered points pair satisfying line equation
Java
1255
Chapter 226. Number of ordered points pair satisfying line equation
1256
Chapter 226. Number of ordered points pair satisfying line equation
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
1257
Chapter 226. Number of ordered points pair satisfying line equation
secondIndex, m, c)) :
counter = counter + 1
return counter
# Driver Code
arr = [ 1, 2, 3, 4, 2 ]
n = len(arr)
# equation of line is y = mx + c
m = 1
c = 1
print (findOrderedPoints(arr, n, m, c))
# This code is contributed by Manish Shaw
# (manishshaw1)
C#
1258
Chapter 226. Number of ordered points pair satisfying line equation
PHP
<?php
1259
Chapter 226. Number of ordered points pair satisfying line equation
1260
Chapter 226. Number of ordered points pair satisfying line equation
Output :
1261
Chapter 226. Number of ordered points pair satisfying line equation
1262
Chapter 226. Number of ordered points pair satisfying line equation
Output:
1263
Chapter 227
A simple solution is to traverse all the subarrays and calculate their sum. If sum is equal
to the required sum then increment the count of subarrays. Print final count of subarrays.
An efficient solution is while traversing the array, store sum so far in currsum. Also maintain
count of different values of currsum in a map. If value of currsum is equal to desired sum
at any instance increment count of subarrays by one. The value of currsum exceeds desired
sum by currsum – sum. If this value is removed from currsum then desired sum can be
obtained. From the map find number of subarrays previously found having sum equal to
currsum-sum. Excluding all those subarrays from current subarray, gives new subarrays
having desired sum. So increase count by the number of such subarrays. Note that when
1264
Chapter 227. Number of subarrays having sum exactly equal to k
currsum is equal to desired sum then also check number of subarrays previously having sum
equal to 0. Excluding those subarrays from current subarray gives new subarrays having
desired sum. Increase count by the number of subarrays having sum 0 in that case.
1265
Chapter 227. Number of subarrays having sum exactly equal to k
return res;
}
int main()
{
int arr[] = { 10, 2, -2, -20, 10 };
int sum = -10;
int n = sizeof(arr) / sizeof(arr[0]);
cout << findSubarraySum(arr, n, sum);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-subarrays-sum-exactly-equal-k/
1266
Chapter 228
Input : 10 20
Output : 10 12 13 14 15 16 17 18 19 20 (Except 11)
Input : 1 10
Output : 1 2 3 4 5 6 7 8 9 10
C++
1267
Chapter 228. Numbers having Unique (or Distinct) digits
{
// Start traversing the numbers
for (int i=l ; i<=r ; i++)
{
int num = i;
bool visited[10] = {false};
// Find digits and maintain its hash
while (num)
{
// if a digit occcurs more than 1 time
// then break
if (visited[num % 10])
break;
visited[num%10] = true;
num = num/10;
}
// num will be 0 only when above loop
// doesn't get break that means the
// number is unique so print it.
if (num == 0)
cout << i << " ";
}
}
// Driver code
int main()
{
int l = 1, r = 20;
printUnique(l, r);
return 0;
}
Java
1268
Chapter 228. Numbers having Unique (or Distinct) digits
{
int num = i;
boolean visited[] = new boolean[10];
// Find digits and maintain its hash
while (num != 0)
{
// if a digit occcurs more than 1 time
// then break
if (visited[num % 10])
break;
visited[num%10] = true;
num = num/10;
}
// num will be 0 only when above loop
// doesn't get break that means the
// number is unique so print it.
if (num == 0)
System.out.print(i + " ");
}
}
// Driver method
public static void main(String args[])
{
int l = 1, r = 20;
printUnique(l, r);
}
}
Python3
# Python3 implementation
# to find unique digit
# numbers in a range
# Function to print
# unique digit numbers
# in range from l to r.
def printUnique(l,r):
# Start traversing
# the numbers
for i in range (l, r + 1):
num = i;
1269
Chapter 228. Numbers having Unique (or Distinct) digits
visited = [0,0,0,0,0,0,0,0,0,0];
# Find digits and
# maintain its hash
while (num):
# if a digit occcurs
# more than 1 time
# then break
if visited[num % 10] == 1:
break;
visited[num % 10] = 1;
num = (int)(num / 10);
# num will be 0 only when
# above loop doesn't get
# break that means the
# number is unique so
# print it.
if num == 0:
print(i, end = " ");
# Driver code
l = 1;
r = 20;
printUnique(l, r);
# This code is
# contributed by mits
C#
1270
Chapter 228. Numbers having Unique (or Distinct) digits
// Find digits and maintain
// its hash
while (num != 0)
{
// if a digit occcurs more
// than 1 time then break
if (visited[num % 10])
break;
visited[num % 10] = true;
num = num / 10;
}
// num will be 0 only when
// above loop doesn't get
// break that means the number
// is unique so print it.
if (num == 0)
Console.Write(i + " ");
}
}
// Driver method
public static void Main()
{
int l = 1, r = 20;
printUnique(l, r);
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP implementation to find unique
// digit numbers in a range
// Function to print unique digit
// numbers in range from l to r.
function printUnique($l, $r)
{
// Start traversing the numbers
for ($i = $l ; $i <= $r; $i++)
{
1271
Chapter 228. Numbers having Unique (or Distinct) digits
$num = $i;
$visited = (false);
// Find digits and
// maintain its hash
while ($num)
{
// if a digit occcurs more
// than 1 time then break
if ($visited[$num % 10])
$visited[$num % 10] = true;
$num = (int)$num / 10;
}
// num will be 0 only when above
// loop doesn't get break that
// means the number is unique
// so print it.
if ($num == 0)
echo $i , " ";
}
}
// Driver code
$l = 1; $r = 20;
printUnique($l, $r);
// This code is contributed by aj_36
?>
Output :
1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20
Source
https://www.geeksforgeeks.org/numbers-unique-distinct-digits/
1272
Chapter 229
Input : int[] arr = { 11, 11, 11, 23, 11, 37, 51,
37, 37, 51, 51, 51, 51 };
k = 2
Output : 37, 51
Explanation :
11's count is 4, 23 count 1, 37 count 3, 51 count 5.
37 and 51 are two number that appear prime number of
time and frequencies greater than or equal to k.
Approach :
1. Create a Map which holds the number as Key and value as its occurrences in the input
array.
2. Iterate the Map keys and look for the values corresponding to their keys, return the key
which
has minimum value fulfilling condition key’s value is a prime number and >= min occurrence
provided
as input.
C++
1273
Chapter 229. Numbers with prime frequencies greater than or equal to k
1274
Chapter 229. Numbers with prime frequencies greater than or equal to k
Java
1275
Chapter 229. Numbers with prime frequencies greater than or equal to k
}
// Check if the number of occurrences
// are primes or not
private static boolean isPrime(int n)
{
if ((n > 2 && n % 2 == 0) || n == 1)
return false;
for (int i = 3; i <= (int)Math.sqrt(n);
i += 2) {
if (n % i == 0)
return false;
}
return true;
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 11, 11, 11, 23, 11, 37,
37, 51, 51, 51, 51, 51 };
int k = 2;
primeOccurences(arr, k);
}
}
Python3
1276
Chapter 229. Numbers with prime frequencies greater than or equal to k
else :
freq = 1
map[val] = freq
# Traverse map and find elements
# with prime frequencies and
# frequency at least k
for entry in map :
value = map[entry]
if isPrime(value) and value >= k:
print(entry)
# Check if the number of occurrences
# are primes or not
def isPrime(n):
if (n > 2 and not n % 2) or n == 1:
return False
for i in range(3, int(n**0.5 + 1), 2):
if not n % i:
return False
return True
# Driver code
arr = [ 11, 11, 11, 23, 11, 37,
37, 51, 51, 51, 51, 51 ]
k = 2
primeOccurences(arr, k)
# This code is contributed by Ansu Kumari.
C#
1277
Chapter 229. Numbers with prime frequencies greater than or equal to k
// Function to find number
// with prime occurrences
static void primeOccurences(int[] arr,
int k)
{
Dictionary<int, int> map =
new Dictionary<int, int>();
// Insert values and
// their frequencies
for (int i = 0; i < arr.Length; i++)
{
int val = arr[i];
int freq;
if (map.ContainsKey(val))
{
freq = map[val];
freq++;
map.Remove(val);
}
else
freq = 1;
map.Add(val, freq);
}
// Traverse map and find elements
// with prime frequencies and
// frequency atleast k
foreach (KeyValuePair<int, int>
pair in map)
{
int value = pair.Value;
if (isPrime(value) &&
value >= k)
Console.WriteLine(pair.Key);
}
}
// Check if the number
// of occurrences
// are primes or not
static bool isPrime(int n)
{
if ((n > 2 &&
n % 2 == 0) || n == 1)
return false;
1278
Chapter 229. Numbers with prime frequencies greater than or equal to k
for (int i = 3;
i <= (int)Math.Sqrt(n);
i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
// Driver code
static void Main()
{
int[] arr = new int[]{11, 11, 11, 23, 11, 37,
37, 51, 51, 51, 51, 51};
int k = 2;
primeOccurences(arr, k);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output :
37
51
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/numbers-prime-frequencies-greater-equal-k/
1279
Chapter 230
Numbers with sum of digits equal to the sum of digits of its all prime factor - GeeksforGeeks
Given a range, the task is to find the count of the numbers in the given range such that the
sum of its digit is equal to the sum of all its prime factors digits sum.
Examples:
Input: l = 2, r = 10
Output: 5
2, 3, 4, 5 and 7 are such numbers
Input: l = 15, r = 22
Output: 3
17, 19 and 22 are such numbers
As, 17 and 19 are already prime.
Prime Factors of 22 = 2 * 11 i.e
For 22, Sum of digits is 2+2 = 4
For 2 * 11, Sum of digits is 2 + 1 + 1 = 4
Approach: An efficient solution is to modify Sieve of Eratosthenes such that for each
non-prime number it stores smallest prime factor(prefactor).
1. Preprocess to find the smallest prime factorfor all the numbers between 2 and MAXN.
This can be done by breaking up the number into its prime factors in constant time
because for each number if it is a prime, it has no prefactor.
1280
Chapter 230. Numbers with sum of digits equal to the sum of digits of its all prime factor
2. Otherwise, we can break it up to into a prime factor and the other part of the number
which may or may not be prime.
5. Now make prefix sum array that counts how many valid numbers are there up to a
number N. For each query, print:
ans[R] – ans[L-1]
C++
1281
Chapter 230. Numbers with sum of digits equal to the sum of digits of its all prime factor
1282
Chapter 230. Numbers with sum of digits equal to the sum of digits of its all prime factor
}
// prefix sum to compute answer
for (int n = 2; n < MAXN; n++) {
if (isValid[n])
ans[n] = 1;
ans[n] += ans[n - 1];
}
}
// Driver code
int main()
{
Smallest_prime_factor();
Sum_Of_All_Digits();
// decleartion
int l, r;
// print answer for required range
l = 2, r = 3;
cout << "Valid numbers in the range " << l << " "
<< r << " are " << ans[r] - ans[l - 1] << endl;
// print answer for required range
l = 2, r = 10;
cout << "Valid numbers in the range " << l << " "
<< r << " are " << ans[r] - ans[l - 1] << endl;
return 0;
}
Java
1283
Chapter 230. Numbers with sum of digits equal to the sum of digits of its all prime factor
1284
Chapter 230. Numbers with sum of digits equal to the sum of digits of its all prime factor
// of digits in a number
static int Digit_Sum(int copy)
{
int d = 0;
while (copy > 0)
{
d += copy % 10;
copy /= 10;
}
return d;
}
// find sum of digits of
// all numbers up to MAXN
static void Sum_Of_All_Digits()
{
for (int n = 2; n < MAXN; n++)
{
// add sum of digits of least
// prime factor and n/spf[n]
sum_digits[n] = sum_digits[n / spf[n]]
+ Digit_Sum(spf[n]);
// if it is valid make isValid true
if (Digit_Sum(n) == sum_digits[n])
isValid[n] = true;
}
// prefix sum to compute answer
for (int n = 2; n < MAXN; n++)
{
if (isValid[n])
ans[n] = 1;
ans[n] += ans[n - 1];
}
}
// Driver code
public static void main (String[] args)
{
Smallest_prime_factor();
Sum_Of_All_Digits();
// declaration
int l, r;
// print answer for required range
1285
Chapter 230. Numbers with sum of digits equal to the sum of digits of its all prime factor
l = 2; r = 3;
System.out.println("Valid numbers in the range " +
l + " " + r + " are " +
(ans[r] - ans[l - 1] ));
// print answer for required range
l = 2; r = 10;
System.out.println("Valid numbers in the range " +
l + " " + r + " are " +
(ans[r] - ans[l - 1]));
}
}
// This code is contributed
// by Inder
C#
1286
Chapter 230. Numbers with sum of digits equal to the sum of digits of its all prime factor
1287
Chapter 230. Numbers with sum of digits equal to the sum of digits of its all prime factor
{
for (int n = 2; n < MAXN; n++)
{
// add sum of digits of least
// prime factor and n/spf[n]
sum_digits[n] = sum_digits[n / spf[n]] +
Digit_Sum(spf[n]);
// if it is valid make
// isValid true
if (Digit_Sum(n) == sum_digits[n])
isValid[n] = true;
}
// prefix sum to compute answer
for (int n = 2; n < MAXN; n++)
{
if (isValid[n])
ans[n] = 1;
ans[n] += ans[n - 1];
}
}
// Driver code
public static void Main ()
{
Smallest_prime_factor();
Sum_Of_All_Digits();
// declaration
int l, r;
// print answer for required range
l = 2; r = 3;
Console.WriteLine("Valid numbers in the range " +
l + " " + r + " are " +
(ans[r] - ans[l - 1] ));
// print answer for required range
l = 2; r = 10;
Console.WriteLine("Valid numbers in the range " +
l + " " + r + " are " +
(ans[r] - ans[l - 1]));
}
}
// This code is contributed
// by Subhadeep
1288
Chapter 230. Numbers with sum of digits equal to the sum of digits of its all prime factor
Output:
Source
https://www.geeksforgeeks.org/numbers-with-sum-of-digits-equal-to-the-sum-of-digits-of-its-all-prime-factor/
1289
Chapter 231
Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap) - GeeksforGeeks
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one
mapping between nuts and bolts. Match nuts and bolts efficiently.
Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed.
It means nut can only be compared with bolt and bolt can only be compared with nut to
see which one is bigger/smaller.
Examples:
Other way of asking this problem is, given a box with locks and keys where one lock can be
opened by one key in the box. We need to match the pair.
We have discussed a sorting based solution in below post.
Nuts & Bolts Problem (Lock & Key problem) | Set 1
In this post, hashmap based approach is discussed.
1290
Chapter 231. Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap)
3. If it is found in the hashmap of nuts than this means bolts exist for that nut.
Output:
1291
Chapter 231. Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap)
Source
https://www.geeksforgeeks.org/nuts-bolts-problem-lock-key-problem-set-2-hashmap/
1292
Chapter 232
Only integer with positive value in positive negative value in array - GeeksforGeeks
Given an array of N integers. In the given, for each positive element ‘x’ there exist a
negative value ‘-x’, except one integer whose negative value is not present. That integer
may occur multiple number of time. The task is find that integer.
Examples:
Method 1: (hashing) The idea is to create a hash table, initialize with zero value. When-
ever we encounter a positive value, we add +1 on corresponding index position in hash.
And whenever we encounter negative value we add -1. Finally we traverse the whole hash.
After traversing, the index with non-zero value is the only integer with only value without
negative pair.
Below is C++ implementation of this approach:
1293
Chapter 232. Only integer with positive value in positive negative value in array
#include <bits/stdc++.h>
using namespace std;
// Return the integer with have no negative value.
int findInteger(int arr[], int n)
{
unorder_map<int, int> hash;
int maximum = 0;
// Traversing the array.
for (int i = 0; i < n; i++) {
// If negative, then subtract 1 in hash array.
if (arr[i] < 0)
hash[abs(arr[i])] -= 1;
// Else add 1 in hash array.
else
hash[arr[i]] += 1;
}
// Traverse the hash array.
for (int i = 0; i < n; i++)
if (hash[arr[i]] == 0)
return i;
return -1;
}
// Driven Program
int main()
{
int arr[] = { 1, 8, -6, -1, 6, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findInteger(arr, n) << endl;
return 0;
}
Output:
Method 2: (efficient) The idea is to find the sum of each element of array and also count
the number of even and odd numbers in the array. Finally, divide the sum by absolute
difference of number of odd element and even element.
1294
Chapter 232. Only integer with positive value in positive negative value in array
C++
Java
1295
Chapter 232. Only integer with positive value in positive negative value in array
// Return the integer with have
// no negative value.
static int findInteger(int arr[], int n)
{
int neg = 0, pos = 0;
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += arr[i];
// If negative, then increment
// neg count.
if (arr[i] < 0)
neg++;
// Else increment pos count..
else
pos++;
}
return (sum / Math.abs(neg - pos));
}
// Driven Program
public static void main(String[] args)
{
int arr[] = new int[]{ 1, 8, -6, -1, 6, 8 };
int n = arr.length;
System.out.println(findInteger(arr, n));
}
}
// This code is contributed by Smitha.
Python 3
1296
Chapter 232. Only integer with positive value in positive negative value in array
neg = 0
pos = 0
sum = 0
for i in range(0, n):
sum += arr[i]
# If negative, then increment
# neg count.
if (arr[i] < 0):
neg += 1
# Else increment pos count..
else:
pos += 1
return (sum / abs(neg - pos))
# Driven Program
arr = [1, 8, -6, -1, 6, 8 ]
n = len(arr)
print(int(findInteger(arr, n)))
# This code is contributed by Smitha.
C#
1297
Chapter 232. Only integer with positive value in positive negative value in array
neg++;
// Else increment pos count..
else
pos++;
}
return (sum / Math.Abs(neg - pos));
}
// Driven Program
public static void Main()
{
int [] arr = new int[]{ 1, 8, -6,
-1, 6, 8 };
int n = arr.Length;
Console.Write(findInteger(arr, n));
}
}
// This code is contributed by Smitha.
PHP
<?php
// An efficient solution to find the only
// element that doesn't have negative value.
// Return the integer with
// have no negative value.
function findInteger($arr, $n)
{
$neg = 0; $pos = 0;
$sum = 0;
for ($i = 0; $i < $n; $i++)
{
$sum += $arr[$i];
// If negative, then
// increment neg count.
if ($arr[$i] < 0)
$neg++;
// Else increment
// pos count..
else
1298
Chapter 232. Only integer with positive value in positive negative value in array
$pos++;
}
return ($sum / abs($neg - $pos));
}
// Driver Code
$arr = array(1, 8, -6, -1, 6, 8);
$n = sizeof($arr);
echo findInteger($arr, $n) ,"\n";
// This code is contributed by aj_36
?>
Output:
Source
https://www.geeksforgeeks.org/integer-positive-value-positive-negative-value-array/
1299
Chapter 233
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) - GeeksforGeeks
We have discussed Overview of Array, Linked List, Queue and Stack. In this article following
Data Structures are discussed.
5. Binary Tree
6. Binary Search Tree
7. Binary Heap
9. Hashing
Binary Tree
Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are
hierarchical data structures.
A binary tree is a tree data structure in which each node has at most two children, which
are referred to as the left child and the right child. It is implemented mainly using Links.
Binary Tree Representation: A tree is represented by a pointer to the topmost node in
tree. If the tree is empty, then value of root is NULL. A Binary Tree node contains following
parts.
1. Data
2. Pointer to left child
3. Pointer to right child
A Binary Tree can be traversed in two ways:
Depth First Traversal: Inorder (Left-Root-Right), Preorder (Root-Left-Right) and Postorder
(Left-Right-Root)
Breadth First Traversal: Level Order Traversal
Binary Tree Properties:
1300
Chapter 233. Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Examples : One reason to use binary tree or tree in general is for the things that form
a hierarchy. They are useful in File structures where each file is located in a particular
directory and there is a specific hierarchy associated with files and directories. Another
example where Trees are useful is storing heirarchical objects like JavaScript Document
Object Model considers HTML page as a tree with nesting of tags as parent child relations.
Binary Search Tree
In Binary Search Tree is a Binary Tree with following additional properties:
1. The left subtree of a node contains only nodes with keys less than the node’s key.
2. The right subtree of a node contains only nodes with keys greater than the node’s key.
3. The left and right subtree each must also be a binary search tree.
Time Complexities:
Search : O(h)
Insertion : O(h)
Deletion : O(h)
Extra Space : O(n) for pointers
h: Height of BST
n: Number of nodes in BST
BST provide moderate access/search (quicker than Linked List and slower than arrays).
BST provide moderate insertion/deletion (quicker than Arrays and slower than Linked
Lists).
Examples : Its main use is in search application where data is constantly entering/leaving
and data needs to printed in sorted order. For example in implementation in E- commerce
1301
Chapter 233. Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
websites where a new product is added or product goes out of stock and all products are
lised in sorted order.
Binary Heap
A Binary Heap is a Binary Tree with following properties.
1) It’s a complete tree (All levels are completely filled except possibly the last level and the
last level has all keys as left as possible). This property of Binary Heap makes them suitable
to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at
root must be minimum among all keys present in Binary Heap. The same property must
be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to Min Heap.
It is mainly implemented using array.
Get Minimum in Min Heap: O(1) [Or Get Max in Max Heap]
Extract Minimum Min Heap: O(Log n) [Or Extract Max in Max Heap]
Decrease Key in Min Heap: O(Log n) [Or Extract Max in Max Heap]
Insert: O(Log n)
Delete: O(Log n)
Example : Used in implementing efficient priority-queues, which in turn are used for
scheduling processes in operating systems. Priority Queues are also used in Dijstra’s and
Prim’s graph algorithms.
The Heap data structure can be used to efficiently find the k smallest (or largest) elements
in an array, merging k sorted arrays, median of a stream, etc.
Heap is a special data structure and it cannot be used for searching of a particular element.
HashingHash Function: A function that converts a given big input key to a small practi-
cal integer value. The mapped integer value is used as an index in hash table. A good hash
function should have following properties
1) Efficiently computable.
2) Should uniformly distribute the keys (Each table position equally likely for each key)
Hash Table: An array that stores pointers to records corresponding to a given phone number.
An entry in hash table is NIL if no existing phone number has hash function value equal to
the index for the entry.
Collision Handling: Since a hash function gets us a small number for a key which is a big
integer or string, there is possibility that two keys result in same value. The situation where
a newly inserted key maps to an already occupied slot in hash table is called collision and
must be handled using some collision handling technique. Following are the ways to handle
collisions:
Chaining:The idea is to make each cell of hash table point to a linked list of records that
have same hash function value. Chaining is simple, but requires additional memory outside
the table.
Open Addressing: In open addressing, all elements are stored in the hash table itself. Each
table entry contains either a record or NIL. When searching for an element, we one by one
examine table slots until the desired element is found or it is clear that the element is not
in the table.
1302
Chapter 233. Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Space : O(n)
Search : O(1) [Average] O(n) [Worst case]
Insertion : O(1) [Average] O(n) [Worst Case]
Deletion : O(1) [Average] O(n) [Worst Case]
Hashing seems better than BST for all the operations. But in hashing, elements are un-
ordered and in BST elements are stored in an ordered manner. Also BST is easy to imple-
ment but hash functions can sometimes be very complex to generate. In BST, we can also
efficiently find floor and ceil of values.
Example : Hashing can be used to remove duplicates from a set of elements. Can also
be used find frequency of all items. For example, in web browsers, we can check visited
urls using hashing. In firewalls, we can use hashing to detect spam. We need to hash IP
addresses. Hashing can be used in any situation where want search() insert() and delete()
in O(1) time.
This article is contributed by Abhiraj Smit. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Rahul1421
Source
https://www.geeksforgeeks.org/overview-of-data-structures-set-2-binary-tree-bst-heap-and-hash/
1303
Chapter 234
Pair with given product | Set 1 (Find if any pair exists) - GeeksforGeeks
Given an array of distinct elements and a number x, find if there is a pair with product
equal to x.
Examples :
Naive approach ( O(n2 ) ) is to run two loops to consider all possible pairs. For every
pair, check if product is equal to x or not.
1304
Chapter 234. Pair with given product | Set 1 (Find if any pair exists)
C++
Java
1305
Chapter 234. Pair with given product | Set 1 (Find if any pair exists)
if (arr[i]*arr[j] == x)
return true;
return false;
}
// Driver code
public static void main(String[] args)
{
GFG g = new GFG();
int arr[] = {10, 20, 9, 40};
int x = 400;
int n = arr.length;
if (g.isProduct(arr, n, x))
System.out.println("Yes");
else
System.out.println("No");
x = 190;
if (g.isProduct(arr, n, x))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Kamal Rawal
Python3
1306
Chapter 234. Pair with given product | Set 1 (Find if any pair exists)
print ("Yes")
else:
print("No")
x = 900
if(isProduct(arr, n, x)):
print("Yes")
else:
print("No")
# This code is contributed
# by prerna saini
C#
// C# program to find
// if there is a pair
// with given product.
using System;
class GFG
{
// Returns true if there
// is a pair in arr[0..n-1]
// with product equal to x.
static bool isProduct(int []arr,
int n, int x)
{
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] * arr[j] == x)
return true;
return false;
}
// Driver Code
static void Main()
{
int []arr = {10, 20, 9, 40};
int x = 400;
int n = arr.Length;
if (isProduct(arr, n, x))
Console.WriteLine("Yes");
else
1307
Chapter 234. Pair with given product | Set 1 (Find if any pair exists)
Console.WriteLine("No");
x = 190;
if (isProduct(arr, n, x))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed
// by Sam007
PHP
<?php
// A simple php program to
// find if there is a pair
// with given product.
// Returns true if there
// is a pair in arr[0..n-1]
// with product equal to x.
function isProduct($arr, $n, $x)
{
// Consider all possible
// pairs and check for
// every pair.
for ($i = 0;
$i < $n - 1; $i++)
for ($j = $i + 1;
$i < $n; $i++)
if ($arr[$i] *
$arr[$j] == $x)
return true;
return false;
}
// Driver code
$arr = array(10, 20, 9, 40);
$x = 400;
$n = count($arr);
if(isProduct($arr, $n, $x))
echo "Yes\n";
else
echo "No\n";
1308
Chapter 234. Pair with given product | Set 1 (Find if any pair exists)
$x = 190;
if(isProduct($arr, $n, $x))
echo "Yes\n";
else
echo "No\n";
// This code is contributed
// by Sam007
?>
Output :
Yes
No
Better Solution (O(n Log n) : We sort the given array. After sorting, we traverse the
array and for every element arr[i], we do binary search for x/arr[i] in the subarry on right
of arr[i], i.e., in subarray arr[i+1..n-1]
Efficient Solution ( O(n) ): We can improve time complexity to O(n) using hashing.
Below are steps.
C++
1309
Chapter 234. Pair with given product | Set 1 (Find if any pair exists)
1310
Chapter 234. Pair with given product | Set 1 (Find if any pair exists)
Java
1311
Chapter 234. Pair with given product | Set 1 (Find if any pair exists)
}
// driver code
public static void main(String[] args)
{
int arr[] = {10, 20, 9, 40};
int x = 400;
int n = arr.length;
if(isProduct(arr, arr.length, x))
System.out.println("Yes");
else
System.out.println("No");
x = 190;
if(isProduct(arr, arr.length, x))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by Kamal Rawal
Output :
Yes
No
In the next set, we will be discussing approach to print all pairs with product equal to 0.
This article is contributed by Shubham Goyal. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Sam007
Source
https://www.geeksforgeeks.org/pair-with-given-product-set-1-find-if-any-pair-exists/
1312
Chapter 235
Pair with given sum and maximum shortest distance from end - GeeksforGeeks
Given an array of N integers and an integer K, pick two distinct elements whose sum is K
and find the maximum shortest distance of the picked elements from the endpoints.
Examples:
1313
Chapter 235. Pair with given sum and maximum shortest distance from end
Naive approach: The approach is to run two loops and in inner loop check if two elements
are making a pair with sum k. If yes, then make answer as maximum of the shortest
distances of two elements, compare it with the previous pair’s answer and make answer as
minimum of these two. When the loop ends we get the desired output.
Efficient Approach: Clearly, Shortest distance is the distance from left end and distance
and store shortest distance of all the array elements in another array(let it be ). Now,
we got shortest distances of all the elements.
Run a for loop. If the picked element is x, then the other element should be k-x. Update the
of previous and present answer. If k-x is not in the array, then will be
INFINITE, which will be initialized already.
1314
Chapter 235. Pair with given sum and maximum shortest distance from end
int ans = INT_MAX;
for (int i = 0; i < n; i++) {
int x = a[i];
// similar elements ignore them
// cause we need distinct elements
if (x != k - x && b.find(k - x) != b.end())
ans = min(max(b[x], b[k - x]), ans);
}
return ans;
}
// driver code
int main()
{
int a[] = { 3, 5, 8, 6, 7 };
int K = 11;
int n = sizeof(a) / sizeof(a[0]);
cout << find_maximum(a, n, K) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/print-maximum-shortest-distance/
1315
Chapter 236
A simple solution is to traverse each pair and check if they form an amicable pair, if they
do we increment the count.
C++
1316
Chapter 236. Pairs of Amicable Numbers
{
// 1 is a proper divisor
int sum = 1;
for (int i = 2; i <= sqrt(x); i++)
{
if (x % i == 0)
{
sum += i;
// To handle perfect squares
if (x / i != i)
sum += x / i;
}
}
return sum;
}
// Check if pair is amicable
bool isAmicable(int a, int b)
{
return (sumOfDiv(a) == b &&
sumOfDiv(b) == a);
}
// This function prints pair
// of amicable pairs present
// in the input array
int countPairs(int arr[], int n)
{
int count = 0;
// Iterate through each
// pair, and find if it
// an amicable pair
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (isAmicable(arr[i], arr[j]))
count++;
return count;
}
// Driver code
int main()
{
int arr1[] = { 220, 284, 1184,
1210, 2, 5 };
int n1 = sizeof(arr1) / sizeof(arr1[0]);
1317
Chapter 236. Pairs of Amicable Numbers
Java
1318
Chapter 236. Pairs of Amicable Numbers
Python3
1319
Chapter 236. Pairs of Amicable Numbers
sum += i
return sum
# Check if pair is amicable
def isAmicable(a, b):
if sumOfDiv(a) == b and sumOfDiv(b) == a:
return True
else:
return False
# This function prints pair
# of amicable pairs present
# in the input array
def countPairs(arr, n):
count = 0
for i in range(0, n):
for j in range(i + 1, n):
if isAmicable(arr[i], arr[j]):
count = count + 1
return count
# Driver Code
arr1 = [220, 284, 1184,
1210, 2, 5]
n1 = len(arr1)
print(countPairs(arr1, n1))
arr2 = [2620, 2924, 5020,
5564, 6232, 6368]
n2 = len(arr2)
print(countPairs(arr2, n2))
# This code is contributed
# by Smitha Dinesh Semwal
C#
1320
Chapter 236. Pairs of Amicable Numbers
// 1 is a proper divisor
int sum = 1;
for (int i = 2; i <= Math.Sqrt(x); i++)
{
if (x % i == 0)
{
sum += i;
// To handle perfect squares
if (x / i != i)
sum += x / i;
}
}
return sum;
}
// Check if pair is amicable
static bool isAmicable(int a, int b)
{
return (sumOfDiv(a) == b &&
sumOfDiv(b) == a);
}
// This function prints pair
// of amicable pairs present
// in the input array
static int countPairs(int []arr, int n)
{
int count = 0;
// Iterate through each pair,
// and find if it an amicable pair
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (isAmicable(arr[i], arr[j]))
count++;
return count;
}
// Driver code
public static void Main()
{
int []arr1 = {220, 284, 1184,
1321
Chapter 236. Pairs of Amicable Numbers
1210, 2, 5};
int n1 = arr1.Length;
Console.WriteLine(countPairs(arr1, n1));
int []arr2 = {2620, 2924, 5020,
5564, 6232, 6368};
int n2 = arr2.Length;
Console.WriteLine(countPairs(arr2, n2));
}
}
// This code is contributed by vt_m.
PHP
<?php
// A simple PHP program to count
// amicable pairs in an array.
// Calculate the sum
// of proper divisors
function sumOfDiv( $x)
{
// 1 is a proper divisor
$sum = 1;
for ( $i = 2; $i <= sqrt($x); $i++)
{
if ($x % $i == 0)
{
$sum += $i;
// To handle perfect squares
if ($x / $i != $i)
$sum += $x / $i;
}
}
return $sum;
}
// Check if pair is amicable
function isAmicable( $a, $b)
{
return (sumOfDiv($a) == $b and
sumOfDiv($b) == $a);
}
1322
Chapter 236. Pairs of Amicable Numbers
Output :
2
3
An efficient solution is be to keep the numbers stored in a map and for every number
we find the sum of its proper divisor and check if that’s also present in the array. If it is
present, we can check if they form an amicable pair or not.
Thus, the complexity would be considerably reduced. Below is the C++ program for the
same.
1323
Chapter 236. Pairs of Amicable Numbers
// Calculate the sum
// of proper divisors
int sumOfDiv(int x)
{
// 1 is a proper divisor
int sum = 1;
for (int i = 2; i <= sqrt(x); i++)
{
if (x % i == 0) {
sum += i;
// To handle perfect squares
if (x / i != i)
sum += x / i;
}
}
return sum;
}
// Check if pair is amicable
bool isAmicable(int a, int b)
{
return (sumOfDiv(a) == b &&
sumOfDiv(b) == a);
}
// This function prints count
// of amicable pairs present
// in the input array
int countPairs(int arr[], int n)
{
// Map to store the numbers
unordered_set<int> s;
int count = 0;
for (int i = 0; i < n; i++)
s.insert(arr[i]);
// Iterate through each number,
// and find the sum of proper
// divisors and check if it's
// also present in the array
for (int i = 0; i < n; i++)
{
if (s.find(sumOfDiv(arr[i])) != s.end())
{
// It's sum of proper divisors
int sum = sumOfDiv(arr[i]);
1324
Chapter 236. Pairs of Amicable Numbers
Output :
2
3
Improved By : vt_m
Source
https://www.geeksforgeeks.org/pairs-amicable-numbers/
1325
Chapter 237
C++
1326
Chapter 237. Pairs of Positive Negative values in an array
Java
1327
Chapter 237. Pairs of Positive Negative values in an array
{
Vector<Integer> v = new Vector<Integer>();
// For each element of array.
for (int i = 0; i < n; i++)
// Try to find the negative value of
// arr[i] from i + 1 to n
for (int j = i + 1; j < n; j++)
// If absolute values are equal
// print pair.
if (Math.abs(arr[i]) ==
Math.abs(arr[j]))
v.add(Math.abs(arr[i]));
// If size of vector is 0, therefore there
// is no element with positive negative
// value, print "0"
if (v.size() == 0)
return;
// Sort the vector
Collections.sort(v);
// Print the pair with negative positive
// value.
for (int i = 0; i < v.size(); i++)
System.out.print(-v.get(i) + " " +
v.get(i));
}
// Driven Program
public static void main(String[] args)
{
int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
int n = arr.length;
printPairs(arr, n);
}
}
// This code is contributed by Prasad Kshirsagar.
Output:
1328
Chapter 237. Pairs of Positive Negative values in an array
Method 2 (Hahing)
The idea is to use hashing. Traverse the given array, increase the count at absolute value of
hash table. If count becomes 2, store its absolute value in another vector. And finally sort
the vector. If the size of the vector is 0, print “0”, else for each term in vector print first its
negative value and the the positive value.
Below is C++ implementation of this approach:
1329
Chapter 237. Pairs of Positive Negative values in an array
printPairs(arr, n);
return 0;
}
Output:
-1 1 -4 4 -8 8 -9 9
Improved By : Prasad_Kshirsagar
Source
https://www.geeksforgeeks.org/pairs-of-positive-negative-values-in-an-array/
1330
Chapter 238
1331
Chapter 238. Palindrome Substring Queries
prefix[0] = 0
prefix[i] = str[0] + str[1] * 101 + str[2] * 1012 +
...... + str[i-1] * 101i-1
prefix[0] = 0
prefix[1] = 97 (ASCII Value of ‘a’ is 97)
prefix[2] = 97 + 98 * 101
prefix[3] = 97 + 98 * 101 + 97 * 1012
...........................
...........................
prefix[11] = 97 + 98 * 101 + 97 * 1012 +
........+ 97 * 10110
Now the reason to store in that way is that we can easily find the hash value of any substring
in O(1) time using-
For example, hash (1, 5) = hash (“baaab”) = prefix[6] – prefix[1] = 98 * 101 + 97 * 1012
+ 97 * 1013 + 97 * 1014 + 98 * 1015 = 1040184646587 [We will use this weird value later
to explain what’s happening].
Similar to this we will fill our suffix[] array as-
suffix[0] = 0
suffix[i] = str[n-1] + str[n-2] * 101 + str[n-3] * 1012 +
...... + str[n-i] * 101i-1
suffix[0] = 0
suffix[1] = 97 (ASCII Value of ‘a’ is 97)
suffix[2] = 97 + 98 * 101
suffix[3] = 97 + 98 * 101 + 97 * 1012
...........................
...........................
suffix[11] = 97 + 98 * 101 + 97 * 1012 + ........+ 97 * 10110
Now the reason to store in that way is that we can easily find the reverse hash value of any
substring in O(1) time using
1332
Chapter 238. Palindrome Substring Queries
1333
Chapter 238. Palindrome Substring Queries
…. ….. ….. ……
…. ….. ….. ……
This property is used by modPow() function which computes power of a number modulo M
3) Mixture of addition and multiplication-
(a * x + b * y + c) % M = ( (a * x) % M +(b * y) % M+ c % M ) % M
4) Subtraction-
(a – b) % M = (a % M – b % M + M) % M [Correct]
(a – b) % M = (a % M – b % M) % M [Wrong]
5) Division-
(a / b) % M = (a * MMI(b)) % M
Where MMI() is a function to calculate Modulo Multiplicative Inverse. In our program this
is implemented by the function- findMMI().
1334
Chapter 238. Palindrome Substring Queries
return 1;
if (exponent == 1)
return base;
unsigned long long int temp = modPow(base, exponent/2);
if (exponent %2 ==0)
return (temp%MOD * temp%MOD) % MOD;
else
return ((( temp%MOD * temp%MOD)%MOD) * base%MOD) % MOD;
}
// A Function to calculate Modulo Multiplicative Inverse of 'n'
unsigned long long int findMMI(unsigned long long int n)
{
return modPow(n, MOD-2);
}
// A Function to calculate the prefix hash
void computePrefixHash(string str, int n, unsigned long long
int prefix[], unsigned long long int power[])
{
prefix[0] = 0;
prefix[1] = str[0];
for (int i=2; i<=n; i++)
prefix[i] = (prefix[i-1]%MOD +
(str[i-1]%MOD * power[i-1]%MOD)%MOD)%MOD;
return;
}
// A Function to calculate the suffix hash
// Suffix hash is nothing but the prefix hash of
// the reversed string
void computeSuffixHash(string str, int n,
unsigned long long int suffix[],
unsigned long long int power[])
{
suffix[0] = 0;
suffix[1] = str[n-1];
for (int i=n-2, j=2; i>=0 && j<=n; i--,j++)
suffix[j] = (suffix[j-1]%MOD +
(str[i]%MOD * power[j-1]%MOD)%MOD)%MOD;
return;
}
1335
Chapter 238. Palindrome Substring Queries
// A Function to answer the Queries
void queryResults(string str, Query q[], int m, int n,
unsigned long long int prefix[],
unsigned long long int suffix[],
unsigned long long int power[])
{
for (int i=0; i<=m-1; i++)
{
int L = q[i].L;
int R = q[i].R;
// Hash Value of Substring [L,R]
unsigned long long hash_LR =
((prefix[R+1]-prefix[L]+MOD)%MOD *
findMMI(power[L])%MOD)%MOD;
// Reverse Hash Value of Substring [L,R]
unsigned long long reverse_hash_LR =
((suffix[n-L]-suffix[n-R-1]+MOD)%MOD *
findMMI(power[n-R-1])%MOD)%MOD;
// If both are equal then the substring is a palindrome
if (hash_LR == reverse_hash_LR )
{
if (isPalindrome(str, L, R) == true)
printf("The Substring [%d %d] is a "
"palindrome\n", L, R);
else
printf("The Substring [%d %d] is not a "
"palindrome\n", L, R);
}
else
printf("The Substring [%d %d] is not a "
"palindrome\n", L, R);
}
return;
}
// A Dynamic Programming Based Approach to compute the
// powers of 101
void computePowers(unsigned long long int power[], int n)
{
// 101^0 = 1
power[0] = 1;
1336
Chapter 238. Palindrome Substring Queries
Output :
Source
https://www.geeksforgeeks.org/palindrome-substring-queries/
1337
Chapter 239
Output :
192.168.1.3 1
192.168.1.2 3
1338
Chapter 239. Parsing Apache access log in Java
import java.util.regex.Pattern;
class FindSuccessIpCount {
public static void findSuccessIpCount(String record)
{
// Creating a regular expression for the records
final String regex = "^(\\S+) (\\S+) (\\S+) " +
"\\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(\\S+)" +
" (\\S+)\\s*(\\S+)?\\s*\" (\\d{3}) (\\S+)";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(record);
// Creating a Hashmap containing string as
// the key and integer as the value.
HashMap<String, Integer> countIP = new HashMap<String, Integer>();
while (matcher.find()) {
String IP = matcher.group(1);
String Response = matcher.group(8);
int response = Integer.parseInt(Response);
// Inserting the IP addresses in the
// HashMap and maintaining the frequency
// for each HTTP 200 code.
if (response == 200) {
if (countIP.containsKey(IP)) {
countIP.put(IP, countIP.get(IP) + 1);
}
else {
countIP.put(IP, 1);
}
}
}
// Printing the hashmap
for (Map.Entry entry : countIP.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
public static void main(String[] args)
{
final String log = "123.123.123.123 - - [26/Apr/2000:00:23:48 -0400] \"GET /pics/wpaper.g
+ "123.123.123.123 - - [26/Apr/2000:00:23:47 -0400] \"GET /asctortf/ H
+ "123.123.123.124 - - [26/Apr/2000:00:23:48 -0400] \"GET /pics/5star2
+ "123.123.123.123 - - [26/Apr/2000:00:23:50 -0400] \"GET /pics/5star.
+ "123.123.123.126 - - [26/Apr/2000:00:23:51 -0400] \"GET /pics/a2hlog
1339
Chapter 239. Parsing Apache access log in Java
Output:
123.123.123.126 1
123.123.123.124 1
123.123.123.123 3
Source
https://www.geeksforgeeks.org/parsing-apache-access-log-in-java/
1340
Chapter 240
Postorder traversal of Binary Tree without recursion and without stack - GeeksforGeeks
Prerequisite – Inorder/preorder/postorder traversal of tree
Given a binary tree, perform postorder traversal.
We have discussed below methods for postorder traversal.
1) Recursive Postorder Traversal.
2) Postorder traversal using Stack.
2) Postorder traversal using two Stacks.
In this method a DFS based solution is discussed. We keep track of visited nodes in a hash
table.
1341
Chapter 240. Postorder traversal of Binary Tree without recursion and without stack
1342
Chapter 240. Postorder traversal of Binary Tree without recursion and without stack
Output:
1 4 7 6 3 13 14 10 8
Alternate Solution:
We can keep visited flag with every node instead of separate hash table.
1343
Chapter 240. Postorder traversal of Binary Tree without recursion and without stack
node->visited = false;
return (node);
}
/* Driver program to test above functions*/
int main()
{
struct Node* root = newNode(8);
root->left = newNode(3);
root->right = newNode(10);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->left->right->left = newNode(4);
root->left->right->right = newNode(7);
root->right->right = newNode(14);
root->right->right->left = newNode(13);
postorder(root);
return 0;
}
Output:
1 4 7 6 3 13 14 10 8
Time complexity of above solution is O(n2 ) in worst case we move pointer back to head
after visiting every node.
Source
https://www.geeksforgeeks.org/postorder-traversal-binary-tree-without-recursion-without-stack/
1344
Chapter 241
• The purpose of hashing is to achieve search, insert and delete complexity to O(1).
• Hash function is designed to distribute keys uniformly over the hash table.
• Load factor � in hash table can be defined as number of slots in hash table to number
of keys to be inserted.
• For open addressing, load factor � is always less than one.
• The complexity of insertion, deletion and searching using open addressing is 1/(1-�).
• The complexity of insertion, deletion and searching using chaining method is (1+�).
1345
Chapter 241. Practice Problems on Hashing
h(9679) = 9679%10 = 9
h(1989) = 1989%10 = 9
h(4199) = 4199%10 = 9
h(1471) = 1471%10 = 1
h(6171) = 6171%10 = 1
As we can see, 9679, 1989 and 4199 hash to same value 9. Also, 1471 and 6171 hash to same
value 1. Therefore, statement (i) and (ii) are correct which match with option (C).
Type 2: Insertion of keys into hash table using linear probing as collision reso-
lution technique –
In linear probing technique, collision is resolved by searching linearly in the hash table until
an empty location is found.
Que – 2. The keys 12, 18, 13, 2, 3, 23, 5 and 15 are inserted into an initially empty hash
table of length 10 using open addressing with hash function h(k) = k mod 10 and linear
probing. What is the resultant hash table?
Solution: Keys 12, 18, 13, 2, 3, 23, 5 and 15 are inserted in hash table as:
For key 12, h(12) is 12%10 = 2. Therefore, 12 is placed at 2nd index in the hash table.
For key 18, h(18) is 18%10 = 8. Therefore, 18 is placed at 8th index in the hash table.
For key 13, h(13) is 13%10 = 3. Therefore, 13 is placed at 3rd index in the hash table.
For key 2, h(2) is 2%10 = 2. However, index 2 is already occupied with 12. Therefore, using
linear probing, 2 will be placed at index 4 as index 2 and 3 are already occupied.
For key 3, h(3) is 3%10 = 3. However, index 3 is already occupied with 13. Therefore, using
linear probing, 3 will be placed at index 5 as index 3 and 4 are already occupied.
Similarly, 23, 5 and 15 will be placed at index 6, 7, 9 respectively.
Therefore, correct option is (C).
Alternative Approach: We can also solve this using elimination approach as:
Option (A) and (B) are incorrect as all keys are not inserted in hash table.
Option (D) is incorrect as some indexes in hash table have more than one key which never
happens using linear probing.
Remaining option is (C) which is the answer.
1346
Chapter 241. Practice Problems on Hashing
Type 3: Given a hash table with keys, verify/find possible sequence of keys
leading to hash table –
For a given hash table, we can verify which sequence of keys can lead to that hash table.
However, to find possible sequences leading to a given hash table, we need to consider all
possibilities.
Que – 3. A hash table of length 10 uses open addressing with hash function h(k)=k mod
10, and linear probing. After inserting 6 values into an empty hash table, the table is as
shown below.
Which one of the following choices gives a possible order in which the key values could have
been inserted in the table?
(A) 46, 42, 34, 52, 23, 33
(B) 34, 42, 23, 52, 33, 46
(C) 46, 34, 42, 23, 52, 33
(D) 42, 46, 33, 23, 34, 52
Solution: We will check whether sequence given in option A can lead to hash table given
in question. Option A inserts 46, 42, 34, 52, 23, 33 as:
For key 46, h(46) is 46%10 = 6. Therefore, 46 is placed at 6th index in the hash table.
For key 42, h(42) is 42%10 = 2. Therefore, 42 is placed at 2nd index in the hash table.
For key 34, h(34) is 34%10 = 4. Therefore, 34 is placed at 4th index in the hash table.
For key 52, h(52) is 52%10 = 2. However, index 2 is occupied with 42. Therefore, 52 is
placed at 3rd index in the hash table. But in given hash table, 52 is placed at 5th index.
Therefore, sequence in option A can’t generate hash table given in question.
In the similar way, we can check for other options as well which leads to answer as (C).
Que – 4. How many different insertion sequences of the key values using the same hash
function and linear probing will result in the hash table given in Question 3 above?
(A) 10
(B) 20
(C) 30
(D) 40
Solution: The first key which is not at the index computed by hash function is 52. It
means index 2, 3 and 4 were already occupied and therefore, key 52 is placed at index 5.
1347
Chapter 241. Practice Problems on Hashing
The keys 42, 23 and 34 are present at index 2, 3, and 4 respectively. As these keys are at
their correct position, their order of insertion does not matter. These 3 keys can be inserted
in 3! = 6 ways. Therefore, the sequence will be any order of (42, 23, 34) followed by 52.
The next key which is not at the index computed by hash function is 33. It means indexes
3 to 6 were already occupied and key 33 is placed at index 7. Therefore, it is the last key
to be inserted into hash table.
The key 46 is present at its correct position computed by hash function. Therefore, it can be
inserted at any place in the sequence before 33. The sequence excluding 33 has 4 elements
42, 23, 34, 52 which create 5 positions for 46 (3 in-between and 2 corners).
Total number of ways is: 6*5 =30
Type 4: Chaining based collision resolution technique –
In chaining based collision resolution technique, the keys generating same hash value are
placed in same bucket using pointers. The different types of questions based on chaining
technique are:
Que – 5. Consider a hash table with 100 slots. Collisions are resolved using chaining.
Assuming simple uniform hashing, what is the probability that the first 3 slots are unfilled
after the first 3 insertions? (GATE-CS-2014)
(A) (97 × 97 × 97)/100^3
(B) (99 × 98 × 97)/100^3
(C) (97 × 96 × 95)/100^3
(D) (97 × 96 × 95)/(3! × 100^3)
Solution: In uniform hashing, the function evenly distributes keys into slots of hash table.
Also, each key has an equal probability of being placed into a slot, being independent of the
other elements already placed.
Therefore, the probability of remaining first 3 slots empty for first insertion (choosing 4 to
100 slot) = 97/100. As next insertions are independent on previous insertion, the probability
for next insertions will also be 97/100. The required probability will be (97/100)^3.
Que – 6. Which one of the following hash functions on integers will distribute keys most
uniformly over 10 buckets numbered 0 to 9 for i ranging from 0 to 2020? (GATE-CS-2015)
(A) h(i) =i^2 mod 10
(B) h(i) =i^3 mod 10
(C) h(i) = (11 ∗ i^2) mod 10
(D) h(i) = (12 ∗ i) mod 10
Solution: In uniform distribution, the function evenly distributes keys into slots of hash
table.
For given hash functions, we have calculated hash values for keys 0 to 9 as:
1348
Chapter 241. Practice Problems on Hashing
As we can see from the table, i^3 mod10 is distributing evenly from indexes 0 to 9. Other
functions have not utilized all indexes.
Source
https://www.geeksforgeeks.org/practice-problems-on-hashing/
1349
Chapter 242
A naive method is to first construct the tree from given postorder and inorder, then use
simple recursive method to print preorder traversal of the constructed tree.
1350
Chapter 242. Preorder from Inorder and Postorder traversals
We can print preorder traversal without constructing the tree. The idea is, root is
always the first item in preorder traversal and it must be the last item in postorder traversal.
We first push right subtree to a stack, then left subtree and finally we push root. Finally
we print contents of stack. To find boundaries of left and right subtrees in post[] and in[],
we search root in in[], all elements before root in in[] are elements of left subtree and all
elements after root are elements of right subtree. In post[], all elements after index of root
in in[] are elements of right subtree. And elements before index (including the element at
index and excluding the first element) are elements of left subtree.
1351
Chapter 242. Preorder from Inorder and Postorder traversals
1352
Chapter 242. Preorder from Inorder and Postorder traversals
Output:
25 15 10 4 12 22 18 24 50 35 31 44 70 66 90
Time Complexity: The above function visits every node in array. For every visit, it calls
search which takes O(n) time. Therefore, overall time complexity of the function is O(n2 )
O(n) Solution
We can further optimize above solution to first hash all items of inorder traversal so that
we do not have to linearly search items. With hash table available to us, we can search an
item in O(1) time.
1353
Chapter 242. Preorder from Inorder and Postorder traversals
Output:
25 15 10 4 12 22 18 24 50 35 31 44 70 66 90
1354
Chapter 242. Preorder from Inorder and Postorder traversals
Source
https://www.geeksforgeeks.org/preorder-from-inorder-and-postorder-traversals/
1355
Chapter 243
A Simple Solution is to use twp nested loops. The outer loop picks an element one by
one starting from the leftmost element. The inner loop checks if the element is present on
left side of it. If present, then ignores the element, else prints the element. Following is the
implementation of the simple algorithm.
C++
1356
Chapter 243. Print All Distinct Elements of a given integer array
void printDistinct(int arr[], int n)
{
// Pick all elements one by one
for (int i=0; i<n; i++)
{
// Check if the picked element is already printed
int j;
for (j=0; j<i; j++)
if (arr[i] == arr[j])
break;
// If not printed earlier, then print it
if (i == j)
cout << arr[i] << " ";
}
}
// Driver program to test above function
int main()
{
int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
int n = sizeof(arr)/sizeof(arr[0]);
printDistinct(arr, n);
return 0;
}
Java
1357
Chapter 243. Print All Distinct Elements of a given integer array
Python3
1358
Chapter 243. Print All Distinct Elements of a given integer array
C#
PHP
<?php
// PHP program to print all distinct
1359
Chapter 243. Print All Distinct Elements of a given integer array
Output:
6 10 5 4 9 120
Time Complexity of above solution is O(n2 ). We can Use Sorting to solve the problem
in O(nLogn) time. The idea is simple, first sort the array so that all occurrences of every
element become consecutive. Once the occurrences become consecutive, we can traverse
the sorted array and print distinct elements in O(n) time. Following is the implementation
of the idea.
C++
1360
Chapter 243. Print All Distinct Elements of a given integer array
Java
1361
Chapter 243. Print All Distinct Elements of a given integer array
// print last occurrence of
// the current element
System.out.print(arr[i] +" ");
}
}
// Driver program
public static void main (String[] args)
{
int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};
int n = arr.length;
printDistinct(arr, n);
}
}
// This code is contributed by vt_m
C#
1362
Chapter 243. Print All Distinct Elements of a given integer array
// Driver program
public static void Main ()
{
int []arr = {6, 10, 5, 4, 9, 120, 4, 6, 10};
int n = arr.Length;
printDistinct(arr, n);
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to print all distinct
// elements in a given array
function printDistinct( $arr, $n)
{
// First sort the array so
// that all occurrences
// become consecutive
sort($arr);
// Traverse the sorted array
for ($i = 0; $i < $n; $i++)
{
// Move the index ahead
// while there are duplicates
while ($i < $n - 1 and
$arr[$i] == $arr[$i + 1])
$i++;
// print last occurrence
// of the current element
echo $arr[$i] , " ";
}
}
// Driver Code
$arr = array(6, 10, 5, 4, 9, 120, 4, 6, 10);
$n = count($arr);
printDistinct($arr, $n);
1363
Chapter 243. Print All Distinct Elements of a given integer array
Output:
4 5 6 9 10 120
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the
given array from left to right and keep track of visited elements in a hash table. Following
is Java implementation of the idea.
Output:
10 5 3 4 6
One more advantage of hashing over sorting is, the elements are printed in same order as
they are in input array.
Improved By : Sam007, nitin mittal, vt_m
1364
Chapter 243. Print All Distinct Elements of a given integer array
Source
https://www.geeksforgeeks.org/print-distinct-elements-given-integer-array/
1365
Chapter 244
Examples:
Input : GEEKSFORGEEKS
Output : EKSFORG
Input : ABDEFGABEF
Output : BDEFGA
Approach: The idea is to traverse the string and for each already visited character store its
last occurrence in a hash table(Here unordered_map is used as hash with key as character
and value as its last position). The variable st stores starting point of current substring,
maxlen stores length of maximum length substring and start stores starting index of max-
imum length substring. While traversing the string, check whether current character is
present in hash table or not. If it is not present, then store current character in hash table
with value as current index. If it is already present in hash table, this means the current
character could repeat in current substring. For this check if the previous occurrence of char-
acter is before or after the starting point st of current substring. If it is before st, then only
update the value in hash table. If it is after st, then find length of current substring currlen
as i-st, where i is current index. Compare currlen with maxlen. If maxlen is less than cur-
rlen, then update maxlen as currlen and start as st. After complete traversal of string, the
required longest substring without repeating characters is from s[start] to s[start+maxlen-1].
1366
Chapter 244. Print Longest substring without repeating characters
Implementation:
1367
Chapter 244. Print Longest substring without repeating characters
Output: EKSFORG
1368
Chapter 244. Print Longest substring without repeating characters
Source
https://www.geeksforgeeks.org/print-longest-substring-without-repeating-characters/
1369
Chapter 245
1
/ \
2 3
/ \ / \
4 5 6 7
Top view of the above binary tree is
4 2 1 3 7
1
/ \
2 3
\
4
\
5
\
6
Top view of the above binary tree is
2 1 3 6
1370
Chapter 245. Print Nodes in Top View of Binary Tree
The idea is to do something similar to vertical Order Traversal. Like vertical Order Traversal,
we need to nodes of same horizontal distance together. We do a level order traversal so that
the topmost node at a horizontal node is visited before any other node of same horizontal
distance below it. Hashing is used to check if a node at given horizontal distance is seen or
not.
C++
1371
Chapter 245. Print Nodes in Top View of Binary Tree
if (n->right != NULL)
q.push(make_pair(n->right, val + 1));
}
}
// function to create a new node
struct Node* newNode(int key)
{
struct Node* node = new Node;
node->data = key;
node->left = node->right = NULL;
return node;
}
// main function
int main()
{
/* Create following Binary Tree
1
/ \
2 3
\
4
\
5
\
6*/
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->left->right->right = newNode(5);
root->left->right->right->right = newNode(6);
topView(root);
return 0;
}
/* This code is contributed by Niteesh Kumar */
Java
1372
Chapter 245. Print Nodes in Top View of Binary Tree
class TreeNode {
// Members
int key;
TreeNode left, right;
// Constructor
public TreeNode(int key)
{
this.key = key;
left = right = null;
}
}
// A class to represent a queue item. The queue is used to do Level
// order traversal. Every Queue item contains node and horizontal
// distance of node from root
class QItem {
TreeNode node;
int hd;
public QItem(TreeNode n, int h)
{
node = n;
hd = h;
}
}
// Class for a Binary Tree
class Tree {
TreeNode root;
// Constructors
public Tree() { root = null; }
public Tree(TreeNode n) { root = n; }
// This method prints nodes in top view of binary tree
public void printTopView()
{
// base case
if (root == null) {
return;
}
// Creates an empty hashset
HashSet<Integer> set = new HashSet<>();
// Create a queue and add root to it
Queue<QItem> Q = new LinkedList<QItem>();
Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
1373
Chapter 245. Print Nodes in Top View of Binary Tree
// Standard BFS or level order traversal loop
while (!Q.isEmpty()) {
// Remove the front item and get its details
QItem qi = Q.remove();
int hd = qi.hd;
TreeNode n = qi.node;
// If this is the first node at its horizontal distance,
// then this node is in top view
if (!set.contains(hd)) {
set.add(hd);
System.out.print(n.key + " ");
}
// Enqueue left and right children of current node
if (n.left != null)
Q.add(new QItem(n.left, hd - 1));
if (n.right != null)
Q.add(new QItem(n.right, hd + 1));
}
}
}
// Driver class to test above methods
public class Main {
public static void main(String[] args)
{
/* Create following Binary Tree
1
/ \
2 3
\
4
\
5
\
6*/
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(4);
root.left.right.right = new TreeNode(5);
root.left.right.right.right = new TreeNode(6);
Tree t = new Tree(root);
System.out.println("Following are nodes in top view of Binary Tree");
t.printTopView();
}
1374
Chapter 245. Print Nodes in Top View of Binary Tree
Output:
Time Complexity of the above implementation is O(n) where n is number of nodes in given
binary tree. The assumption here is that add() and contains() methods of HashSet work in
O(1) time.
This article is contributed by Rohan. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Improved By : Aarsee
Source
https://www.geeksforgeeks.org/print-nodes-top-view-binary-tree/
1375
Chapter 246
Print a Binary Tree in Vertical Order | Set 2 (Map based Method) - GeeksforGeeks
Given a binary tree, print it vertically. The following example illustrates vertical order
traversal.
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
1376
Chapter 246. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
We have discussed a O(n2 ) solution in the previous post. In this post, an efficient solution
based on hash map is discussed. We need to check the Horizontal Distances from root for
all nodes. If two nodes have the same Horizontal Distance (HD), then they are on same
vertical line. The idea of HD is simple. HD for root is 0, a right edge (edge connecting
to right subtree) is considered as +1 horizontal distance and a left edge is considered as -1
horizontal distance. For example, in the above tree, HD for Node 4 is at -2, HD for Node 2
is -1, HD for 5 and 6 is 0 and HD for node 7 is +2.
We can do preorder traversal of the given Binary Tree. While traversing the tree, we can
recursively calculate HDs. We initially pass the horizontal distance as 0 for root. For left
subtree, we pass the Horizontal Distance as Horizontal distance of root minus 1. For right
subtree, we pass the Horizontal Distance as Horizontal Distance of root plus 1. For every
HD value, we maintain a list of nodes in a hasp map. Whenever we see a node in traversal,
we go to the hash map entry and add the node to the hash map using HD as a key in map.
Following is C++ implementation of the above method. Thanks to Chirag for providing
the below C++ implementation.
1377
Chapter 246. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
C++
1378
Chapter 246. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
Java
1379
Chapter 246. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
// Constructor
Node(int data)
{
key = data;
left = null;
right = null;
}
}
// Utility function to store vertical order in map 'm'
// 'hd' is horizontal distance of current node from root.
// 'hd' is initially passed as 0
static void getVerticalOrder(Node root, int hd,
TreeMap<Integer,Vector<Integer>> m)
{
// Base case
if(root == null)
return;
//get the vector list at 'hd'
Vector<Integer> get = m.get(hd);
// Store current node in map 'm'
if(get == null)
{
get = new Vector<>();
get.add(root.key);
}
else
get.add(root.key);
m.put(hd, get);
// Store nodes in left subtree
getVerticalOrder(root.left, hd-1, m);
// Store nodes in right subtree
getVerticalOrder(root.right, hd+1, m);
}
// The main function to print vertical oder of a binary tree
// with given root
static void printVerticalOrder(Node root)
{
// Create a map and store vertical oder in map using
// function getVerticalOrder()
TreeMap<Integer,Vector<Integer>> m = new TreeMap<>();
1380
Chapter 246. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
int hd =0;
getVerticalOrder(root,hd,m);
// Traverse the map and print nodes at every horigontal
// distance (hd)
for (Entry<Integer, Vector<Integer>> entry : m.entrySet())
{
System.out.println(entry.getValue());
}
}
// Driver program to test above functions
public static void main(String[] args) {
// TO DO Auto-generated method stub
Node 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);
System.out.println("Vertical Order traversal is");
printVerticalOrder(root);
}
}
// This code is contributed by Sumit Ghosh
Python
1381
Chapter 246. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
1382
Chapter 246. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
Output:
Time Complexity of hashing based solution can be considered as O(n) under the assump-
tion that we have good hashing function that allows insertion and retrieval operations in
O(1) time. In the above C++ implementation, map of STL is used. map in STL is typically
implemented using a Self-Balancing Binary Search Tree where all operations take O(Logn)
time. Therefore time complexity of above implementation is O(nLogn).
Note that the above solution may print nodes in same vertical order as they
appear in tree. For example, the above program prints 12 before 9. See this for a sample
run.
1
/
2 3
/ /
4 5 6 7
/
8 10 9
11
12
Refer below post for level order traversal based solution. The below post makes sure that
nodes of a vertical line are printed in same order as they appear in tree.
Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
Source
https://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/
1383
Chapter 247
Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal) - GeeksforGeeks
Given a binary tree, print it vertically. The following example illustrates vertical order
traversal.
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
1384
Chapter 247. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
1
/ \
2 3
/ \ / \
4 5 6 7
\ / \
8 10 9
1385
Chapter 247. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
\
11
\
12
If we use level order traversal, we can make sure that if a node like 12 comes below in same
vertical line, it is printed after a node like 9 which comes above in vertical line.
C++
1386
Chapter 247. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
1387
Chapter 247. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
Python3
1388
Chapter 247. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
hd_node[root] = 0
m[0] = [root.data]
# loop will run while queue is not empty
while len(queue) > 0:
# dequeue node from queue
temp = queue.pop(0)
if temp.left:
# Enqueue left child
queue.append(temp.left)
# Store the horizontal distance of left node
# hd(left child) = hd(parent) -1
hd_node[temp.left] = hd_node[temp] - 1
hd = hd_node[temp.left]
if m.get(hd) is None:
m[hd] = []
m[hd].append(temp.left.data)
if temp.right:
# Enqueue right child
queue.append(temp.right)
# store the horizontal distance of right child
# hd(right child) = hd(parent) + 1
hd_node[temp.right] = hd_node[temp] + 1
hd = hd_node[temp.right]
if m.get(hd) is None:
m[hd] = []
m[hd].append(temp.right.data)
# Sort the map according to horizontal distance
sorted_m = collections.OrderedDict(sorted(m.items()))
# Traverse the sorted map and print nodes at each horizontal distance
for i in sorted_m.values():
for j in i:
print(j, " ", end="")
print()
# Driver program to check above function
1389
Chapter 247. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
"""
Constructed binary tree is
1
/ \
2 3
/ \ / \
4 5 6 7
\ / \
8 10 9
\
11
\
12
"""
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right =Node(8)
root.right.right.left = Node(10)
root.right.right.right = Node(9)
root.right.right.left.right = Node(11)
root.right.right.left.right.right = Node(12)
print("Vertical order traversal is ")
verticalTraverse(root)
# This code is contributed by Shweta Singh
Output:
Time Complexity of above implementation is O(n Log n). Note that above implementation
uses map which is implemented using self-balancing BST.
We can reduce time complexity to O(n) using unordered_map. To print nodes in desired
order, we can have 2 variables denoting min and max horizontal distance. We can simply
1390
Chapter 247. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
iterate from min to max horizontal distance and get corresponding values from Map. So it
is O(n)
Auxiliary Space : O(n)
Improved By : shweta44
Source
https://www.geeksforgeeks.org/print-a-binary-tree-in-vertical-order-set-3-using-level-order-traversal/
1391
Chapter 248
Print all Subsequences of String which Start with Vowel and End with Consonant. - Geeks-
forGeeks
Given a string return all possible subsequences which start with vowel and end with con-
sonant. A String is a subsequence of a given String, that is generated by deleting some
character of a given string without changing its order.
Examples:
Input : 'abc'
Output : ab, ac, abc
Input : 'aab'
Output : ab, aab
1392
Chapter 248. Print all Subsequences of String which Start with Vowel and End with
Consonant.
1393
Chapter 248. Print all Subsequences of String which Start with Vowel and End with
Consonant.
}
}
// Utility method to check vowel
static boolean isVowel(char c)
{
return (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u');
}
// Utility method to check consonant
static boolean isConsonant(char c)
{
return !(c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u');
}
// Driver code
public static void main(String[] args)
{
String s = "xabcef";
subsequence(s);
System.out.println(st);
}
}
Output:
[ef, ab, ac, aef, abc, abf, af, acf, abcef, abcf, acef, abef]
Source
https://www.geeksforgeeks.org/subsequences-string-start-vowel-end-consonant/
1394
Chapter 249
Examples :
Input : arr[] = {1, 5, 7, -1, 5},
sum = 6
Output : (1, 5) (7, -1) (1, 5)
A simple solution is be traverse each element and check if there’s another number in the
array which can be added to it to give sum.
C++
1395
Chapter 249. Print all pairs with given sum
Java
1396
Chapter 249. Print all pairs with given sum
{
int arr[] = {1, 5, 7, -1, 5};
int n = arr.length;
int sum = 6;
printPairs(arr, n, sum);
}
}
// This code is contributed
// by Smitha
Python 3
# Python 3 implementation
# of simple method to find
# print pairs with given sum.
# Returns number of pairs
# in arr[0..n-1] with sum
# equal to 'sum'
def printPairs(arr, n, sum):
# count = 0
# Consider all possible
# pairs and check their sums
for i in range(0, n ):
for j in range(i + 1, n ):
if (arr[i] + arr[j] == sum):
print("(" , arr[i] ,
", ", arr[j],
")", sep = "")
# Driver Code
arr = [1, 5, 7, -1, 5]
n = len(arr)
sum = 6
printPairs(arr, n, sum)
# This code is contributed
# by Smitha
C#
// C# implementation of simple
// method to find print pairs
1397
Chapter 249. Print all pairs with given sum
PHP
<?php
// PHP implementation of simple
// method to find print pairs
// with given sum.
// Returns number of pairs in
// arr[0..n-1] with sum equal
// to 'sum'
function printPairs($arr, $n, $sum)
1398
Chapter 249. Print all pairs with given sum
{
// Initialize result
$count = 0;
// Consider all possible
// pairs and check their sums
for ($i = 0; $i < $n; $i++)
for ( $j = $i + 1; $j < $n; $j++)
if ($arr[$i] + $arr[$j] == $sum)
echo "(" , $arr[$i] , ", ",
$arr[$j] , ")" ,"\n";
}
// Driver Code
$arr = array (1, 5, 7, -1, 5);
$n = sizeof($arr);
$sum = 6;
printPairs($arr, $n, $sum);
// This code is contributed by m_kit
?>
Output :
(1, 5)
(1, 5)
(7, -1)
1399
Chapter 249. Print all pairs with given sum
Output :
(1, 5)
(7, -1)
(1, 5)
Source
https://www.geeksforgeeks.org/print-all-pairs-with-given-sum/
1400
Chapter 250
1401
Chapter 250. Print all subarrays with 0 sum
1402
Chapter 250. Print all subarrays with 0 sum
}
// Utility function to print all subarrays with sum 0
void print(vector<pair<int, int>> out)
{
for (auto it = out.begin(); it != out.end(); it++)
cout << "Subarray found from Index " <<
it->first << " to " << it->second << endl;
}
// Driver code
int main()
{
int arr[] = {6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7};
int n = sizeof(arr)/sizeof(arr[0]);
vector<pair<int, int> > out = findSubArrays(arr, n);
// if we didn’t find any subarray with 0 sum,
// then subarray doesn’t exists
if (out.size() == 0)
cout << "No subarray exists";
else
print(out);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/print-all-subarrays-with-0-sum/
1403
Chapter 251
A simple solution is to run three nested loops to generate all triplets and for every triplet,
check if it forms AP or not. Time complexity of this solution is O(n3 )
1404
Chapter 251. Print all triplets in sorted array that form AP
A better solution is to use hashing. We traverse array from left to right. We consider
every element as middle and all elements after it as next element. To search the previous
element, we use hash table.
C++
Java
1405
Chapter 251. Print all triplets in sorted array that form AP
1406
Chapter 251. Print all triplets in sorted array that form AP
// This code is contributed by
// Manish Shaw(manishshaw1)
Python3
C#
1407
Chapter 251. Print all triplets in sorted array that form AP
1408
Chapter 251. Print all triplets in sorted array that form AP
// Manish Shaw(manishshaw1)
PHP
<?php
// PHP program to pr$all
// triplets in given array
// that form Arithmetic
// Progression
// Function to print
// all triplets in
// given sorted array
// that forms AP
function printAllAPTriplets($arr, $n)
{
$s = array();
for ($i = 0; $i < $n - 1; $i++)
{
for ($j = $i + 1;
$j < $n; $j++)
{
// Use hash to find if
// there is a previous
// element with difference
// equal to arr[j] - arr[i]
$diff = $arr[$j] - $arr[$i];
if (in_array($arr[$i] -
$diff, $arr))
echo(($arr[$i] - $diff) .
" " . $arr[$i] .
" " . $arr[$j] . "\n");
}
array_push($s, $arr[$i]);
}
}
// Driver code
$arr = array(2, 6, 9, 12, 17,
22, 31, 32, 35, 42);
$n = count($arr);
printAllAPTriplets($arr, $n);
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
1409
Chapter 251. Print all triplets in sorted array that form AP
Output :
6 9 12
2 12 22
12 17 22
2 17 32
12 22 32
9 22 35
2 22 42
22 32 42
C++
1410
Chapter 251. Print all triplets in sorted array that form AP
Java
1411
Chapter 251. Print all triplets in sorted array that form AP
{
// if a triplet is found
if (arr[j] + arr[k] == 2 * arr[i])
{
System.out.println(arr[j] +" " +
arr[i]+ " " + arr[k]);
// Since elements are distinct,
// arr[k] and arr[j] cannot form
// any more triplets with arr[i]
k++;
j--;
}
// If middle element is more move to
// higher side, else move lower side.
else if (arr[j] + arr[k] < 2 * arr[i])
k++;
else
j--;
}
}
}
// Driver code
public static void main (String[] args)
{
int arr[] = { 2, 6, 9, 12, 17,
22, 31, 32, 35, 42 };
int n = arr.length;
findAllTriplets(arr, n);
}
}
// This code is contributed by vt_m.
Python 3
1412
Chapter 251. Print all triplets in sorted array that form AP
C#
// C# implementation to print
// all the triplets in given array
// that form Arithmetic Progression
using System;
class GFG
{
// Function to print all triplets in
// given sorted array that forms AP
1413
Chapter 251. Print all triplets in sorted array that form AP
1414
Chapter 251. Print all triplets in sorted array that form AP
PHP
<?php
// PHP implementation to print
// all the triplets in given array
// that form Arithmetic Progression
// Function to print all triplets in
// given sorted array that forms AP
function findAllTriplets($arr, $n)
{
for ($i = 1; $i < $n - 1; $i++)
{
// Search other two elements
// of AP with arr[i] as middle.
for ($j = $i - 1, $k = $i + 1;
$j >= 0 && $k < $n�
{
// if a triplet is found
if ($arr[$j] + $arr[$k] == 2 *
$arr[$i])
{
echo $arr[$j] ." " .
$arr[$i]. " " .
$arr[$k] . "\n";
// Since elements are distinct,
// arr[k] and arr[j] cannot form
// any more triplets with arr[i]
$k++;
$j--;
}
// If middle element is more move to
// higher side, else move lower side.
else if ($arr[$j] + $arr[$k] < 2 *
$arr[$i])
$k++;
else
$j--;
}
}
}
// Driver code
$arr = array(2, 6, 9, 12, 17,
1415
Chapter 251. Print all triplets in sorted array that form AP
Output :
6 9 12
2 12 22
12 17 22
2 17 32
12 22 32
9 22 35
2 22 42
22 32 42
Source
https://www.geeksforgeeks.org/print-triplets-sorted-array-form-ap/
1416
Chapter 252
C++
1417
Chapter 252. Print all triplets with given sum
Java
1418
Chapter 252. Print all triplets with given sum
{
System.out.println(arr[i]+ " "+
arr[j] +" "+
arr[k] );
}
}
}
}
}
// Driver code
public static void main (String[] args)
{
int arr[] = {0, -1, 2, -3, 1};
int n = arr.length;
findTriplets(arr, n, -2);
}
}
// This code is contributed by m_kit
Python 3
1419
Chapter 252. Print all triplets with given sum
C#
// A simple C# program
// to find three elements
// whose sum is equal to
// given sum
using System;
class GFG
{
// Prints all triplets in
// arr[] with given sum
static void findTriplets(int []arr,
int n, int sum)
{
for (int i = 0;
i < n - 2; i++)
{
for (int j = i + 1;
j < n - 1; j++)
{
for (int k = j + 1;
k < n; k++)
{
if (arr[i] + arr[j] + arr[k] == sum)
{
Console.WriteLine(arr[i]+ " "+
arr[j] +" "+
arr[k] );
}
}
}
}
}
// Driver code
static public void Main ()
{
int []arr = {0, -1, 2, -3, 1};
int n = arr.Length;
findTriplets(arr, n, -2);
}
}
// This code is contributed by akt_mit
PHP
1420
Chapter 252. Print all triplets with given sum
<?php
// A simple PHP program to
// find three elements whose
// sum is equal to given sum
// Prints all triplets in
// arr[] with given sum
function findTriplets($arr, $n, $sum)
{
for ($i = 0; $i < $n - 2; $i++)
{
for ($j = $i + 1; $j < $n - 1; $j++)
{
for ($k = $j + 1; $k < $n; $k++)
{
if ($arr[$i] + $arr[$j] +
$arr[$k] == $sum)
{
echo $arr[$i] , " ",
$arr[$j] , " ",
$arr[$k] , "\n";
}
}
}
}
}
// Driver code
$arr = array (0, -1, 2, -3, 1);
$n = sizeof($arr);
findTriplets($arr, $n, -2);
// This code is contributed by aj_36
?>
Output :
0 -3 1
-1 2 -3
1421
Chapter 252. Print all triplets with given sum
C++
Output:
-3 0 1
2 -1 -3
1422
Chapter 252. Print all triplets with given sum
C++
1423
Chapter 252. Print all triplets with given sum
l++;
// if sum is greater than given sum, then
// decrement in right side
else
r--;
}
}
}
// Driver code
int main()
{
int arr[] = { 0, -1, 2, -3, 1 };
int sum = -2;
int n = sizeof(arr) / sizeof(arr[0]);
findTriplets(arr, n, sum);
return 0;
}
Java
1424
Chapter 252. Print all triplets with given sum
C#
1425
Chapter 252. Print all triplets with given sum
// function to print
// triplets with given sum
static void findTriplets(int[] arr,
int n, int sum)
{
// sort array elements
Array.Sort(arr);
for (int i = 0; i < n - 1; i++)
{
// initialize left and right
int l = i + 1;
int r = n - 1;
int x = arr[i];
while (l < r)
{
if (x + arr[l] + arr[r] == sum)
{
// print elements if it's
// sum is given sum.
Console.WriteLine(x + " " + arr[l] +
" " + arr[r]);
l++;
r--;
}
// If sum of three elements
// is less than 'sum' then
// increment in left
else if (x + arr[l] +
arr[r] < sum)
l++;
// if sum is greater than
// given sum, then decrement
// in right side
else
r--;
}
}
}
// Driver code
static int Main()
{
int[] arr = new int[]{ 0, -1, 2, -3, 1 };
int sum = -2;
1426
Chapter 252. Print all triplets with given sum
int n = arr.Length;
findTriplets(arr, n, sum);
return 0;
}
}
// This code is contributed by rahul
PHP
<?php
// PHP program to find triplets
// in a given array whose sum
// is given sum.
// function to print triplets
// with given sum
function findTriplets($arr, $n, $sum)
{
// sort array elements
sort($arr);
for ($i = 0; $i < $n - 1; $i++)
{
// initialize left and right
$l = $i + 1;
$r = $n - 1;
$x = $arr[$i];
while ($l < $r)
{
if ($x + $arr[$l] +
$arr[$r] == $sum)
{
// print elements if it's
// sum is given sum.
echo $x, " ", $arr[$l],
" ", $arr[$r], "\n";
$l++;
$r--;
}
// If sum of three elements
// is less than 'sum' then
// increment in left
else if ($x + $arr[$l] +
$arr[$r] < $sum)
$l++;
1427
Chapter 252. Print all triplets with given sum
Output:
-3 -1 2
-3 0 1
Source
https://www.geeksforgeeks.org/print-all-triplets-with-given-sum/
1428
Chapter 253
Print array elements that are divisible by at-least one other - GeeksforGeeks
Given an array of length N that contains only integers, the task is to print the special
numbers of array. A number in this array is called Special number if it is divisible by at
least one other number in the array.
Examples :
Input : 1 2 3
Output : 2 3
Explanation : both 2 and 3 are divisible by 1.
Input : 2 3 4 6 8 9
Output : 4 6 8 9
Explanation : 2 and 3 are not divisible by any other element. Rest of the element
are divisible by at-least 1 element. 6 is divisible by both 2 and 3, 4 divisible by
2, 8 divisible by 2 and 4 both, 9 divisible by 3.
Input : 3 5 7 11
Output :
Explanation : all elements are relatively prime so no special number.
A simple solution is to traverse through all elements, then check for every element if it is
divisible by any other. Time complexity of this solution is O(n2 )
Another solution that works better when there are many elements with not
very big values. Store all array elements into hash and find out the max element in array
then up-to max element find out the multiples of a given number then if multiple of array
element is in hash then that number is divisible by at-least one element of array .To remove
duplicate values we store the value into set because if array has 2, 3 and 6 then only 6 is
divisible by at-least one element of array, both 2 and 3 divide 6 so 6 will be stored only one
1429
Chapter 253. Print array elements that are divisible by at-least one other
time.
C++
1430
Chapter 253. Print array elements that are divisible by at-least one other
// Driver code
int main()
{
int arr[] = { 2, 3, 8, 6, 9, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
divisibilityCheck(arr, n);
return 0;
}
Java
1431
Chapter 253. Print array elements that are divisible by at-least one other
if (arr.get(i) != 0)
// checking the factor
// of current element
for (int j = arr.get(i) * 2;
j <= max_ele;
j += arr.get(i))
{
// if factor is already
// part of array element
// then store it
if (s.contains(j))
res.add(j);
}
}
// displaying elements that
// are divisible by at least
// one other in array
List<Integer> list =
new ArrayList<Integer>(res);
Collections.reverse(list);
for (Integer temp : list)
System.out.print(temp + " ");
}
// Driver Code
public static void main(String args[])
{
List<Integer> arr = Arrays.asList(2, 3, 8,
6, 9, 10);
int n = arr.size();
divisibilityCheck(arr, n);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
C#
1432
Chapter 253. Print array elements that are divisible by at-least one other
class GFG
{
// Function to find
// special numbers
static void divisibilityCheck(List<int> arr,
int n)
{
// Storing all array elements
// in a hash and finding maximum
// element in array
List<int> s = new List<int>();
int max_ele = Int32.MinValue;
for (int i = 0; i < n; i++)
{
s.Add(arr[i]);
// finding maximum element of array
max_ele = Math.Max(max_ele,
arr[i]);
}
// traversing array element and
// storing the array multiples
// that are present in s in res.
HashSet<int> res = new HashSet<int>();
for (int i = 0; i < n; i++)
{
// Check for non-zero values only
if (arr[i] != 0)
// checking the factor
// of current element
for (int j = arr[i] * 2; j <= max_ele;
j += arr[i])
{
// if factor is already part
// of array element then store it
if (s.Contains(j))
res.Add(j);
}
}
// displaying elements that
// are divisible by at least
// one other in array
foreach (int i in res.Reverse())
1433
Chapter 253. Print array elements that are divisible by at-least one other
Output :
9 10 8 6
Note : If we need result to be printed in sorted order, we can use set in place of un-
ordered_set.
Improved By : manishshaw1
Source
https://www.geeksforgeeks.org/divisibility-check/
1434
Chapter 254
Print n smallest elements from given array in their original order - GeeksforGeeks
We are given an array of m-elements, we need to find n smallest elements from the array
but they must be in the same order as they are in given array.
Examples:
Make a copy of original array and then sort copy array. After sorting the copy array, save
all n smallest numbers. Further for each element in original array, check whether it is
in n-smallest number or not if it present in n-smallest array then print it otherwise move
forward.
1435
Chapter 254. Print n smallest elements from given array in their original order
Make copy_arr[]
sort(copy_arr)
For all elements in arr[] -
Output :
1 3 4 2 0
1436
Chapter 254. Print n smallest elements from given array in their original order
For making a copy of array we need space complexity of O(n) and then for sorting we will
need complexity of order O(n log n). Further for each element in arr[] we are performing
searching in copy_arr[], which will result O(n) for linear search but we can improve it by
applying binary search and hence our overall time complexity will be O(n log n).
Source
https://www.geeksforgeeks.org/find-n-smallest-element-given-array-order-array/
1437
Chapter 255
Approach:
C++
1438
Chapter 255. Print the last occurrence of elements in array in relative order
Java
1439
Chapter 255. Print the last occurrence of elements in array in relative order
C#
// C# program to print the
// last occurrence of every
// element in relative order
using System;
class GFG
{
// Function to print the last
// occurrence of every element
// in an array
public static void printLastOccurrence(int[] a,
int n)
{
HashMap map = new HashMap();
// iterate and store the last
1440
Chapter 255. Print the last occurrence of elements in array in relative order
5 6 1
Source
https://www.geeksforgeeks.org/print-the-last-occurrence-of-elements-in-array-in-relative-order/
1441
Chapter 256
1442
Chapter 256. Printing longest Increasing consecutive subsequence
1443
Chapter 256. Printing longest Increasing consecutive subsequence
Output:
3 4 5 6 7 8
Source
https://www.geeksforgeeks.org/printing-longest-increasing-consecutive-subsequence/
1444
Chapter 257
Input : alkasingh
Output : snlkihgaa
Input : nupursingh
Output : uusrpnnihg
Input : geeksforgeeks
Output : ssrokkggfeeee
1445
Chapter 257. Program to sort string in descending order
int main()
{
string s = "geeksforgeeks";
descOrder(s); // function call
return 0;
}
Python
Output:
ssrokkggfeeee
C++
1446
Chapter 257. Program to sort string in descending order
Output:
snlkihgaa
1447
Chapter 257. Program to sort string in descending order
Source
https://www.geeksforgeeks.org/program-sort-string-descending-order/
1448
Chapter 258
1449
Chapter 258. Queries to find distance between two nodes of a Binary tree
A sparse table will preprocess the minimum values given for an array in Nlogn space i.e.
each node will contain chain of values of log(i) length where i is the index of the ith node in
L array. Each entry in the sparse table says M[i][j] will represent the index of the minimum
value in the subarray starting at i having length 2^j.
The distance between two nodes can be obtained in terms of lowest common ancestor.
This problem can be breakdown into finding levels of each node, finding the Euler
tour of binary tree and building sparse table for LCA, these steps are explained below :
2. Find the LCA of two nodes in the binary tree in O(logn) by Storing Euler tour of
tree in array and computing two other arrays with the help of levels of each node and
Euler tour.
These steps are shown below:
(I) First, find Euler Tour of binary tree.
1450
Chapter 258. Queries to find distance between two nodes of a Binary tree
(III) Then, store First occurrences of all nodes of binary tree in Euler array.
3. Then build sparse table on L array and find the minimum value say X in range (H[A]
to H[B]). Then use the index of value X as an index to Euler array to get LCA, i.e.
Euler[index(X)].
Let, A=8 and B=5.
(I) H[8]= 1 and H[5]=2
(II) we get min value in L array between 1 and 2 as X=0, index=7
(III) Then, LCA= Euler[7], i.e LCA=1.
4. Finally, apply distance formula discussed above to get the distance between two nodes.
Source
https://www.geeksforgeeks.org/queries-find-distance-two-nodes-binary-tree/
1451
Chapter 259
Queries to find distance between two nodes of a Binary tree - O(logn) method - Geeks-
forGeeks
Given a binary tree, the task is to find the distance between two keys in a binary tree, no
parent pointers are given. Distance between two nodes is the minimum number of edges to
be traversed to reach one node from other.
This problem has been already discussed in previous post but it uses three traversals of
the Binary tree, one for finding Lowest Common Ancestor(LCA) of two nodes(let A and B)
and then two traversals for finding distance between LCA and A and LCA and B which has
O(n) time complexity. In this post, a method will be discussed that requires the O(log(n))
time to find LCA of two nodes.
1452
Chapter 259. Queries to find distance between two nodes of a Binary tree – O(logn)
method
The distance between two nodes can be obtained in terms of lowest common ancestor. Fol-
lowing is the formula.
1453
Chapter 259. Queries to find distance between two nodes of a Binary tree – O(logn)
method
2. Find the LCA of two nodes in binary tree in O(logn) by Storing Euler tour
of Binary tree in array and computing two other arrays with the help of
levels of each node and Euler tour.
These steps are shown below:
(I) First, find Euler Tour of binary tree.
(III) Then, store First occurrences of all nodes of binary tree in Euler array.
H stores the indices of nodes from Euler array, so that range of query for
finding minimum can be minimized and their by further optimizing the
query time.
3. Then build segment tree on L array and take the low and high values
from H array that will give us the first occurrences of say Two nodes(A
and B) . Then, <strong>we query segment tree to find the minimum value
say X in range (H[A] to H[B]). Then we use the index of value X as
index to Euler array to get LCA, i.e. Euler[index(X)].
Let, A = 8 and B = 5.
(I) H[8] = 1 and H[5] =2
(II) Querying on Segment tree, we get min value in L array between 1 and
2 as X=0, index=7
(III) Then, LCA= Euler[7], i.e LCA = 1.
1454
Chapter 259. Queries to find distance between two nodes of a Binary tree – O(logn)
method
1455
Chapter 259. Queries to find distance between two nodes of a Binary tree – O(logn)
method
level[p.first->data] = p.second;
// If left child exits, put it in queue
// with current_level +1
if (p.first->left)
q.push({ p.first->left, p.second + 1 });
// If right child exists, put it in queue
// with current_level +1
if (p.first->right)
q.push({ p.first->right, p.second + 1 });
}
}
// Stores Euler Tour
int Euler[MAX];
// index in Euler array
int idx = 0;
// Find Euler Tour
void eulerTree(struct Node* root)
{
// store current node's data
Euler[++idx] = root->data;
// If left node exists
if (root->left) {
// traverse left subtree
eulerTree(root->left);
// store parent node's data
Euler[++idx] = root->data;
}
// If right node exists
if (root->right) {
// traverse right subtree
eulerTree(root->right);
// store parent node's data
Euler[++idx] = root->data;
}
}
// checks for visited nodes
1456
Chapter 259. Queries to find distance between two nodes of a Binary tree – O(logn)
method
int vis[MAX];
// Stores level of Euler Tour
int L[MAX];
// Stores indices of first occurrence
// of nodes in Euler tour
int H[MAX];
// Preprocessing Euler Tour for finding LCA
void preprocessEuler(int size)
{
for (int i = 1; i <= size; i++) {
L[i] = level[Euler[i]];
// If node is not visited before
if (vis[Euler[i]] == 0) {
// Add to first occurrence
H[Euler[i]] = i;
// Mark it visited
vis[Euler[i]] = 1;
}
}
}
// Stores values and positions
pair<int, int> seg[4 * MAX];
// Utility function to find minimum of
// pair type values
pair<int, int> min(pair<int, int> a,
pair<int, int> b)
{
if (a.first <= b.first)
return a;
else
return b;
}
// Utility function to build segment tree
pair<int, int> buildSegTree(int low, int high, int pos)
{
if (low == high) {
seg[pos].first = L[low];
seg[pos].second = low;
return seg[pos];
}
1457
Chapter 259. Queries to find distance between two nodes of a Binary tree – O(logn)
method
1458
Chapter 259. Queries to find distance between two nodes of a Binary tree – O(logn)
method
}
void preProcessing(Node* root, int N)
{
// Build Tree
eulerTree(root);
// Store Levels
FindLevels(root);
// Find L and H array
preprocessEuler(2 * N - 1);
// Build segment Tree
buildSegTree(1, 2 * N - 1, 1);
}
/* Driver function to test above functions */
int main()
{
int N = 8; // Number of nodes
/* Constructing tree given in the above figure */
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->right->left->right = newNode(8);
// Function to do all preprocessing
preProcessing(root, N);
cout << "Dist(4, 5) = " << findDistance(4, 5, 2 * N - 1) << "\n";
cout << "Dist(4, 6) = " << findDistance(4, 6, 2 * N - 1) << "\n";
cout << "Dist(3, 4) = " << findDistance(3, 4, 2 * N - 1) << "\n";
cout << "Dist(2, 4) = " << findDistance(2, 4, 2 * N - 1) << "\n";
cout << "Dist(8, 5) = " << findDistance(8, 5, 2 * N - 1) << "\n";
return 0;
}
Output:
Dist(4, 5) = 2
1459
Chapter 259. Queries to find distance between two nodes of a Binary tree – O(logn)
method
Dist(4, 6) = 4
Dist(3, 4) = 3
Dist(2, 4) = 1
Dist(8, 5) = 5
Source
https://www.geeksforgeeks.org/queries-find-distance-two-nodes-binary-tree-ologn-method/
1460
Chapter 260
Queries to insert, delete one occurrence of a number and print the least and most frequent
element - GeeksforGeeks
Given Q queries of type 1, 2, 3 and 4 as described below.
Input:
Query1: 1 6
Query2: 1 6
Query3: 1 7
Query4: 3
Query5: 1 7
Query6: 2 7
Query7: 1 7
1461
Chapter 260. Queries to insert, delete one occurrence of a number and print the least and
most frequent element
Query8: 3
Query9: 4
Output:
7
7
6
While answering Query4, the frequency of 6 is 2 and that of
7 is 1, hence the least frequent element is 7.
In Query8, the least frequent element is 6 and 7, so print the largest.
In Query9, the most frequent element is 6 and 7, so print the smallest.
A naive approach is to use any Data-Structures(array, vector, ..) and store all the elements.
Using a hash-table, the frequency of every element can be stored. While processing the Query
of type-2, delete one occurrence of that element from the DS in which the element has been
stored. The queries of type-3 and type-4 can be answered by traversing the hash-table. The
time complexity will be O(N) per query, where N is the number of elements till then in the
DS.
An efficient approach will be to use set container to answer every query. Using two sets,
one hash-table the above problem can be solved in O(log n) per query. Two sets s1 and
s2 are used, one stores the {num, frequency}, while the other stores the {frequency,
number}. A hash-map is used which stores the frequency of each number. Design the set
s2 using operator overloading such that it is sorted in ascending order of the first elements.
If the first element appears to be same of one or more element, the set will be sorted in
descending order of the second elements. The user-defined operating-overloading function
thus will be:
• Type1: Check using hash-table if the element exists. If it does not exist, then mark
the number in hash-table. Insert {num, 1} in set s1 and {1, num} in set2 us-
inginsert(). If it exists previously, then get the frequency from hash-table and delete
{num, frequency} from set1 and {frequency, num} from set2 using find() and
erase() function. Insert {num, frequency+1} in set1 and {frequency+1, num}
in set2. Also, increase the count in hash-table.
• Type2: Follow the same process as above in query type1. Ony difference is to decrease
the count in hash-table and insert {num, frequency-1} in set1 and {frequency-1,
num} in set2.
• Type3: Print the beginning element which can be obtained using begin() function,
as the set has been designed in such a way that begin() returns the least frequent
element. If there are more than one, then it returns the largest.
1462
Chapter 260. Queries to insert, delete one occurrence of a number and print the least and
most frequent element
• Type4: Print the last element in the set which can be obtained using rbegin() function
in set.
1463
Chapter 260. Queries to insert, delete one occurrence of a number and print the least and
most frequent element
// deletes the pair from sets
s1.erase(it1);
s2.erase(it2);
// re-insert the pair by increasing
// frequency
s1.insert({ num, m[num] + 1 });
s2.insert({ m[num] + 1, num });
}
// if the element is not there in the list
else {
// insert the element with frequency 1
s1.insert({ num, 1 });
s2.insert({ 1, num });
}
// increase the count in hash-table
m[num] += 1;
}
// Function to process the query
// of type-2
void type2(int num)
{
// if the element exists
if (m[num]) {
// get the frequency of the element
int cnt = m[num];
// returns an iterator pointing to
// position where the pair is
auto it1 = s1.find({ num, cnt });
auto it2 = s2.find({ cnt, num });
// deletes the pair from sets
s1.erase(it1);
s2.erase(it2);
// re-insert the pair by increasing
// frequency
s1.insert({ num, m[num] - 1 });
s2.insert({ m[num] - 1, num });
// decrease the count
1464
Chapter 260. Queries to insert, delete one occurrence of a number and print the least and
most frequent element
m[num] -= 1;
}
}
// Function to process the query
// of type-3
int type3()
{
// if the set is not empty
// return the first element
if (!s1.empty()) {
auto it = s2.begin();
return it->second;
}
else
return -1;
}
// Function to process the query
// of type-4
int type4()
{
// if the set is not empty
// return the last element
if (!s1.empty()) {
auto it = s2.rbegin();
return it->second;
}
else
return -1;
}
// Driver Code
int main()
{
// Queries
// inserts 6, 6 and 7
type1(6);
type1(6);
type1(7);
// print the answer to query of type3
cout << type3() << endl;
1465
Chapter 260. Queries to insert, delete one occurrence of a number and print the least and
most frequent element
// inserts 7
type1(7);
// deletes one occurence of 7
type2(7);
// inserts 7
type1(7);
// print the answer to query of type3
cout << type3() << endl;
// print the answer to query of type4
cout << type4() << endl;
return 0;
}
Output:
7
7
6
Source
https://www.geeksforgeeks.org/queries-to-insert-delete-one-occurrence-of-a-number-and-print-the-least-and-most-f
1466
Chapter 261
Input : a a b c
Output : a -1 b b
Input : a a c
Output : a -1 c
We have already discussed a Doubly linked list based approach in the previous post.
Approach-
1. Create a count array of size 26(assuming only lower case characters are present) and
initialize it with zero.
2. Create a queue of char datatype.
3. Store each character in queue and increase its frequency in the hash array.
4. For every character of stream, we check front of the queue.
5. If the frequency of character at the front of queue is one, then that will be the first
non repeating character.
6. Else if frequency is more than 1, then we pop that element.
7. If queue became empty that means there are no non repeating character so we will
print -1.
1467
Chapter 261. Queue based approach for first non-repeating character in a stream
C++
1468
Chapter 261. Queue based approach for first non-repeating character in a stream
Java
1469
Chapter 261. Queue based approach for first non-repeating character in a stream
}
System.out.println();
}
// Driver function
public static void main(String[] args)
{
String str = "aabc";
firstNonRepeating(str);
}
}
//This code is Contributed by Sumit Ghosh
Output:
a -1 b b
Source
https://www.geeksforgeeks.org/queue-based-approach-for-first-non-repeating-character-in-a-stream/
1470
Chapter 262
Naive approach: is to traverse from left to right and update count variable whenever we
find the element.
Below is the code of Naive approach:-
C++
1471
Chapter 262. Range Queries for Frequencies of array elements
Java
1472
Chapter 262. Range Queries for Frequencies of array elements
Python3
C#
1473
Chapter 262. Range Queries for Frequencies of array elements
Output:
Frequency of 2 from 1 to 6 = 1
Frequency of 8 from 4 to 9 = 2
1474
Chapter 262. Range Queries for Frequencies of array elements
1. At first, we will store the position in map[] of every distinct element as a vector like
that
2. As we can see that elements in map[] are already in sorted order (Because we inserted
elements from left to right), the answer boils down to find the total count in that hash
map[] using binary search like method.
3. In C++ we can use lower_bound which will returns an iterator pointing to the first
element in the range [first, last] which has a value not less than ’left’. and upper_bound
returns an iterator pointing to the first element in the range [first,last) which has a
value greater than ’right’.
4. After that we just need to subtract the upper_bound() and lower_bound() result to
get the final answer. For example, suppose if we want to find the total count of 8 in
the range from [1 to 6], then the map[8] of lower_bound() function will return the
result 0 (pointing to 2) and upper_bound() will return 2 (pointing to 7), so we need
to subtract the both the result like 2 – 0 = 2 .
1475
Chapter 262. Range Queries for Frequencies of array elements
right)
- store[element].begin();
return b-a;
}
// Driver code
int main()
{
int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
int n = sizeof(arr) / sizeof(arr[0]);
// Storing the indexes of an element in the map
for (int i=0; i<n; ++i)
store[arr[i]].push_back(i+1); //starting index from 1
// Print frequency of 2 from position 1 to 6
cout << "Frequency of 2 from 1 to 6 = "
<< findFrequency(arr, n, 1, 6, 2) <<endl;
// Print frequency of 8 from position 4 to 9
cout << "Frequency of 8 from 4 to 9 = "
<< findFrequency(arr, n, 4, 9, 8);
return 0;
}
Output:
Frequency of 2 from 1 to 6 = 1
Frequency of 8 from 4 to 9 = 2
Source
https://www.geeksforgeeks.org/range-queries-for-frequencies-of-array-elements/
1476
Chapter 263
Approach:
1. Navigate the array.
2. Check if a[i] = -1, if yes then ignore it.
3. If a[i] != -1, Check if element a[i] is at its correct position (i=A[i]). If yes then ignore
it.
4. If a[i] != -1 and element a[i] is not at its correct position (i!=A[i]) then place it to its
correct position, but there are two conditions:
• Either A[i] is vacate, means A[i] = -1, then just put A[i] = i .
• OR A[i] is not vacate, means A[i] = x, then int y=x put A[i] = i. Now, we need
to place y to its correct place, so repeat from step 3.
1477
Chapter 263. Rearrange an array such that arr[i] = i
C++
1478
Chapter 263. Rearrange an array such that arr[i] = i
}
}
}
}
// Driver function.
int main()
{
int A[] = { -1, -1, 6, 1, 9,
3, 2, -1, 4, -1 };
int len = sizeof(A) / sizeof(A[0]);
fix(A, len);
for (int i = 0; i < len; i++)
cout << A[i] << " ";
}
// This code is contributed by Smitha Dinesh Semwal
Java
1479
Chapter 263. Rearrange an array such that arr[i] = i
Python3
1480
Chapter 263. Rearrange an array such that arr[i] = i
x = A[i];
# check if desired place
# is not vacate
while (A[x] != -1 and A[x] != x):
#store the value from
# desired place
y = A[x]
# place the x to its correct
# position
A[x] = x
# now y will become x, now
# search the place for x
x = y
# place the x to its correct
# position
A[x] = x;
# check if while loop hasn't
# set the correct value at A[i]
if (A[i] != i) :
# if not then put -1 at
# the vacated place
A[i] = -1;
# Driver function.
A = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ]
fix(A, len(A))
for i in range(0, len(A)):
print (A[i],end = ' ')
# This code is contributed by Saloni1297
C#
1481
Chapter 263. Rearrange an array such that arr[i] = i
1482
Chapter 263. Rearrange an array such that arr[i] = i
return A;
}
// Driver Code
static void Main()
{
int []A = new int[]{-1, -1, 6, 1, 9,
3, 2, -1, 4,-1};
Console.WriteLine(string.Join(",",
fix(A)));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
<?php
// PHP program for rearrange an
// array such that arr[i] = i.
// Function to rearrange an
// array such that arr[i] = i.
function fix(&$A, $len)
{
for ($i = 0; $i < $len; $i++)
{
if ($A[$i] != -1 &&
$A[$i] != $i)
{
$x = $A[$i];
// check if desired
// place is not vacate
while ($A[$x] != -1 &&
$A[$x] != $x)
{
// store the value
// from desired place
$y = $A[$x];
// place the x to its
// correct position
$A[$x] = $x;
// now y will become x,
// now search the place
1483
Chapter 263. Rearrange an array such that arr[i] = i
// for x
$x = $y;
}
// place the x to its
// correct position
$A[$x] = $x;
// check if while loop hasn't
// set the correct value at A[i]
if ($A[$i] != $i)
{
// if not then put -1
// at the vacated place
$A[$i] = -1;
}
}
}
}
// Driver Code
$A = array(-1, -1, 6, 1, 9,
3, 2, -1, 4, -1);
$len = count($A);
fix($A, $len);
for ($i = 0; $i < $len; $i++)
echo ($A[$i]." ");
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Output:
Java
1484
Chapter 263. Rearrange an array such that arr[i] = i
Python3
1485
Chapter 263. Rearrange an array such that arr[i] = i
C#
1486
Chapter 263. Rearrange an array such that arr[i] = i
{
// store the value from
// desired place
int y = A[x];
// place the x to its
// correct position
A[x] = x;
// now y will become x, now
// search the place for x
x = y;
}
// place the x to its
// correct position
A[x] = x;
// check if while loop hasn't
// set the correct value at A[i]
if (A[i] != i)
{
// if not then put -1 at
// the vacated place
A[i] = -1;
}
}
}
return A;
}
// Driver Code
static void Main()
{
int []A = new int[]{-1, -1, 6, 1, 9,
3, 2, -1, 4,-1};
Console.Write(string.Join(",", fix(A)));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output :
1487
Chapter 263. Rearrange an array such that arr[i] = i
Source
https://www.geeksforgeeks.org/rearrange-array-arri/
1488
Chapter 264
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++
1489
Chapter 264. Recaman’s sequence
Java
1490
Chapter 264. 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
1491
Chapter 264. Recaman’s sequence
Python 3
C#
1492
Chapter 264. 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
1493
Chapter 264. 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:
1494
Chapter 264. Recaman’s sequence
Optimizations :
We can us hashing to store previously computed values and can make this program work in
O(n) time.
1495
Chapter 264. Recaman’s sequence
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/recamans-sequence/
1496
Chapter 265
Remove minimum number of elements such that no common element exist in both array -
GeeksforGeeks
Given two arrays A[] and B[] consisting of n and m elements respectively. Find minimum
number of elements to remove from each array such that no common element exist in both.
Examples:
Input : A[] = { 1, 2, 3, 4}
B[] = { 2, 3, 4, 5, 8 }
Output : 3
We need to remove 2, 3 and 4 from any array.
Input : A[] = { 4, 2, 4, 4}
B[] = { 4, 3 }
Output : 1
We need to remove 4 from from B[]
Input : A[] = { 1, 2, 3, 4 }
B[] = { 5, 6, 7 }
Output : 0
There is no common element in both.
Count occurrence of each number in both array. If there is number in both array remove
number from array in which it appear less number of times add it to the result.
C++
1497
Chapter 265. Remove minimum number of elements such that no common element exist
in both array
Java
1498
Chapter 265. Remove minimum number of elements such that no common element exist
in both array
1499
Chapter 265. Remove minimum number of elements such that no common element exist
in both array
Output:
Source
https://www.geeksforgeeks.org/remove-minimum-number-elements-no-common-element-exist-array/
1500
Chapter 266
C++
1501
Chapter 266. Reorder the given string to form a K-concatenated string
1502
Chapter 266. Reorder the given string to form a K-concatenated string
}
}
}
string kString;
// append the single copy formed k times
for (int i = 0; i < k; i++) {
kString += single_copy;
}
return kString;
}
// Driver Code
int main()
{
string str = "gkeekgee";
int K = 2;
string kString = kStringGenerate(str, K);
cout << kString;
return 0;
}
Java
1503
Chapter 266. Reorder the given string to form a K-concatenated string
for (int i = 0; i < len; i++)
{
// for each character
// increment its frequency
// in the frequency array
frequency[str.charAt(i) - 'a']++;
}
// stores a single copy
// of a string, which on
// repeating forms a k-string
String single_copy = "";
// iterate over
// frequency array
for (int i = 0; i < 26; i++)
{
// if the character occurs
// in the string, check if
// it is divisible by k,
// if not divisible then
// k-string cant be formed
if (frequency[i] != 0)
{
if ((frequency[i] % k) != 0)
{
String ans = "Not Possible";
return ans;
}
else
{
// ith character occurs
// (frequency[i]/k) times in
// a single copy of k-string
int total_occurrences = (frequency[i] / k);
for (int j = 0;
j < total_occurrences; j++)
{
single_copy += (char)(i + 97);
}
}
}
1504
Chapter 266. Reorder the given string to form a K-concatenated string
}
String kString = "";
// append the single
// copy formed k times
for (int i = 0; i < k; i++)
{
kString += single_copy;
}
return kString;
}
// Driver Code
public static void main(String[] args)
{
String str = "gkeekgee";
int K = 2;
String kString = kStringGenerate(str, K);
System.out.print(kString);
}
}
Output:
eegkeegk
Source
https://www.geeksforgeeks.org/reorder-the-given-string-to-form-a-k-concatenated-string/
1505
Chapter 267
Algorithm:
One obvious approach to solve this problem would be to sort the input string and then
traverse through the sorted string to find the character which is occurring maximum number
of times. Let us see if we can improve on this. So we will use a technique called ‘Hashing’.
In this, when we traverse through the string, we would hash each character into an array of
ASCII characters.
Typically, ASCII characters are 256, so we use our Hash array size as 256. But if we know
that our input string will have characters with value from 0 to 127 only, we can limit Hash
array size as 128. Similarly, based on extra info known about input string, the Hash array
size can be limited to 26.
Implementation:
C++
1506
Chapter 267. Return maximum occurring character in an input string
// in a string
#include<bits/stdc++.h>
#define ASCII_SIZE 256
using namespace std;
char getMaxOccuringChar(char* str)
{
// Create array to keep the count of individual
// characters and initialize the array as 0
int count[ASCII_SIZE] = {0};
// Construct character count array from the input
// string.
int len = strlen(str);
for (int i=0; i<len; i++)
count[str[i]]++;
int max = -1; // Initialize max count
char result; // Initialize result
// Traversing through the string and maintaining
// the count of each character
for (int i = 0; i < len; i++) {
if (max < count[str[i]]) {
max = count[str[i]];
result = str[i];
}
}
return result;
}
// Driver program to test the above function
int main()
{
char str[] = "sample string";
cout << "Max occurring character is "
<< getMaxOccuringChar(str);
}
Java
1507
Chapter 267. Return maximum occurring character in an input string
Python
# Python program to return the maximum occuring character in the input string
ASCII_SIZE = 256
def getMaxOccuringChar(str):
# Create array to keep the count of individual characters
# Initialize the count array to zero
count = [0] * ASCII_SIZE
# Utility variables
max = -1
1508
Chapter 267. Return maximum occurring character in an input string
c = ''
# Traversing through the string and maintaining the count of
# each character
for i in str:
count[ord(i)]+=1;
for i in str:
if max < count[ord(i)]:
max = count[ord(i)]
c = i
return c
# Driver program to test the above function
str = "sample string"
print "Max occurring character is " + getMaxOccuringChar(str)
# Although this program can be written in atmost 3 lines in Python
# the above program has been written for a better understanding of
# the reader
# Shorter version of the program
# import collections
# str = "sample string"
# print "Max occurring character is " +
# collections.Counter(str).most_common(1)[0][0]
# This code has been contributed by Bhavya Jain
C#
1509
Chapter 267. Return maximum occurring character in an input string
Output:
1510
Chapter 267. Return maximum occurring character in an input string
Also, can you think of improvement if we can avoid two loopings in the above? Basically,
you need to figure out if we can solve the same problem with one loop itself instead of two
loops.
Source
https://www.geeksforgeeks.org/return-maximum-occurring-character-in-the-input-string/
1511
Chapter 268
Input : 1
/ \
2 3
/ \ / \
4 5 6 3
\ \
8 9
Output : 4
The root to leaf path with maximum distinct
nodes is 1-3-6-8.
A simple solution is to explore all root to leaf paths. In every root to leaf path, count
distinct nodes and finally return the maximum count.
An efficient solution is to use hashing. We recursively traverse the tree and maintain
count of distinct nodes on path from root to current node. We recur for left and right
subtrees and finally return maximum of two values.
Below c++ implementation of above idea
1512
Chapter 268. Root to leaf path with maximum distinct nodes
1513
Chapter 268. Root to leaf path with maximum distinct nodes
// return max length unique value path
return largestUinquePathUtil(node, hash);
}
// Driver program to test above functions
int main()
{
// Create binary tree shown in above figure
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->right->left->right = newNode(8);
root->right->right->right = newNode(9);
cout << largestUinquePath(root) << endl;
return 0;
}
Source
https://www.geeksforgeeks.org/root-leaf-path-maximum-distinct-nodes/
1514
Chapter 269
The idea is to traverse the tree and keep track of path length. Whenever we reach a leaf
node, we increment path length count in a hash map.
Once we have traverse the tree, hash map has counts of distinct path lengths. Finally we
print contents of hash map.
1515
Chapter 269. Root to leaf paths having equal lengths in a Binary Tree
1516
Chapter 269. Root to leaf paths having equal lengths in a Binary Tree
Output:
Source
https://www.geeksforgeeks.org/root-leaf-paths-equal-lengths-binary-tree/
1517
Chapter 270
Asked in : Amazon
1. Store all the words in a map with their occurrence with word as key and its occurrence
as value.
2. Find the second largest value in the map.
3. Traverse the map again and return the word with occurrence value equals to second
max value.
C++
1518
Chapter 270. Second most repeated word in a sequence
#include <bits/stdc++.h>
using namespace std;
// Function to find the word
string secMostRepeated(vector<string> seq)
{
// Store all the words with its occurrence
unordered_map<string, int> occ;
for (int i = 0; i < seq.size(); i++)
occ[seq[i]]++;
// find the second largest occurrence
int first_max = INT_MIN, sec_max = INT_MIN;
for (auto it = occ.begin(); it != occ.end(); it++) {
if (it->second > first_max) {
sec_max = first_max;
first_max = it->second;
}
else if (it->second > sec_max &&
it->second != first_max)
sec_max = it->second;
}
// Return string with occurrence equals
// to sec_max
for (auto it = occ.begin(); it != occ.end(); it++)
if (it->second == sec_max)
return it->first;
}
// Driver program
int main()
{
vector<string> seq = { "ccc", "aaa", "ccc",
"ddd", "aaa", "aaa" };
cout << secMostRepeated(seq);
return 0;
}
Java
1519
Chapter 270. Second most repeated word in a sequence
class GFG
{
// Method to find the word
static String secMostRepeated(Vector<String> seq)
{
// Store all the words with its occurrence
HashMap<String, Integer> occ = new HashMap<String,Integer>(seq.size()){
@Override
public Integer get(Object key) {
return containsKey(key) ? super.get(key) : 0;
}
};
for (int i = 0; i < seq.size(); i++)
occ.put(seq.get(i), occ.get(seq.get(i))+1);
// find the second largest occurrence
int first_max = Integer.MIN_VALUE, sec_max = Integer.MIN_VALUE;
Iterator<Map.Entry<String, Integer>> itr = occ.entrySet().iterator();
while (itr.hasNext())
{
Map.Entry<String, Integer> entry = itr.next();
int v = entry.getValue();
if( v > first_max) {
sec_max = first_max;
first_max = v;
}
else if (v > sec_max &&
v != first_max)
sec_max = v;
}
// Return string with occurrence equals
// to sec_max
itr = occ.entrySet().iterator();
while (itr.hasNext())
{
Map.Entry<String, Integer> entry = itr.next();
int v = entry.getValue();
if (v == sec_max)
return entry.getKey();
}
return null;
}
1520
Chapter 270. Second most repeated word in a sequence
Output:
ccc
Reference:
https://www.careercup.com/question?id=5748104113422336
Source
https://www.geeksforgeeks.org/second-repeated-word-sequence/
1521
Chapter 271
1522
Chapter 271. Shortest substring of a string containing all given words
In the first example, two solutions are possible: “world is here. this is a life full of ups” and
“ups and downs. life is world”.
1. Initialize HashMap with all the given words which are required to be searched and
assign their values as -1.
2. Maintain a counter.
3. Traverse the entire String word by word and do following for each sentence word
• If the sentence word exists in the list of words you’re looking for, update the last
position of that word.
• Increase the total count if the updated last position was not initialized.
• If the total count is equal to count of all given words, loop through the last
positions and find the smallest one. The distance between the current position
and that value will be the length of the substring. Record these values and find
the best one over all positions
1523
Chapter 271. Shortest substring of a string containing all given words
1524
Chapter 271. Shortest substring of a string containing all given words
}
}
Output :
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/shortest-substring-string-containing-given-words/
1525
Chapter 272
Input : arr[] = {2 2 1 3 1}
k = 2
Output: 1
Explanation:
Here in array,
2 is repeated 2 times
1 is repeated 2 times
3 is repeated 1 time
Hence 2 and 1 both are repeated 'k' times
i.e 2 and min(2, 1) is 1
Input : arr[] = {3 5 3 2}
k = 1
Output : 2
Explanation:
Both 2 and 5 are repeating 1 time but
min(5, 2) is 2
Simple Approach: A simple approach is to use two nested loops.The outer loop picks an
1526
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
element one by one starting from the leftmost element. The inner loop checks if the same
element is present on right side of it. If present increase the count and make the number
negative which we got at the right side to prevent it from counting again.
C++
Java
1527
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
Python3
1528
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
MAX = 1000
def findDuplicate(arr, n, k):
# Since arr[] has numbers in
# range from 1 to MAX
res = MAX + 1
for i in range(0, n):
if (arr[i] > 0):
# set count to 1 as number
# is present once
count = 1
for j in range(i + 1, n):
if (arr[i] == arr[j]):
count += 1
# If frequency of number is equal to 'k'
if (count == k):
res = min(res, arr[i])
return res
# Driver code
arr = [2, 2, 1, 3, 1]
k = 2
n = len(arr)
print(findDuplicate(arr, n, k))
# This code is contributed by Smitha Dinesh Semwal.
C#
1529
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
// Since arr[] has numbers in range
// from 1 to MAX
int res = MAX + 1;
for (int i = 0; i < n; i++)
{
if (arr[i] > 0)
{
// set count to 1 as number
// is present once
int count = 1;
for (int j = i + 1; j < n; j++)
if (arr[i] == arr[j])
count += 1;
// If frequency of number is
// equal to 'k'
if (count == k)
res = Math.Min(res, arr[i]);
}
}
return res;
}
// Driver code
public static void Main()
{
int[] arr = { 2, 2, 1, 3, 1 };
int k = 2;
int n = arr.Length;
Console.WriteLine(
findDuplicate(arr, n, k));
}
}
// This article is contributed by vt_m.
Output:
1530
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
C++
Java
1531
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
Python
1532
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
# Sort the array
arr.sort()
# Find the first element with exactly
# k occurrences.
i = 0
while (i < n):
j, count = i + 1, 1
while (j < n and arr[j] == arr[i]):
count += 1
j += 1
if (count == k):
return arr[i]
i = j
return -1
# Driver code
arr = [ 2, 2, 1, 3, 1 ];
k = 2
n = len(arr)
print findDuplicate(arr, n, k)
# This code is contributed by Sachin Bisht
C#
1533
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
int i = 0;
while (i < n) {
int j, count = 1;
for (j = i + 1; j < n &&
arr[j] == arr[i]; j++)
count++;
if (count == k)
return arr[i];
i = j;
}
return -1;
}
// Driver code
public static void Main()
{
int[] arr = { 2, 2, 1, 3, 1 };
int k = 2;
int n = arr.Length;
Console.WriteLine(
findDuplicate(arr, n, k));
}
}
// This article is contributed by vt_m.
Output:
C++
1534
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000;
int findDuplicate(int arr[], int n, int k)
{
// Computing frequencies of all elements
int freq[MAX];
memset(freq, 0, sizeof(freq));
for (int i = 0; i < n; i++) {
if (arr[i] < 1 && arr[i] > MAX) {
cout << "Out of range";
return -1;
}
freq[arr[i]] += 1;
}
// Finding the smallest element with
// frequency as k
for (int i = 0; i < MAX; i++) {
// If frequency of any of the number
// is equal to k starting from 0
// then return the number
if (freq[i] == k)
return i;
}
return -1;
}
// Driver code
int main()
{
int arr[] = { 2, 2, 1, 3, 1 };
int k = 2;
int n = sizeof(arr) / (sizeof(arr[0]));
cout << findDuplicate(arr, n, k);
return 0;
}
Java
1535
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
static final int MAX = 1000;
// finds the smallest number in arr[]
// that is repeated k times
static int findDuplicate(int arr[], int n, int k)
{
// Computing frequencies of all elements
int[] freq = new int[MAX];
for (int i = 0; i < n; i++) {
if (arr[i] < 1 && arr[i] > MAX) {
System.out.println("Out of range");
return -1;
}
freq[arr[i]] += 1;
}
// Finding the smallest element with
// frequency as k
for (int i = 0; i < MAX; i++) {
// If frequency of any of the number
// is equal to k starting from 0
// then return the number
if (freq[i] == k)
return i;
}
return -1;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 2, 2, 1, 3, 1 };
int k = 2;
int n = arr.length;
System.out.println(findDuplicate(arr, n, k));
}
}
// This article is contributed by Sumit Ghosh
Python
1536
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
MAX = 1000
def findDuplicate(arr, n, k):
# Computing frequencies of all elements
freq = [0 for i in range(MAX)]
for i in range(n):
if (arr[i] < 1 and arr[i] > MAX):
print "Out of range"
return -1
freq[arr[i]] += 1
# Finding the smallest element with
# frequency as k
for i in range(MAX):
# If frequency of any of the number
# is equal to k starting from 0
# then return the number
if (freq[i] == k):
return i
return -1
# Driver code
arr = [ 2, 2, 1, 3, 1 ]
k = 2
n = len(arr)
print findDuplicate(arr, n, k)
# This code is contributed by Sachin Bisht
C#
1537
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
int n, int k)
{
// Computing frequencies of all
// elements
int[] freq = new int[MAX];
for (int i = 0; i < n; i++)
{
if (arr[i] < 1 && arr[i] > MAX)
{
Console.WriteLine("Out of range");
return -1;
}
freq[arr[i]] += 1;
}
// Finding the smallest element with
// frequency as k
for (int i = 0; i < MAX; i++) {
// If frequency of any of the
// number is equal to k starting
// from 0 then return the number
if (freq[i] == k)
return i;
}
return -1;
}
// Driver code
public static void Main()
{
int[] arr = { 2, 2, 1, 3, 1 };
int k = 2;
int n = arr.Length;
Console.WriteLine(
findDuplicate(arr, n, k));
}
}
// This article is contributed by vt_m.
Output:
1538
Chapter 272. Smallest element in an array that is repeated exactly ‘k’ times.
Source
https://www.geeksforgeeks.org/smallest-element-array-repeated-exactly-k-times/
1539
Chapter 273
Smallest element repeated exactly ‘k’ times (not limited to small range) - GeeksforGeeks
Given an array of size n, the goal is to find out the smallest number that is repeated exactly
‘k’ times where k > 0?
And
Examples:
1540
Chapter 273. Smallest element repeated exactly ‘k’ times (not limited to small range)
3) Traverse hash map and print the smallest element with frequency k.
C++
Java
1541
Chapter 273. Smallest element repeated exactly ‘k’ times (not limited to small range)
{
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
// Map is used to store the count of
// elements present in the array
for (int i = 0; i < n; i ++)
if (m.containsKey(a[i]))
m.put(a[i], m.get(a[i]) + 1);
else m.put(a[i], 1);
// Traverse the map and find minimum
// element with frequency k.
int res = Integer.MAX_VALUE;
Set<Integer> s = m.keySet();
for (int temp : s)
if (m.get(temp) == k)
res = Math.min(res, temp);
return (res != Integer.MAX_VALUE)? res : -1;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = { 2, 2, 1, 3, 1 };
int k = 2;
System.out.println(smallestKFreq(arr, arr.length, k));
}
}
// This code is contributed by Arnav Kr. Mandal.
Output:
1542
Chapter 273. Smallest element repeated exactly ‘k’ times (not limited to small range)
Source
https://www.geeksforgeeks.org/smallest-element-repeated-exactly-k-times-not-limited-small-range/
1543
Chapter 274
1544
Chapter 274. Smallest subarray with all occurrences of a most frequent element
of the first occurrence of the element and the index of the last occurrence the element and
the frequency of the element. And at every step for a maximum repeated element minimize
the size of our subsegment.
C++
1545
Chapter 274. Smallest subarray with all occurrences of a most frequent element
strindex = left[x];
}
// select subsegment of smallest size
else if (count[x] == mx && i - left[x] + 1 < mn) {
mn = i - left[x] + 1;
strindex = left[x];
}
}
// Print the subsegment with all occurrences of
// a most frequent element
for (int i = strindex; i < strindex + mn; i++)
cout << a[i] << " ";
}
// Driver code
int main()
{
int A[] = { 1, 2, 2, 2, 1 };
int n = sizeof(A) / sizeof(A[0]);
smallestSubsegment(A, n);
return 0;
}
Java
1546
Chapter 274. Smallest subarray with all occurrences of a most frequent element
for (int i = 0; i < n; i++)
{
int x = a[i];
// First occurrence of an element,
// store the index
if (count.get(x) == null)
{
left.put(x, i) ;
count.put(x, 1);
}
// increase the frequency of elements
else
count.put(x, count.get(x) + 1);
// Find maximum repeated element and
// store its last occurrence and first
// occurrence
if (count.get(x) > mx)
{
mx = count.get(x);
// length of subsegment
mn = i - left.get(x) + 1;
strindex = left.get(x);
}
// select subsegment of smallest size
else if ((count.get(x) == mx) &&
(i - left.get(x) + 1 < mn))
{
mn = i - left.get(x) + 1;
strindex = left.get(x);
}
}
// Print the subsegment with all occurrences of
// a most frequent element
for (int i = strindex; i < strindex + mn; i++)
System.out.print(a[i] + " ");
}
// Driver program
public static void main (String[] args)
{
1547
Chapter 274. Smallest subarray with all occurrences of a most frequent element
int A[] = { 1, 2, 2, 2, 1 };
int n = A.length;
smallestSubsegment(A, n);
}
}
// This code is contributed by Gitanjali.
Output:
2 2 2
Source
https://www.geeksforgeeks.org/smallest-subarray-with-all-occurrences-of-a-most-frequent-element/
1548
Chapter 275
Input : arr[] = { 1, 1, 2, 2, 3, 3, 4, 5}
k = 3
Output : 5 7
Input : arr[] = { 1, 2, 2, 3}
k = 2
Output : 0 1
A simple solution is to use two nested loops. The outer loop is used to pick a starting
point and inner loop is used to pick an ending point. For every pair of starting-ending
points, we count distinct elements in it and update result if current window is smaller. We
use hashing to count distinct elements in a range.
C++
1549
Chapter 275. Smallest subarray with k distinct numbers
// k distinct numbers.
void minRange(int arr[], int n, int k)
{
int l = 0, r = n;
// Consider every element as starting
// point.
for (int i = 0; i < n; i++) {
// Find the smallest window starting
// with arr[i] and containing exactly
// k distinct elements.
unordered_set<int> s;
int j;
for (j = i; j < n; j++) {
s.insert(arr[j]);
if (s.size() == k) {
if ((j - i) < (r - l)) {
r = j;
l = i;
}
break;
}
}
// There are less than k distinct elements
// now, so no need to continue.
if (j == n)
break;
}
// If there was no window with k distinct
// elements (k is greater than total distinct
// elements)
if (l == 0 && r == n)
cout << "Invalid k";
else
cout << l << " " << r;
}
// Driver code for above function.
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
minRange(arr, n, k);
return 0;
1550
Chapter 275. Smallest subarray with k distinct numbers
Java
1551
Chapter 275. Smallest subarray with k distinct numbers
if (j == n)
break;
}
// If there was no window
// with k distinct elements
// (k is greater than total
// distinct elements)
if (l == 0 && r == n)
System.out.println("Invalid k");
else
System.out.println(l + " " + r);
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = arr.length;
int k = 3;
minRange(arr, n, k);
}
}
// This code is contributed
// by Kirti_Mangal
Output:
0 2
Optimization over above simple solution. The idea is to remove repetitions on left side
after we find k distinct elements.
C++
1552
Chapter 275. Smallest subarray with k distinct numbers
1553
Chapter 275. Smallest subarray with k distinct numbers
// it is same as explained in above loop.
if (hm.size() == k && (r - l) >= (j - i))
{
l = i;
r = j;
}
}
if (hm[arr[i]] == 1)
hm.erase(arr[i]);
else
hm[arr[i]]--;
}
if (l == 0 && r == n)
cout << "Invalid k" << endl;
else
cout << l << " " << r << endl;
}
// Driver code for above function.
int main()
{
int arr[] = { 1, 1, 2, 2, 3, 3, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
minRange(arr, n, k);
return 0;
}
Output:
5 7
Time complexity of this solution is O(n). In every nested iteration, we either add an element
or remove an element. Every element is inserted and removed at most once.
Improved By : Kirti_Mangal
Source
https://www.geeksforgeeks.org/smallest-subarray-k-distinct-numbers/
1554
Chapter 276
Input : aabcbcdbca
Output : dcba
Explanation :
dbca of length 4 is the smallest
window with highest number of distinct
characters.
Input : aaab
Output : ab
Explanation :
ab of length 2 is the smallest window
with highest number of distinct characters.
Above problem states that we have to find the smallest window that contains all the distinct
characters of the given string even if the smallest string contains repeating elements.
For example, in “aabcbcdb”, the smallest string that contains all the characters is “abcbcd”.
This problem reduces to Find the smallest window in a string containing all characters of
another string.
In that problem we find the smallest window that contains all the characters of given pattern.
1- Count all distinct characters in given string.
1555
Chapter 276. Smallest window that contains all characters of string itself
C++
1556
Chapter 276. Smallest window that contains all characters of string itself
if (curr_count[str[j]] == 1 )
count++;
// if all the characters are matched
if (count == dist_count)
{
// Try to minimize the window i.e., check if
// any character is occurring more no. of times
// than its occurrence in pattern, if yes
// then remove it from starting and also remove
// the useless characters.
while (curr_count[str[start]] > 1)
{
if (curr_count[str[start]] > 1)
curr_count[str[start]]--;
start++;
}
// Update window size
int len_window = j - start + 1;
if (min_len > len_window)
{
min_len = len_window;
start_index = start;
}
}
}
// Return substring starting from start_index
// and length min_len
return str.substr(start_index, min_len);
}
// Driver code
int main()
{
string str = "aabcbcdbca";
cout << "Smallest window containing all distinct"
" characters is " << findSubString(str);
return 0;
}
Java
1557
Chapter 276. Smallest window that contains all characters of string itself
static final int MAX_CHARS = 256;
// Function to find smallest window containing
// all distinct characters
static String findSubString(String str)
{
int n = str.length();
// Count all distinct characters.
int dist_count = 0;
boolean[] visited = new boolean[MAX_CHARS];
Arrays.fill(visited, false);
for (int i=0; i<n; i++)
{
if (visited[str.charAt(i)] == false)
{
visited[str.charAt(i)] = true;
dist_count++;
}
}
// Now follow the algorithm discussed in below
// post. We basically maintain a window of characters
// that contains all characters of given string.
// https://www.geeksforgeeks.org/find-the-smallest-window-in-a-string-containing-all-char
int start = 0, start_index = -1;
int min_len = Integer.MAX_VALUE;
int count = 0;
int[] curr_count = new int[MAX_CHARS];
for (int j=0; j<n; j++)
{
// Count occurrence of characters of string
curr_count[str.charAt(j)]++;
// If any distinct character matched,
// then increment count
if (curr_count[str.charAt(j)] == 1 )
count++;
// if all the characters are matched
if (count == dist_count)
{
// Try to minimize the window i.e., check if
// any character is occurring more no. of times
// than its occurrence in pattern, if yes
1558
Chapter 276. Smallest window that contains all characters of string itself
Output:
Related Article :
Length of the smallest sub-string consisting of maximum distinct characters
Improved By : Debasish Chowdhury 1
1559
Chapter 276. Smallest window that contains all characters of string itself
Source
https://www.geeksforgeeks.org/smallest-window-contains-characters-string/
1560
Chapter 277
1561
Chapter 277. Sort an array according to absolute difference with given value
The idea is to use a self balancing binary search tree. We traverse input array and for every
element, we find its difference with x and store the difference as key and element as value in
self balancing binary search tree. Finally we traverse the tree and print its inorder traversal
which is required output.
C++ Implementation :
In C++, self-balancing-bianry-search-tree is implemented by set, map and multimap. We
can’t use set here as we have key value pairs (not only keys). We also can’t directly use map
also as a single key can belong to multiple values and map allows a single value for a key.
So we use multimap which stores key value pairs and can have multiple values for a key.
1. Store the values in the multimap with the difference with X as key.
2. In multiimap, the values will be already in sorted order according to key i.e. difference
with X because it implements self-balancing-bianry-search-tree internally.
3. Update all the values of array with the values of map so that array has the required
output.
1562
Chapter 277. Sort an array according to absolute difference with given value
{
int arr[] = {10, 5, 3, 9 ,2};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 7;
rearrange(arr, n, x);
printArray(arr, n);
return 0;
}
Output:
5 9 10 3 2
Source
https://www.geeksforgeeks.org/sort-an-array-according-to-absolute-difference-with-given-value/
1563
Chapter 278
1. We insert all elements and their counts into a hash. This step takes O(n) time where
n is number of elements.
1564
Chapter 278. Sort elements by frequency | Set 4 (Efficient approach using hash)
2. We copy contents of hash to an array (or vector) and sort them by counts. This step
takes O(m Log m) time where m is total number of distinct elements.
3. For maintaining the order of elements if the frequency is same, we use another hash
which has the key as elements of the array and value as the index. If the frequency is
same for two elements then sort elements according to the index.
1565
Chapter 278. Sort elements by frequency | Set 4 (Efficient approach using hash)
Output:
8 8 8 2 2 5 5 6 -1 9999999
Time Complexity : O(n) + O(m Log m) where n is total number of elements and m is total
number of distinct elements
Source
https://www.geeksforgeeks.org/sort-elements-frequency-set-4-efficient-approach-using-hash/
1566
Chapter 279
Input : bbccdefbbaa
Output : aabbbbccdef
Input : geeksforgeeks
Output : eeeefggkkorss
A simple approach will be to use sorting algorithms like quick sort or merge sort and
sort the input string and print it.
C++
1567
Chapter 279. Sort string of characters
{
string s = "geeksforgeeks";
sortString(s);
return 0;
}
Output:
eeeefggkkorss
C++
1568
Chapter 279. Sort string of characters
Java
1569
Chapter 279. Sort string of characters
Output:
eeeefggkkorss
Source
https://www.geeksforgeeks.org/sort-string-characters/
1570
Chapter 280
Sort the linked list in the order of elements appearing in the array - GeeksforGeeks
Given an array of size N and a Linked List where elements will be from the array but can
also be duplicated, sort the linked list in the order, elements are appearing in the array. It
may be assumed that the array covers all elements of the linked list.
arr[] =
list =
Sorted list =
Asked in Amazon
First, make a hash table that stores the frequencies of elements in linked list. Then, simply
traverse list and for each element of arr[i] check the frequency in the has table and modify
the data of list by arr[i] element upto its frequency and at last Print the list.
1571
Chapter 280. Sort the linked list in the order of elements appearing in the array
1572
Chapter 280. Sort the linked list in the order of elements appearing in the array
Output :
Sort list:
5 -> 5 -> 1 -> 3 -> 2 -> 2 -> 8
1573
Chapter 280. Sort the linked list in the order of elements appearing in the array
Source
https://www.geeksforgeeks.org/sort-linked-list-order-elements-appearing-array/
1574
Chapter 281
Input : 9 4 3 5 8
Output : 3 4 5 8 9
We have read about various sorting algorithms such as heap sort, bubble sort, merge sort
and others.
Here we will see how can we sort N elements using hash array. But this algorithm has a
limitation. We can sort only those N elements, where the value of elements is not large
(typically not above 10^6).
Explanation of sorting using hash:
Step 1: create a hash array of size(max_element), since that is the maximum we will need
Step 2: traverse through all the elements and keep a count of number of occurrence of a
particular element.
Step 3: after keep a count of occurrence of all elements in the hash table, simply iterate
from 0 to max_element in the hash array
Step 4: while iterating in the hash array, if we find the value stored at any hash position
is more then 0, which indicated that the element is present at least once in the original list
of elements.
Step 5: Hash[i] has the count of the number of times a element is present in the list, so
when its >0, we print those number of times the element.
If you want to store the elements, use another array to store them in a sorted way.
If we want to sort it in a descending order, we simply traverse from max to 0, and repeat
the same procedure.
1575
Chapter 281. Sorting using trivial hash function
1576
Chapter 281. Sorting using trivial hash function
return 0;
}
Output:
0 1 2 2 3 3 4 4 5 5 9 10 12 15 18 19 20
1577
Chapter 281. Sorting using trivial hash function
Output:
1578
Chapter 281. Sorting using trivial hash function
-6 -5 -4 -3 -2 -1 0 1 2 3 4 5 7 8
Complexity:
This sort function can have complexity O(max_element). So performance depends on that
set of data provided.
Limitations:
1. Can only sort array elements of limited range (typically from -10^6 to +10^6)
2. Auxiliary space in worst cases is O(max_element) + O(min_element)
Source
https://www.geeksforgeeks.org/sorting-using-trivial-hash-function/
1579
Chapter 282
Split array to three subarrays such that sum of first and third subarray is equal and maxi-
mum - GeeksforGeeks
Given an array of N integers, the task is to print the sum of the first subarray by splitting
the array into exactly three subarrays such that the sum of the first and third subarray
elements are equal and the maximum.
Note: All the elements must belong to a subarray and the subarrays can also be empty.
Examples:
A naive approach is to check for all possible partitions and use the prefix-sum concept to
find out the partitions. The partition which gives the maximum sum of the first subarray
will be the answer.
An efficient approach is as follows:
1580
Chapter 282. Split array to three subarrays such that sum of first and third subarray is
equal and maximum
• If it does, then check for the previous maximum value and update accordingly.
1581
Chapter 282. Split array to three subarrays such that sum of first and third subarray is
equal and maximum
else
return maxi;
}
// Driver Code
int main()
{
int a[] = { 1, 3, 2, 1, 4 };
int n = sizeof(a) / sizeof(a[0]);
cout << sumFirst(a, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/split-array-to-three-subarrays-such-that-sum-of-first-and-third-subarray-is-equal-an
1582
Chapter 283
1583
Chapter 283. Subarray with no pair sum divisible by K
Naive Approach :
The naive method would be to consider all the subarrays. While considering a subarray, take
elements pairwise and compute the sum of the two elements of the pair. If the computed
sum is divisible by K, then ignore this subarray and continue with the next subarray. Else,
compute the sum of other pairs of this subarray in a similar fashion. If no pair’s sum is a
multiple of K, then compare the size of this subarray with the maximum size obtained so
far and update if required.
C++
1584
Chapter 283. Subarray with no pair sum divisible by K
for (int i = 1; i < n; i++)
{
int mod = arr[i] % k;
// Removing starting elements of current
// subarray while there is an element in
// set which makes a pair with mod[i] such
// that the pair sum is divisible.
while (mp[k - mod] != 0 ||
(mod == 0 && mp[mod] != 0))
{
mp[arr[s] % k]--;
s++;
}
// include the current element in
// the current subarray the ending
// index of the current subarray
// increments by one
mp[mod]++;
e++;
// compare the size of the current
// subarray with the maximum size so
// far
if ((e - s) > (maxe - maxs))
{
maxe = e;
maxs = s;
}
}
cout << "The maximum size is "
<< maxe - maxs + 1 << " and "
"the subarray is as follows\n";
for (int i=maxs; i<=maxe; i++)
cout << arr[i] << " ";
}
int main()
{
int k = 3;
int arr[] = {5, 10, 15, 20, 25};
int n = sizeof(arr)/sizeof(arr[0]);
subarrayDivisibleByK(arr, n, k);
1585
Chapter 283. Subarray with no pair sum divisible by K
return 0;
}
Java
1586
Chapter 283. Subarray with no pair sum divisible by K
// include the current element in
// the current subarray the ending
// index of the current subarray
// increments by one
mp[mod]++;
e++;
// compare the size of the current
// subarray with the maximum size so
// far
if ((e - s) > (maxe - maxs))
{
maxe = e;
maxs = s;
}
}
System.out.print("The maximum size is "
+ (maxe - maxs + 1)
+ " and the subarray is as follows\n");
for (int i = maxs; i <= maxe; i++)
System.out.print(arr[i] + " ");
}
// Driver Code
public static void main(String args[])
{
int k = 3;
int []arr = {5, 10, 15, 20, 25};
int n = arr.length;
subarrayDivisibleByK(arr, n, k);
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
1587
Chapter 283. Subarray with no pair sum divisible by K
# hash table to store the remainders
# obtained on dividing by K
mp = [0] * 1000
# s : starting index of the
# current subarray, e : ending
# index of the current subarray, maxs :
# starting index of the maximum
# size subarray so far, maxe : ending
# index of the maximum size subarray
# so far
s = 0; e = 0; maxs = 0; maxe = 0;
# insert the first element in the set
mp[arr[0] % k] = mp[arr[0] % k] + 1;
for i in range(1, n):
mod = arr[i] % k
# Removing starting elements of current
# subarray while there is an element in
# set which makes a pair with mod[i] such
# that the pair sum is divisible.
while (mp[k - mod] != 0 or (mod == 0
and mp[mod] != 0)) :
mp[arr[s] % k] = mp[arr[s] % k] - 1
s = s + 1
# include the current element in
# the current subarray the ending
# index of the current subarray
# increments by one
mp[mod] = mp[mod] + 1
e = e + 1
# compare the size of the current
# subarray with the maximum size so
# far
if ((e - s) > (maxe - maxs)) :
maxe = e
maxs = s
print ("The maximum size is {} and the "
" subarray is as follows"
.format((maxe - maxs + 1)))
for i in range(maxs, maxe + 1) :
1588
Chapter 283. Subarray with no pair sum divisible by K
C#
1589
Chapter 283. Subarray with no pair sum divisible by K
1590
Chapter 283. Subarray with no pair sum divisible by K
PHP
<?php
// PHP Program to find the
// subarray with no pair
// sum divisible by K
// function to find the subarray
// with no pair sum divisible by k
function subarrayDivisibleByK($arr, $n, $k)
{
// hash table to store the remainders
// obtained on dividing by K
$mp = array_fill(0, 1000, 0);
// s : starting index of the
// current subarray, e : ending
// index of the current subarray, maxs :
// starting index of the maximum
// size subarray so far, maxe : ending
// index of the maximum size subarray
// so far
$s = 0;
$e = 0;
$maxs = 0;
$maxe = 0;
// insert the first
// element in the set
$mp[$arr[0] % $k]++;
for ($i = 1; $i < $n; $i++)
{
$mod = $arr[$i] % $k;
// Removing starting elements
// of current subarray while
// there is an element in set
// which makes a pair with
// mod[i] such that the pair
// sum is divisible.
while ($mp[$k - $mod] != 0 ||
($mod == 0 &&
$mp[$mod] != 0))
{
$mp[$arr[$s] % $k]--;
$s++;
}
1591
Chapter 283. Subarray with no pair sum divisible by K
// include the current element in
// the current subarray the ending
// index of the current subarray
// increments by one
$mp[$mod]++;
$e++;
// compare the size of the current
// subarray with the maximum size so
// far
if (($e - $s) > ($maxe - $maxs))
{
$maxe = $e;
$maxs = $s;
}
}
echo ("The maximum size is ".
($maxe - $maxs + 1).
" and the subarray is".
" as follows\n");
for ($i = $maxs; $i <= $maxe; $i++)
echo ($arr[$i]." ");
}
// Driver Code
$k = 3;
$arr = array(5, 10, 15, 20, 25);
$n = count($arr);
subarrayDivisibleByK($arr, $n, $k);
// This code is contributed by
// Manish Shaw (manishshaw1)
?>
Output :
1592
Chapter 283. Subarray with no pair sum divisible by K
Source
https://www.geeksforgeeks.org/subarray-no-pair-sum-divisible-k/
1593
Chapter 284
A simple solution is to consider all subarrays and for every subarray check if it has distinct
elements or not using hashing. And add lengths of all subarrays having distinct elements.
1594
Chapter 284. Subarrays with distinct elements
If we use hashing to find distinct elements, then this approach takes O(n2 ) time under the
assumption that hashing search and insert operations take O(1) time.
An efficient solution is based on the fact that if we know all elements in a subarray arr[i..j]
are distinct, sum of all lengths of distinct element subarrays in this sub array is ((j-i+1)*(j-
i+2))/2. How? the possible lengths of subarrays are 1, 2, 3,……, j – i +1. So, the sum will
be ((j – i +1)*(j – i +2))/2.
We first find largest subarray (with distinct elements) starting from first element. We count
sum of lengths in this subarray using above formula. For finding next subarray of the distinct
element, we increment starting point, i and ending point, j unless (i+1, j) are distinct. If
not possible, then we increment i again and move forward the same way.
Below is C++ implementation of this approach:
1595
Chapter 284. Subarrays with distinct elements
return ans;
}
// Driven Code
int main()
{
int arr[] = {1, 2, 3, 4};
int n = sizeof(arr)/sizeof(arr[0]);
cout << sumoflength(arr, n) << endl;
return 0;
}
Output:
20
Time Complexity of this solution is O(n). Note that the inner loop runs n times in total as
j goes from 0 to n across all outer loops. So we do O(2n) operations which is same as O(n).
Source
https://www.geeksforgeeks.org/subarrays-distinct-elements/
1596
Chapter 285
Input:
4
1 5 10 8
3
2 20 13
Output: 1
1597
Chapter 285. Sudo Placement | Beautiful Pairs
Output:
Source
https://www.geeksforgeeks.org/sudo-placement-beautiful-pairs/
1598
Chapter 286
A naive approach will be to traverse left and right from every index and check if the
partition is possible or not at that index. If the partition is possible, then check if the
absolute difference between the sum of an element of left array and element of right array
is less than that of the previous obtained value at the partition. After finding the partition
point, greedily find the |sumleft – sumright |.
Time Complexity: O(N2 )
An efficient solution will be to store the last index of every occurring element in a hash-
map. Since the element values are large, direct indexing cannot be used. Create a prefix[]
and suffix[] array which stores the prefix sum and suffix sum respectively. Initialize a
1599
Chapter 286. Sudo Placement[1.5] | Partition
variable count as 0. Iterate for all the element in the array. A common point of observation
is, while traversing if the present element’s(Ai ) last nonoccurence is not i itself, then we
cannot have a partition in between i and the element’s last occurrence. While traversing
store the maximum of element’s last occurrence as the partition cannot be done till then.
Once the count is i itself, we can have a partition, now if there are multiple partitions then
choose the min |sumleft – sumright |.
Note : Use of map instead of unordered_map may cause TLE.
Below is the implementation of the above approach.
1600
Chapter 286. Sudo Placement[1.5] | Partition
// Check if partition is possible or not
// donot check for the last element
// as partition is not possible
for (int i = 0; i < n - 1; i++) {
// takes an element and checks it last occurrence
// stores the maximum of the last occurrence
// where partition can be done
count = max(count, mpp[a[i]]);
// if partition is possible
if (count == i) {
// partition is possible
possible = true;
// stores the left array sum
long long sumleft = presum[i];
// stores the rigth array sum
long long sumright = sufsum[i + 1];
// check if the difference is minimum
if ((abs(sumleft - sumright)) < ans) {
ans = abs(sumleft - sumright);
index = i + 1;
}
}
}
// is partition is possible or not
if (possible)
cout << index << ".5" << endl;
else
cout << -1 << endl;
}
// Driver Code-
int main()
{
int a[] = { 1, 2, -1, 2, 3 };
int n = sizeof(a) / sizeof(a[0]);
partition(a, n);
return 0;
}
1601
Chapter 286. Sudo Placement[1.5] | Partition
Time Complexity: O(n) under the assumption that unordered_map search works in O(1)
time.
Source
https://www.geeksforgeeks.org/sudo-placement1-5-partition/
1602
Chapter 287
One simple solution is to use two nested loops to count occurrences of every element.
While counting, we need to consider an element only if it is not already considered.
C++
1603
Chapter 287. Sum of all elements repeating ‘k’ times in an array
int sum = 0;
// To keep track of processed elements
vector<bool> visited(n, false);
// initializing count equal to zero
for (int i = 0; i < n; i++) {
// If arr[i] already processed
if (visited[i] == true)
continue;
// counting occurrences of arr[i]
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
visited[j] = true;
}
}
if (count == k)
sum += arr[i];
}
return sum;
}
// Driver code
int main()
{
int arr[] = { 9, 9, 10, 11, 8, 8, 9, 8 };
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
cout << sumKRepeating(arr, n, k);
return 0;
}
Java
1604
Chapter 287. Sum of all elements repeating ‘k’ times in an array
int n, int k)
{
int sum = 0;
// To keep track of
// processed elements
Vector<Boolean> visited = new Vector<Boolean>();
for (int i = 0; i < n; i++)
visited.add(false);
// initializing count
// equal to zero
for (int i = 0; i < n; i++)
{
// If arr[i] already processed
if (visited.get(i) == true)
continue;
// counting occurrences of arr[i]
int count = 1;
for (int j = i + 1; j < n; j++)
{
if (arr[i] == arr[j])
{
count++;
visited.add(j, true);
}
}
if (count == k)
sum += arr[i];
}
return sum;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 9, 9, 10, 11,
8, 8, 9, 8 };
int n = arr.length;
int k = 3;
System.out.println(sumKRepeating(arr, n, k));
}
}
1605
Chapter 287. Sum of all elements repeating ‘k’ times in an array
// This code is contributed by Arnab Kundu
Output:
17
C++
1606
Chapter 287. Sum of all elements repeating ‘k’ times in an array
Output:
17
Source
https://www.geeksforgeeks.org/sum-of-all-elements-repeating-k-times-in-an-array/
1607
Chapter 288
If |a[j]-a[i]| > 1
f(a[i], a[j]) = a[j] - a[i]
Else // if |a[j]-a[i]| <= 1
f(a[i], a[j]) = 0
Examples:
Input : 6 6 4 4
Output : -8
Explanation:
All pairs are: (6 - 6) + (6 - 6) +
(6 - 6) + (4 - 6) + (4 - 6) + (4 - 6) +
(4 - 6) + (4 - 4) + (4 - 4) = -8
Input: 1 2 3 1 3
Output: 4
Explanation: the pairs that add up are:
(3, 1), (3, 1) to give 4, rest all pairs
according to condition gives 0.
1608
Chapter 288. Sum of f(a[i], a[j]) over all pairs in an array of n integers
A naive approach is to iterate through all pairs and calculate f(a[i], a[j]) and summing it
while traversing in two nested loops will give us our answer.
Time Complexity: O(n^2)
A efficient approach will be to use a map/hash function to keep a count of every occurring
numbers and then traverse through the list. While traversing through the list, we multiply
the count of numbers that are before it and the number itself. Then subtract this result
with the pre-sum of the number before that number to get the sum of difference of all
pairs possible with that number. To remove all pairs whose absolute difference is <=1,
simply subtract the count of occurrence of (number-1) and (number+1) from the previously
computed sum. Here we subtract count of (number-1) from the computed sum as it had
been previously added to the sum, and we add (number+1) count since the negative has
been added to the pre-computed sum of all pairs.
Time Complexity : O(n)
Below is the implementation of the above approach :
C++
1609
Chapter 288. Sum of f(a[i], a[j]) over all pairs in an array of n integers
Java
1610
Chapter 288. Sum of f(a[i], a[j]) over all pairs in an array of n integers
Output :
Source
https://www.geeksforgeeks.org/sum-fai-aj-pairs-array-n-integers/
1611
Chapter 289
Traversal of tree with k jumps allowed between nodes of same height - GeeksforGeeks
Consider a tree with n nodes and root. You can jump from one node to any other node on
the same height a maximum of k times on total jumps. Certain nodes of the tree contain a
fruit, find out the maximum number of fruits he can collect.
Example :
Input Tree :
Number of Nodes = 12
Number of jumps allowed : 2
Edges:
1 2
1 3
2 4
2 5
5 9
9 10
9 11
11 12
1 3
3 7
7 6
7 8
Nodes Containing Fruits : 2 4 5 7 8 9 11 12
Output: 7
1612
Chapter 289. Traversal of tree with k jumps allowed between nodes of same height
Explanation:
1613
Chapter 289. Traversal of tree with k jumps allowed between nodes of same height
Approach: The idea is to use DFS to create a Height Adjacency List of the Nodes and to
store the parents. Then use another dfs to compute the maximum no of special nodes that
can be reached using the following dp state:
1614
Chapter 289. Traversal of tree with k jumps allowed between nodes of same height
int Fruit[N];
int Parent[N];
int dp[N][20];
// Function for DFS
void dfs1(vector<int> tree[], int s,
int p, int h)
{
Parent[s] = p;
int i;
H[h].push_back(s);
for (i = 0; i < tree[s].size(); i++) {
int v = tree[s][i];
if (v != p)
dfs1(tree, v, s, h + 1);
}
}
// Function for DFS
int dfs2(vector<int> tree[], int s,
int p, int h, int j)
{
int i;
int ans = 0;
if (dp[s][j] != -1)
return dp[s][j];
// jump
if (j > 0) {
for (i = 0; i < H[h].size(); i++) {
int v = H[h][i];
if (v != s)
ans = max(ans, dfs2(tree, v,
Parent[v], h, j - 1));
}
}
// climb
for (i = 0; i < tree[s].size(); i++) {
int v = tree[s][i];
if (v != p)
ans = max(ans, dfs2(tree, v, s, h + 1, j));
}
if (Fruit[s] == 1)
ans++;
dp[s][j] = ans;
1615
Chapter 289. Traversal of tree with k jumps allowed between nodes of same height
return ans;
}
// Function to calculate and
// return maximum number of fruits
int maxFruit(vector<int> tree[],
int NodesWithFruits[],
int n, int m, int k)
{
// reseting dp table and Fruit array
for (int i = 0; i < N; i++) {
for (int j = 0; j < 20; j++)
dp[i][j] = -1;
Fruit[i] = 0;
}
// This array is used to mark
// which nodes contain Fruits
for (int i = 0; i < m; i++)
Fruit[NodesWithFruits[i]] = 1;
dfs1(tree, 1, 0, 0);
int ans = dfs2(tree, 1, 0, 0, k);
return ans;
}
// Function to add Edge
void addEdge(vector<int> tree[], int u, int v)
{
tree[u].push_back(v);
tree[v].push_back(u);
}
// Driver Code
int main()
{
int n = 12; // Number of nodes
int k = 2; // Number of allowed jumps
vector<int> tree[N];
// Edges
addEdge(tree, 1, 2);
addEdge(tree, 1, 3);
addEdge(tree, 2, 4);
addEdge(tree, 2, 5);
addEdge(tree, 5, 9);
1616
Chapter 289. Traversal of tree with k jumps allowed between nodes of same height
addEdge(tree, 9, 10);
addEdge(tree, 9, 11);
addEdge(tree, 11, 12);
addEdge(tree, 1, 3);
addEdge(tree, 3, 7);
addEdge(tree, 7, 6);
addEdge(tree, 7, 8);
int NodesWithFruits[] = { 2, 4, 5, 7, 8, 9, 11, 12 };
// Number of nodes with fruits
int m = sizeof(NodesWithFruits) / sizeof(NodesWithFruits[0]);
int ans = maxFruit(tree, NodesWithFruits, n, m, k);
cout << ans << endl;
return 0;
}
Output:
Time Complexity : O(n*n*k) (worst case, eg: 2 level tree with the root having n-1 child
nodes)
Source
https://www.geeksforgeeks.org/traversal-tree-ability-jump-nodes-height/
1617
Chapter 290
Input:
List1: 10->15->4->20
lsit2: 8->4->2->10
Output:
Intersection List: 4->10
Union List: 2->8->20->4->15->10
Method 1 (Simple)
Following are simple algorithms to get union and intersection lists respectively.
Intersection (list1, list2)
Initialize result list as NULL. Traverse list1 and look for its each element in list2, if the
element is present in list2, then add the element to result.
Union (list1, list2):
Initialize result list as NULL. Traverse list1 and add all of its elements to the result.
Traverse list2. If an element of list2 is already present in result then do not insert it to
result, otherwise insert.
This method assumes that there are no duplicates in the given lists.
Thanks to Shekhu for suggesting this method. Following are C and Java implementations
of this method.
1618
Chapter 290. Union and Intersection of two Linked Lists
C/C++
1619
Chapter 290. Union and Intersection of two Linked Lists
1620
Chapter 290. Union and Intersection of two Linked Lists
1621
Chapter 290. Union and Intersection of two Linked Lists
return 0;
}
Java
1622
Chapter 290. Union and Intersection of two Linked Lists
// Traverse list1 and search each element of it in list2.
// If the element is present in list 2, then insert the
// element to result
while (t1 != null)
{
if (isPresent(head2, t1.data))
push(t1.data);
t1 = t1.next;
}
}
/* Utility function to print list */
void printList()
{
Node temp = head;
while(temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
/* Inserts a node at start of linked list */
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
/* A utilty function that returns true if data is present
in linked list else return false */
boolean isPresent (Node head, int data)
{
Node t = head;
while (t != null)
{
if (t.data == data)
1623
Chapter 290. Union and Intersection of two Linked Lists
return true;
t = t.next;
}
return false;
}
/* Drier program to test above functions */
public static void main(String args[])
{
LinkedList llist1 = new LinkedList();
LinkedList llist2 = new LinkedList();
LinkedList unin = new LinkedList();
LinkedList intersecn = new LinkedList();
/*create a linked lits 10->15->5->20 */
llist1.push(20);
llist1.push(4);
llist1.push(15);
llist1.push(10);
/*create a linked lits 8->4->2->10 */
llist2.push(10);
llist2.push(2);
llist2.push(4);
llist2.push(8);
intersecn.getIntersection(llist1.head, llist2.head);
unin.getUnion(llist1.head, llist2.head);
System.out.println("First List is");
llist1.printList();
System.out.println("Second List is");
llist2.printList();
System.out.println("Intersection List is");
intersecn.printList();
System.out.println("Union List is");
unin.printList();
}
} /* This code is contributed by Rajat Mishra */
Output:
First list is
1624
Chapter 290. Union and Intersection of two Linked Lists
10 15 4 20
Second list is
8 4 2 10
Intersection list is
4 10
Union list is
2 8 20 4 15 10
Time Complexity: O(mn) for both union and intersection operations. Here m is the number
of elements in first list and n is the number of elements in second list.
Method 2 (Use Merge Sort)
In this method, algorithms for Union and Intersection are very similar. First we sort the
given lists, then we traverse the sorted lists to get union and intersection.
Following are the steps to be followed to get union and intersection lists.
1) Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this
post for details of this step.
2) Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this
post for details of this step.
3) Linearly scan both sorted lists to get the union and intersection. This step takes O(m +
n) time. This step can be implemented using the same algorithm as sorted arrays algorithm
discussed here.
Time complexity of this method is O(mLogm + nLogn) which is better than method 1’s
time complexity.
Method 3 (Use Hashing)
Union (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse both lists one
by one, for each element being visited, look the element in hash table. If the element is not
present, then insert the element to result list. If the element is present, then ignore it.
Intersection (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse list1. For each
element being visited in list1, insert the element in hash table. Traverse list2, for each
element being visited in list2, look the element in hash table. If the element is present, then
insert the element to result list. If the element is not present, then ignore it.
Both of the above methods assume that there are no duplicates.
1625
Chapter 290. Union and Intersection of two Linked Lists
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
/* Utility function to print list */
void printList()
{
Node temp = head;
while(temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
/* Inserts a node at start of linked list */
void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
/* 3. Make next of new Node as head */
new_node.next = head;
/* 4. Move the head to point to new Node */
head = new_node;
}
public void append(int new_data)
{
if(this.head == null)
{
Node n = new Node(new_data);
this.head = n;
return;
}
Node n1 = this.head;
Node n2 = new Node(new_data);
while(n1.next != null)
{
1626
Chapter 290. Union and Intersection of two Linked Lists
n1 = n1.next;
}
n1.next = n2;
n2.next = null;
}
/* A utilty function that returns true if data is
present in linked list else return false */
boolean isPresent (Node head, int data)
{
Node t = head;
while (t != null)
{
if (t.data == data)
return true;
t = t.next;
}
return false;
}
LinkedList getIntersection(Node head1, Node head2)
{
HashSet<Integer> hset = new HashSet<>();
Node n1 = head1;
Node n2 = head2;
LinkedList result = new LinkedList();
// loop stores all the elements of list1 in hset
while(n1 != null)
{
if(hset.contains(n1.data))
{
hset.add(n1.data);
}
else
{
hset.add(n1.data);
}
n1 = n1.next;
}
//For every element of list2 present in hset
//loop inserts the element into the result
while(n2 != null)
{
if(hset.contains(n2.data))
{
1627
Chapter 290. Union and Intersection of two Linked Lists
result.push(n2.data);
}
n2 = n2.next;
}
return result;
}
LinkedList getUnion(Node head1, Node head2)
{
// HashMap that will store the
// elements of the lists with their counts
HashMap<Integer, Integer> hmap = new HashMap<>();
Node n1 = head1;
Node n2 = head2;
LinkedList result = new LinkedList();
// loop inserts the elements and the count of
// that element of list1 into the hmap
while(n1 != null)
{
if(hmap.containsKey(n1.data))
{
int val = hmap.get(n1.data);
hmap.put(n1.data, val + 1);
}
else
{
hmap.put(n1.data, 1);
}
n1 = n1.next;
}
// loop further adds the elements of list2 with
// their counts into the hmap
while(n2 != null)
{
if(hmap.containsKey(n2.data))
{
int val = hmap.get(n2.data);
hmap.put(n2.data, val + 1);
}
else
{
hmap.put(n2.data, 1);
}
n2 = n2.next;
}
1628
Chapter 290. Union and Intersection of two Linked Lists
1629
Chapter 290. Union and Intersection of two Linked Lists
Output:
First List is
10 15 4 20
Second List is
8 4 2 10
Intersection List is
10 4
Union List is
2 4 20 8 10 15
Time complexity of this method depends on the hashing technique used and the distribution
of elements in input lists. In practical, this approach may turn out to be better than above
2 methods.
Source
https://www.geeksforgeeks.org/union-and-intersection-of-two-linked-lists/
1630
Chapter 291
Union and Intersection of two linked lists | Set-2 (Using Merge Sort) - GeeksforGeeks
Given two Linked Lists, create union and intersection lists that contain union and inter-
section of the elements present in the given lists. Order of elements in output lists doesn’t
matter.
Examples:
Input:
List1: 10 -> 15 -> 4 ->20
lsit2: 8 -> 4 -> 2 -> 10
Output:
Intersection List: 4 -> 10
Union List: 2 -> 8 -> 20 -> 4 -> 15 -> 10
There were three methods discussed in this post with an implementation of Method 1.
In this post, we will see an implementation of Method 2 i.e. Using Merge sort.
Implementation:
Following are the steps to be followed to get union and intersection lists.
2) Linearly scan both sorted lists to get the union and intersection.
This step takes O(m + n) time.
1631
Chapter 291. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
Just like Method 1, This method also assumes that there are distinct elements in the lists.
1632
Chapter 291. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
else
{
slow = source;
fast = source->next;
/* Advance 'fast' two nodes, and advance 'slow' one node */
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
/* 'slow' is before the midpoint in the list,
so split it in two at that point. */
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
}
/* See https://www.geeksforgeeks.org/?p=3622 for details
of this function */
struct Node* SortedMerge(struct Node* a, struct Node* b)
{
struct Node* result = NULL;
/* Base cases */
if (a == NULL)
return(b);
else if (b==NULL)
return(a);
/* Pick either a or b, and recur */
if (a->data <= b->data)
{
result = a;
result->next = SortedMerge(a->next, b);
}
else
{
result = b;
result->next = SortedMerge(a, b->next);
}
return(result);
1633
Chapter 291. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
}
/* sorts the linked list by changing next pointers
(not data) */
void mergeSort(struct Node** headRef)
{
struct Node *head = *headRef;
struct Node *a, *b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL))
return;
/* Split head into 'a' and 'b' sublists */
FrontBackSplit(head, &a, &b);
/* Recursively sort the sublists */
mergeSort(&a);
mergeSort(&b);
/* answer = merge the two sorted lists together */
*headRef = SortedMerge(a, b);
}
/* Function to get union of two linked lists head1 and head2 */
struct Node *getUnion(struct Node *head1, struct Node *head2)
{
struct Node *result = NULL;
struct Node *t1 = head1, *t2 = head2;
// Traverse both lists and store the element in
// the resu1tant list
while (t1 != NULL && t2 != NULL)
{
// Move to the next of first list
// if its element is smaller
if (t1->data < t2->data)
{
push(&result, t1->data);
t1 = t1->next;
}
// Else move to the next of second list
else if (t1->data>t2->data)
{
push(&result, t2->data);
t2 = t2->next;
1634
Chapter 291. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
}
// If same then move to the next node
// in both lists
else
{
push(&result, t2->data);
t1 = t1->next;
t2 = t2->next;
}
}
/* Print remaining elements of the lists */
while (t1 != NULL)
{
push(&result, t1->data);
t1 = t1->next;
}
while (t2 != NULL)
{
push(&result, t2->data);
t2 = t2->next;
}
return result;
}
/* Function to get intersection of two linked lists
head1 and head2 */
struct Node *getIntersection(struct Node *head1,
struct Node *head2)
{
struct Node *result = NULL;
struct Node *t1 = head1, *t2 = head2;
// Traverse both lists and store the same element
// in the resu1tant list
while (t1 != NULL && t2 != NULL)
{
// Move to the next of first list if smaller
if (t1->data < t2->data)
t1 = t1->next;
// Move to the next of second list if it is smaller
else if (t1->data > t2->data)
t2 = t2->next;
// If both are same
1635
Chapter 291. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
else
{
// Store current element in the list
push(&result, t2->data);
// Move to the next node of both lists
t1 = t1->next;
t2 = t2->next;
}
}
//return the resultant list
return result;
}
/* A utility function to print a linked list*/
void printList (struct Node *node)
{
while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head1 = NULL;
struct Node* head2 = NULL;
struct Node* intersection_list = NULL;
struct Node* union_list = NULL;
/*create a linked lits 11->10->15->4->20 */
push(&head1, 20);
push(&head1, 4);
push(&head1, 15);
push(&head1, 10);
push(&head1, 11);
/*create a linked lits 8->4->2->10 */
push(&head2, 10);
push(&head2, 2);
push(&head2, 4);
push(&head2, 8);
1636
Chapter 291. Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
Output:
First list is
4 10 11 15 20
Second list is
2 4 8 10
Intersection list is
10 4
Union list is
20 15 11 10 8 4 2
Source
https://www.geeksforgeeks.org/union-intersection-two-linked-lists-set-2-using-merge-sort/
1637
Chapter 292
Input:
List1: 10 -> 15 -> 4 -> 20
list2: 8 -> 4 -> 2 -> 10
Output:
Intersection List: 4 -> 10
Union List: 2 -> 8 -> 20 -> 4 -> 15 -> 10
Implementation:
1- Start traversing both the lists.
a) Store the current element of both lists
with its occurrence in the map.
2- For Union: Store all the elements of the map
in the resultant list.
3- For Intersection: Store all the elements only
with an occurrence of 2 as 2 denotes that
they are present in both the lists.
1638
Chapter 292. Union and Intersection of two linked lists | Set-3 (Hashing)
1639
Chapter 292. Union and Intersection of two linked lists | Set-3 (Hashing)
// store element in the map
if (ptr2 != NULL)
{
eleOcc[ptr2->data]++;
ptr2=ptr2->next;
}
}
}
/* Function to get union of two linked lists head1
and head2 */
struct Node *getUnion(unordered_map<int, int> eleOcc)
{
struct Node *result = NULL;
// Push all the elements into the resultant list
for (auto it=eleOcc.begin(); it!=eleOcc.end(); it++)
push(&result, it->first);
return result;
}
/* Function to get intersection of two linked lists
head1 and head2 */
struct Node *getIntersection(unordered_map<int, int> eleOcc)
{
struct Node *result = NULL;
// Push a node with an element having occurrence
// of 2 as that means the current element is present
// in both the lists
for (auto it=eleOcc.begin(); it!=eleOcc.end(); it++)
if (it->second == 2)
push(&result, it->first);
// return resultant list
return result;
}
/* A utility function to print a linked list*/
void printList(struct Node *node)
{
while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
1640
Chapter 292. Union and Intersection of two linked lists | Set-3 (Hashing)
}
// Prints union and intersection of lists with head1
// and head2.
void printUnionIntersection(Node *head1, Node *head2)
{
// Store all the elements of both lists in the map
unordered_map<int, int> eleOcc;
storeEle(head1, head2, eleOcc);
Node *intersection_list = getIntersection(eleOcc);
Node *union_list = getUnion(eleOcc);
printf("\nIntersection list is \n");
printList(intersection_list);
printf("\nUnion list is \n");
printList(union_list);
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head1 = NULL;
struct Node* head2 = NULL;
/* create a linked lits 11->10->15->4->20 */
push(&head1, 1);
push(&head1, 2);
push(&head1, 3);
push(&head1, 4);
push(&head1, 5);
/* create a linked lits 8->4->2->10 */
push(&head2, 1);
push(&head2, 3);
push(&head2, 5);
push(&head2, 6);
printf("First list is \n");
printList(head1);
printf("\nSecond list is \n");
printList(head2);
printUnionIntersection(head1, head2);
1641
Chapter 292. Union and Intersection of two linked lists | Set-3 (Hashing)
return 0;
}
Output:
First list is
5 4 3 2 1
Second list is
6 5 3 1
Intersection list is
3 5 1
Union list is
3 4 6 5 2 1
We can also handle the case of duplicates by maintaining separate Hash for both the lists.
Time Complexity : O(m + n)
Auxiliary Space : O(m + n)
Source
https://www.geeksforgeeks.org/union-intersection-two-linked-lists-set-3-hashing/
1642
Chapter 293
Unique element in an array where all elements occur k times except one - GeeksforGeeks
Given an array which contains all elements occurring k times, but one occurs only once.
Find that unique element.
Examples:
A Simple Solution is to use two nested loops. The outer loop picks an element one by one
starting from the leftmost element. The inner loop checks if the element is present k times
or not. If present, then ignores the element, else prints the element.
Time Complexity of above solution is O(n2 ). We can Use Sorting to solve the problem
in O(nLogn) time. The idea is simple, first sort the array so that all occurrences of every
element become consecutive. Once the occurrences become consecutive, we can traverse the
sorted array and print the unique element in O(n) time.
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the
given array from left to right and keep track of visited elements in a hash table. Finally
print the element with count 1.
1643
Chapter 293. Unique element in an array where all elements occur k times except one
The hashing based solution requires O(n) extra space. We can use bitwise AND to find
the unique element in O(n) time and constant extra space.
1644
Chapter 293. Unique element in an array where all elements occur k times except one
Output:
Source
https://www.geeksforgeeks.org/find-unique-element-element-occurs-k-times-except-one/
1645
Chapter 294
1
/ \
2 3
/ \ / \
4 5 6 7
1646
Chapter 294. Vertical Sum in a given Binary Tree | Set 1
recursively calculate HDs. We initially pass the horizontal distance as 0 for root. For left
subtree, we pass the Horizontal Distance as Horizontal distance of root minus 1. For right
subtree, we pass the Horizontal Distance as Horizontal Distance of root plus 1.
Following is Java implementation for the same. HashMap is used to store the vertical sums
for different horizontal distances. Thanks to Nages for suggesting this method.
Java
import java.util.HashMap;
// Class for a tree node
class TreeNode {
// data members
private int key;
private TreeNode left;
private TreeNode right;
// Accessor methods
public int key() { return key; }
public TreeNode left() { return left; }
public TreeNode right() { return right; }
// Constructor
public TreeNode(int key)
{ this.key = key; left = null; right = null; }
// Methods to set left and right subtrees
public void setLeft(TreeNode left) { this.left = left; }
public void setRight(TreeNode right) { this.right = right; }
}
// Class for a Binary Tree
class Tree {
private TreeNode root;
// Constructors
public Tree() { root = null; }
public Tree(TreeNode n) { root = n; }
// Method to be called by the consumer classes
// like Main class
public void VerticalSumMain() { VerticalSum(root); }
// A wrapper over VerticalSumUtil()
private void VerticalSum(TreeNode root) {
1647
Chapter 294. Vertical Sum in a given Binary Tree | Set 1
// base case
if (root == null) { return; }
// Creates an empty hashMap hM
HashMap<Integer, Integer> hM =
new HashMap<Integer, Integer>();
// Calls the VerticalSumUtil() to store the
// vertical sum values in hM
VerticalSumUtil(root, 0, hM);
// Prints the values stored by VerticalSumUtil()
if (hM != null) {
System.out.println(hM.entrySet());
}
}
// Traverses the tree in Inoorder form and builds
// a hashMap hM that contains the vertical sum
private void VerticalSumUtil(TreeNode root, int hD,
HashMap<Integer, Integer> hM) {
// base case
if (root == null) { return; }
// Store the values in hM for left subtree
VerticalSumUtil(root.left(), hD - 1, hM);
// Update vertical sum for hD of this node
int prevSum = (hM.get(hD) == null) ? 0 : hM.get(hD);
hM.put(hD, prevSum + root.key());
// Store the values in hM for right subtree
VerticalSumUtil(root.right(), hD + 1, hM);
}
}
// Driver class to test the verticalSum methods
public class Main {
public static void main(String[] args) {
/* Create following Binary Tree
1
/ \
2 3
/ \ / \
4 5 6 7
1648
Chapter 294. Vertical Sum in a given Binary Tree | Set 1
*/
TreeNode root = new TreeNode(1);
root.setLeft(new TreeNode(2));
root.setRight(new TreeNode(3));
root.left().setLeft(new TreeNode(4));
root.left().setRight(new TreeNode(5));
root.right().setLeft(new TreeNode(6));
root.right().setRight(new TreeNode(7));
Tree t = new Tree(root);
System.out.println("Following are the values of" +
" vertical sums with the positions" +
" of the columns with respect to root ");
t.VerticalSumMain();
}
}
C++
1649
Chapter 294. Vertical Sum in a given Binary Tree | Set 1
1650
Chapter 294. Vertical Sum in a given Binary Tree | Set 1
Source
https://www.geeksforgeeks.org/vertical-sum-in-a-given-binary-tree/
1651
Chapter 295
1652
Chapter 295. Zoho On Campus Drive | Set 24 (Software Developer)
Eg: a b a a b c c d e d
Here a has only 2 occurrences
Round 3 & 4 – Advanced coding:
In these rounds we were asked to implement the logic for 2 games
– Minesweeper
– Breakout a.k.a. Arkanoid a.k.a. Brick-Breaker (you’ll find it online)
The game was split into various stages and we were asked to implement the logic stage by
stage.
Interviews:
A few interviews followed. Some of which was just to get to know you. One interview had
a few puzzles. And one was an official interview with a lead HR from Zoho
Those who did really well got the higher package and those who just missed it also got the
job with a lower package.
Some were offered internships.
Overall it was a challenging process. Those with strong logical and coding skills would make
it �
Source
https://www.geeksforgeeks.org/zoho-campus-drive-set-24-software-developer/
1653
Chapter 296
A simple solution is to use two nested loops where outer loop picks elements from left to
right, and inner loop checks if the picked element is present somewhere else. If not present,
then increment count of distinct elements. If count becomes k, return current element.
C++
1654
Chapter 296. k-th distinct (or non-repeating) element in an array.
Java
1655
Chapter 296. k-th distinct (or non-repeating) element in an array.
C#
1656
Chapter 296. k-th distinct (or non-repeating) element in an array.
{
// Returns k-th distinct element in arr
static int printKDistinct(int []arr,
int n,
int k)
{
int dist_count = 0;
for (int i = 0; i < n; i++)
{
// Check if current element is
// present somewhere else.
int j;
for (j = 0; j < n; j++)
if (i != j && arr[j] == arr[i])
break;
// If element is unique
if (j == n)
dist_count++;
if (dist_count == k)
return arr[i];
}
return -1;
}
//Driver code
public static void Main ()
{
int []ar = {1, 2, 1, 3, 4, 2};
int n = ar.Length;
int k = 2;
Console.Write(printKDistinct(ar, n, k));
}
}
// This code is contributed by nitn mittal
PHP
<?php
// PHP program to print k-th
1657
Chapter 296. k-th distinct (or non-repeating) element in an array.
// distinct element in a
// given array
// Returns k-th distinct
// element in arr.
function printKDistinct($arr,
$n, $k)
{
$dist_count = 0;
for ($i = 0; $i < $n; $i++)
{
// Check if current element
// is present somewhere else.
$j;
for ($j = 0; $j < $n; $j++)
if ($i != $j && $arr[$j] ==
$arr[$i])
break;
// If element is unique
if ($j == $n)
$dist_count++;
if ($dist_count == $k)
return $arr[$i];
}
return -1;
}
// Driver Code
$ar = array(1, 2, 1, 3, 4, 2);
$n = sizeof($ar) / sizeof($ar[0]);
$k = 2;
echo printKDistinct($ar, $n, $k);
// This code is contributed by nitin mittal.
?>
Output :
1658
Chapter 296. k-th distinct (or non-repeating) element in an array.
C++
1659
Chapter 296. k-th distinct (or non-repeating) element in an array.
{
int ar[] = {1, 2, 1, 3, 4, 2};
int n = sizeof(ar) / sizeof(ar[0]);
cout << printKDistinct(ar, n, 2);
return 0;
}
Python3
Output :
Source
https://www.geeksforgeeks.org/k-th-distinct-or-non-repeating-element-in-an-array/
1660
Chapter 297
k-th missing element in increasing sequence which is not present in a given sequence -
GeeksforGeeks
Given two sequences, one is increasing sequence a[] and another a normal sequence b[],
find the K-th missing element in the increasing sequence which is not present in the given
sequence. If no k-th missing element is there output -1
Examples:
1661
Chapter 297. k-th missing element in increasing sequence which is not present in a given
sequence
An efficient approach is to use hashing. We store all elements of given sequence in a hash
table. Then we iterate through all elements of increasing sequence. For every element, we
search it in the hash table. If element is present in not hash table, then we increment count
of missing elements. If count becomes k, we return the missing element.
Below is the C++ implementation of the above approach
Output:
1662
Chapter 297. k-th missing element in increasing sequence which is not present in a given
sequence
14
Source
https://www.geeksforgeeks.org/k-th-missing-element-increasing-sequence-not-present-given-sequence/
1663
Chapter 298
| set | unordered_set
---------------------------------------------------------
Ordering | increasing order | no ordering
| (by default) |
1664
Chapter 298. set vs unordered_set in C++ STL
Examples:
set:
Input : 1, 8, 2, 5, 3, 9
Output : 1, 2, 3, 5, 8, 9
Unordered_set:
Input : 1, 8, 2, 5, 3, 9
Output : 9 3 1 8 2 5
If you want to look at implementation details of set and unordered_set in c++ STL, see
Set Vs Map. Set allows to traverse elements in sorted order whereas Unordered_set doesn’t
allow to traverse elements in sorted order.
Output:
1665
Chapter 298. set vs unordered_set in C++ STL
Output:
Elements of unordered_set:
2 7 5 1 6 3
Predecessor/Successor in Set:
Set can be modified to find predecessor or successor whereas Unordered_set doesn’t allow
to find predecessor/Successor.
1666
Chapter 298. set vs unordered_set in C++ STL
1667
Chapter 298. set vs unordered_set in C++ STL
return 0;
}
Output:
predecessor of 5 is=2
No predecessor
predecessor of 8 is=5
successor of 5 is=8
successor of 2 is=5
No successor
Source
https://www.geeksforgeeks.org/set-vs-unordered_set-c-stl/
1668