ATA Tructures Lgorithm and Rograms For AVA Nterview
ATA Tructures Lgorithm and Rograms For AVA Nterview
1
Sat 1/6/2018
162. When does the worst case of Quicksort occur? .......................................................................................................................... 141
163. Sorting Strings using Bubble Sort ................................................................................................................................................. 141
164. Sorting Strings using Bubble Sort ................................................................................................................................................. 142
165. Breadth First Traversal or BFS for a Graph ................................................................................................................................. 143
166. Depth First Traversal or DFS for a Graph .................................................................................................................................... 145
167. Find Minimum Depth of a Binary Tree .......................................................................................................................................... 147
STRINGS ..................................................................................................................................................................................... 147
168. Write a Java program to concatenate a given string to the end of another string. ................................................................. 147
169. Write a Java program to test if a given string contains the specified sequence of char values. .......................................... 147
170. Write a Java program to compare a given string to the specified character sequence. ........................................................ 148
171. Write a Java program to compare a given string to the specified string buffer. ...................................................................... 148
172. Write a Java program to check whether a given string ends with the contents of another string. ....................................... 148
173. Write a Java program to check whether two String objects contain the same data. ............................................................. 149
174. Write a Java program to compare a given string to another string, ignoring case considerations. ..................................... 149
175. Write a Java program to get the contents of a given string as a byte array. ........................................................................... 149
176. Write a Java program to get the contents of a given string as a character array. .................................................................. 150
177. Write a Java program to create a unique identifier of a given string. ....................................................................................... 150
178. Write a Java program to get the index of all the characters of the alphabet. .......................................................................... 150
179. Write a Java program to get the canonical representation of the string object. ...................................................................... 152
180. Write a Java program to get the last index of a string within a string. ...................................................................................... 152
181. Write a java program to get the length of a given string. ........................................................................................................... 153
182. Write a Java program to find whether a region in the current string matches a region in another string. ........................... 154
183. Write a Java program to replace all the 'd' characters with 'f' characters. ............................................................................... 154
184. Write a Java program to replace each substring of a given string that matches the given regular expression with the
given replacement. ....................................................................................................................................................................................... 154
185. Write a Java program to check whether a given string starts with the contents of another string. ...................................... 155
186. Write a Java method to find the smallest number among three numbers. .............................................................................. 155
187. Write a Java method to compute the average of three numbers. ............................................................................................. 156
188. Write a Java method to display the middle character of a string. ............................................................................................. 158
189. Write a Java method to count all vowels in a string. ................................................................................................................... 159
190. Write a Java method to count all words in a string. .................................................................................................................... 160
191. Write a Java method to compute the sum of the digits in an integer........................................................................................ 161
192. Write a Java method to display the first 50 pentagonal numbers. ............................................................................................ 162
193. Write a Java method to compute the future investment value at a given interest rate for a specified number of years. .. 163
194. Write a Java method to print characters between two characters (i.e. A to P ). ................................................................... 165
195. Write a Java method to check whether an year (integer) entered by the user is a leap year or not. .................................. 167
196. Write a Java method to check whether a string is a valid password. ....................................................................................... 167
197. Write a Java method (takes a number n as input) to displays an n-by-n matrix. .................................................................... 169
198. Write Java methods to calculate the area of a triangle. ............................................................................................................. 171
199. Write a Java method to create the area of a pentagon. ............................................................................................................. 172
200. Write a Java method to find all twin prime numbers less than 100. ......................................................................................... 173
201. Write a Java program to create a new array list, add some elements (string) and print out the collection. ....................... 175
202. Write a Java program to iterate through all elements in a array list. ........................................................................................ 175
203. Write a Java program to insert an element into the array list at the first position. .................................................................. 175
204. Write a Java program to retrieve an element (at a specified index) from a given array list. ................................................. 176
205. Write a Java program to update specific array element by given element. ............................................................................. 177
206. Write a Java program to remove the third element from a array list. ....................................................................................... 177
207. Write a Java program to search an element in a array list. ....................................................................................................... 177
208. Write a Java program to sort a given array list. ........................................................................................................................... 178
209. Write a Java program to copy one array list into another. ......................................................................................................... 178
210. Write a Java program to shuffle elements in a array list. ........................................................................................................... 179
211. Write a Java program to reverse elements in a array list. ......................................................................................................... 179
212. Write a Java program to extract a portion of a array list. ........................................................................................................... 180
213. Write a Java program to compare two array lists........................................................................................................................ 180
214. Write a Java program of swap two elements in an array list. .................................................................................................... 181
215. Write a Java program to join two array lists. ................................................................................................................................ 181
216. Write a Java program to append the specified element to the end of a linked list. ................................................................ 182
217. Write a Java program to iterate through all elements in a linked list. ....................................................................................... 182
4
Sat 1/6/2018
218. Write a Java program to iterate through all elements in a linked list starting at the specified position. .............................. 183
219. Write a Java program to iterate a linked list in reverse order. ................................................................................................... 183
220. Write a Java program to insert the specified element at the specified position in the linked list. ......................................... 184
221. Write a Java program to insert elements into the linked list at the first and last position. ..................................................... 185
222. Write a Java program to insert the specified element at the front of a linked list. .................................................................. 185
223. Write a Java program to insert the specified element at the end of a linked list. ................................................................... 186
224. Write a Java program to insert some elements at the specified position into a linked list. ................................................... 186
225. Write a Java program to remove a specified element from a linked list. ................................................................................. 187
226. Write a Java program to remove all the elements from a linked list. ........................................................................................ 187
227. Write a Java program of swap two elements in an linked list. ................................................................................................... 188
228. Write a Java program to clone an linked list to another linked list. ........................................................................................... 188
229. Write a Java program to retrieve but does not remove, the first element of a linked list....................................................... 189
230. Write a Java program to convert a linked list to array list. ......................................................................................................... 189
231. Write a Java program to compare two linked lists. ..................................................................................................................... 190
HASHSET ........................................................................................................................................................................................... 190
232. Write a Java program to append the specified element to the end of a hash set. ................................................................. 190
233. Write a Java program to iterate through all elements in a hash list. ........................................................................................ 191
234. Write a Java program to get the number of elements in a hash set. ........................................................................................ 191
235. Write a Java program to empty an hash set. ............................................................................................................................... 192
236. Write a Java program to test a hash set is empty or not............................................................................................................ 192
237. Write a Java program to clone a hash set to another hash set................................................................................................. 193
238. Write a Java program to convert a hash set to an array. ........................................................................................................... 193
239. Write a Java program to convert a hash set to a tree set. ......................................................................................................... 194
240. Write a Java program to convert a hash set to a List/ArrayList. ............................................................................................... 194
241. Write a Java program to compare two hash sets........................................................................................................................ 195
TREESET............................................................................................................................................................................................ 196
242. Write a Java program to compare two sets and retain elements which are same on both sets. ......................................... 196
243. Write a Java program to remove all of the elements from a hash set...................................................................................... 196
244. Write a Java program to create a new tree set, add some colors (string) and print out the tree set. .................................. 197
245. Write a Java program to iterate through all elements in a tree set. .......................................................................................... 197
246. Write a Java program to add all the elements of a specified tree set to another tree set. .................................................... 198
247. Write a Java program to create a reverse order view of the elements contained in a given tree set. ................................. 198
248. Write a Java program to get the first and last elements in a tree set. ...................................................................................... 199
249. Write a Java program to clone a tree set list to another tree set. ............................................................................................. 199
250. Write a Java program to get the number of elements in a tree set. ......................................................................................... 200
251. Write a Java program to retrieve and remove the first element of a tree set. ......................................................................... 200
252. Write a Java program to retrieve and remove the last element of a tree set. ......................................................................... 201
253. Write a Java program to remove a given element from a tree set. .......................................................................................... 201
254. Write a Java program to create a new priority queue, add some colors (string) and print out the elements of the priority
queue. 202
255. Write a Java program to iterate through all elements in priority queue. .................................................................................. 202
PRIORITY QUEUE ............................................................................................................................................................................... 203
256. Write a Java program to add all the elements of a priority queue to another priority queue. ............................................... 203
257. Write a Java program to remove all the elements from a priority queue. ................................................................................ 203
258. Write a Java program to compare two priority queues............................................................................................................... 204
259. Write a Java program to retrieve the first element of the priority queue. ................................................................................. 205
260. Write a Java program to retrieve and remove the first element. ............................................................................................... 205
MAP .................................................................................................................................................................................................... 206
261. Write a Java program to associate the specified value with the specified key in a HashMap. ............................................. 206
262. Write a Java program to count the number of key-value (size) mappings in a map. ............................................................. 206
263. Write a Java program to copy all of the mappings from the specified map to another map. ................................................ 206
264. Write a Java program to remove all the mappings from a map. ............................................................................................... 207
265. Write a Java program to check whether a map contains key-value mappings (empty) or not. ............................................ 207
266. Write a Java program to get a shallow copy of a HashMap instance. ..................................................................................... 208
267. Write a Java program to test if a map contains a mapping for the specified key. .................................................................. 208
268. Write a Java program to test if a map contains a mapping for the specified value. ............................................................... 209
269. Write a Java program to create a set view of the mappings contained in a map. .................................................................. 210
270. Write a Java program to get the value of a specified key in a map. ......................................................................................... 210
271. Write a Java program to get a set view of the keys contained in this map. ............................................................................ 211
5
Sat 1/6/2018
272. Write a Java program to get a collection view of the values contained in this map. .............................................................. 211
273. Write a Java program to get the first (lowest) key and the last (highest) key currently in a map. ........................................ 212
274. Write a Java program to get a reverse order view of the keys contained in a given map. .................................................... 212
275. Write a Java program to get the portion of a map whose keys are strictly less than a given key. ....................................... 212
276. Write a Java program to get the portion of this map whose keys are less than (or equal to, if inclusive is true) a given
key. 213
277. Write a Java program to get NavigableSet view of the keys contained in a map. ................................................................. 214
278. Write a Java program to remove and get a key-value mapping associated with the least key in a map. ........................... 214
279. Write a Java program to get the portion of a map whose keys range from a given key to another key. ............................. 215
280. Write a Java program to get a key-value mapping associated with the least key greater than or equal to the given key.
Return null if there is no such key. ............................................................................................................................................................. 215
281. Write a Java program to get the least key greater than or equal to the given key. Returns null if there is no such key. .. 216
282. Write a Java program to reverse an integer number. ................................................................................................................. 216
283. Write a Java program to convert Roman number to an integer number. ................................................................................. 217
284. Write a Java program to convert a float value to absolute value. ............................................................................................. 218
285. Write a Java program to find the length of the longest sequence of zeros in binary representation of an integer. ........... 218
286. Write a Java program to convert temperature from Fahrenheit to Celsius degree. ............................................................... 219
287. Write a Java program to calculate the average value of array elements................................................................................. 220
288. Write a Java program to remove a specific element from an array. ......................................................................................... 221
289. Write a Java program to insert an element (specific position) into an array. ........................................................................... 222
290. Write a Java program to reverse an array of integer values. .................................................................................................... 223
291. Write a Java program to find the duplicate values of an array of string values. ..................................................................... 224
292. Write a Java program to find the duplicate values of an array of integer values. ................................................................... 225
293. Write a Java program to find the common elements between two arrays (string values). .................................................... 227
294. Write a Java program to remove duplicate elements from an array. ........................................................................................ 229
295. Write a Java program to add two matrices of the same size. ................................................................................................... 231
296. Write a Java program to convert an array to ArrayList. .............................................................................................................. 235
297. Write a Java program to convert an ArrayList to an array. ......................................................................................................... 235
298. Write a Java program to find a missing number in an array. ..................................................................................................... 237
299. Write a Java program to move all 0's to the end of an array. Maintain the relative order of the other (non-zero) array
elements. ....................................................................................................................................................................................................... 238
300. Write a Java program to compute the average value of an array of integers except the largest and smallest values. .... 240
301. Write a Java program to check if an array of integers contains two specified elements 65 and 77. ................................... 242
302. Write a Java program to find the length of the longest consecutive elements sequence from a given unsorted array of
integers. ......................................................................................................................................................................................................... 243
303. Write a Java program to find all the unique triplets such that sum of all the three elements [x, y, z (x ≤ y ≤ z)] equal to a
specified number........................................................................................................................................................................................... 245
304. Write a Java program that reads a number and display the square, cube, and fourth power. ............................................. 250
6
Sat 1/6/2018
3. How to find 3rd element from end in a linked list in one pass?
finding middle
This is another frequently asked linked list interview question. This question is exactly similar to
element of linked list in single pass. If we apply same trick of maintaining two pointers and increment other
pointer, when first has moved up to 3rd element, than when first pointer reaches to the end of linked list, second pointer will
be pointing to the 3rd element from last in a linked list.
7
Sat 1/6/2018
4. In an integer array, there is 1 to 100 number, out of one is duplicate, how to find?
This is a rather simple data structures question, especially for this kind of. In this case you can simply add all numbers
stored in array, and total sum should be equal to n(n+1)/2. Now just subtract actual sum to expected sum, and that is your
duplicate number. Of course there is a brute force way of checking each number against all other numbers, but that will
result in performance of O(n^which is not good. By the way this trick will not work if array have multiple duplicates or its not
numbers forming arithmetic progression. Here is example of one way to find duplicate number in array.
Find all duplicates in an array in linear time (v1)
This is a common interview question where you need to write a program to find all duplicates in an array where the numbers
in the array are in the range of 0 to n-1 where n is the size of the array. For example: [1, 2, 3, 3] is okay but [1, 2,
6, 3] is not. In this version of the challenge there can be multiple duplicate numbers as well. The algorithm below is
commented to explain what each piece of code does, but the general algorithm is:
(1) Loop through the array (2) For each element, find array[absolute(array[i])] in the array and set its value to negative if
positive (3) If in step 2 you encounter a negative number, then it means the element at index i in the array is a duplicate
An example
arr = [1, 2, 2, 3, 1] At i = 0 arr[absolute(arr[0])] = 2 which is positive so make it negative arr = [1, -2, 2, 3, 1] At i = 1
arr[absolute(arr[1])] = 2 which is positive so make it negative arr = [1, -2, -2, 3, 1] At i = 2 arr[absolute(arr[2])] = -2 which is
negative which means the element originally at index 2 is a duplicate duplicates = [2] At i = 3 arr[absolute(arr[3])] = 3 which
is positive so make it negative arr = [1, -2, -2, -3, 1] At i = 4 arr[absolute(arr[4])] = -2 which is negative which means the
element originally at index 4 is a duplicate duplicates = [2, 1]
Solution
function duplicates(arr) {
// where we will store our duplicate values
var dups = [];
for (var i = 0; i < arr.length; i++) {
// get element in array
var el = arr[Math.abs(arr[i])];
// element in array is positive so make it negative
if (el > 0) { arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])]; }
// special case if element is zero
// we set the value at this index to -arr.size as not to
// mix this number up with the others because we know the
// numbers are all in the range of 0 to n-1
else if (el === 0) { arr[Math.abs(arr[i])] = -arr.length; }
// element is negative so it is a duplicate
else {
if (Math.abs(arr[i]) === arr.length) { dups.push(0); }
else { dups.push(Math.abs(arr[i])); }
}
}
return dups;
}
duplicates([0,2,0,1,3,3]);
8
Sat 1/6/2018
if the array size is n and the array elements are in the range 1 to n-1(with one element repeated) then we will traverse the
array once from index(0) to index(n-1). If we have k at index(0) make the array value negative at index k(if positive) else
return that index if the value at that index is already negative.Will do the same for complete loop(while accessing the index
ignore the sign of array element) until we get the repeated element.
Thus no extra space is required and it'll take O(n) space. But we are loosing the original array here so no need to worry,
just make all the negative elements of the array as positive in another pass. ex. there is an array of size 5 with the values
as- A = [1,4,3,2,1] for i = 0 A[0] = 1 so we will change A[1] which is +ve, now A = [1,-4,3,2,1] for i = 1 A[1] = -4 so we will
change A[4] which is +ve, now A = [1,-4,3,2,-1] for i = 2 A[2] = 3 so we will change A[3] which is +ve, now A = [1,-4,3,-2,-1]
for i = 3 A[3] = -2 so we will change A[2] which is +ve, now A = [1,-4,-3,2,-1] for i = 4 A[4] = -1 so we will change A[1] which
is already -ve so report this index(1) as ans.
Solution 2* This method does not work if any of the elements in the array is smaller than 0 or greater than
n-1.
traverse the list for i= 0 to n-1 elements{check for sign of A[abs(A[i])] ;if positive thenmake it negative by
A[abs(A[i])]=-A[abs(A[i])];else // i.e., A[abs(A[i])] is negativethis element (ith element of list) is a
repetition}
int i;
Testdata:If you are going for an SDET interview, seeing that your code passes all the possible testdata and
handles every edge case.Positive Tests:{4,2,6,7,2}{1,2,3,4,5,5}{1,1,2,3,4,5}{0,0,0,0,0,0}Negative
Tests{1,2,3,4,5,6}{-1,-4,1,2,3}
Another solution
Assuming that there is an upped bound for the values of the numbers in the array (which is the case with all
built-in integer types in all programming languages I 've ever used -- for example, let's say they are 32-bit
integers) there is a solution that uses constant space:
9
Sat 1/6/2018
1. Create an array of N elements, where N is the upper bound for the integer values in the input array and
initialize all elements to 0 or false or some equivalent. I 'll call this the lookup array.
2. Loop over the input array, and use each number to index into the lookup array. If the value you find is 1
or true (etc), the current number in the input array is a duplicate.
3. Otherwise, set the corresponding value in the lookup array to 1 or true to remember that we have seen
this particular input number.
Technically, this is O(n) time and O(1) space, and it does not destroy the input array. Practically, you would
need things to be going your way to have such a program actually run (e.g. it's out of the question if talking
about 64-bit integers in the input).
Another solution
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.
class Main
{
// This function prints the first repeating element in arr[]
static void printFirstRepeating(int arr[])
{
// Initialize index of first repeating element
int min = -1;
10
Sat 1/6/2018
11
Sat 1/6/2018
7. How do you find duplicates in an array if there is more than one duplicate?
Sometime this is asked as follow-up question of earlier data structure interview question, related to finding duplicates in
Array. One way of solving this problem is using a HashTable or HashMap data structure. You can traverse through
array, and store each number as key and number of occurrence as value. At the end of traversal you can find all duplicate
numbers, for which occurrence is more than one. In Java if a number already exists in HashMap then calling
get(index) will return number otherwise it return null. this property can be used to insert or update numbers in HashMap.
12
Sat 1/6/2018
16. How to find angle between hour and minute hands at a given time?
The idea is to take a reference point as 12. Find the angle moved by hour and minute hands, subtract the two angles to find
the angle between them. See angle between hour hand and minute hand for more details
18. A sorted array is rotated at some unknown point, how to efficiently search an element in it.
A simple approach is linear search, but we can search in O(Logn) time using Binary
Search.
Other variations of this problem like find the minimum element or maximum element in a sorted and
rotated array.
19. Given a big string of characters, how to efficiently find the first unique character in it?
The efficient solution is to use character as an index in a count array. Traverse the given string and store index of first
occurrence of every character, also store count of occurrences. Then traverse the count array and find the smallest index
with count as 1..
20. Given a big array, how to efficiently find k’th largest element in it?
There can be many solutions for this. The best solution is to use min heap. We Build a Min Heap MH of the first k elements.
For each element, after the kth element (arr[k] to arr[n-1]), compare it with root of MH, if the element is greater than the root
then make it root and call heapify for MH, Else ignore it. Finally, MH has k largest elements and root of the MH is the kth
largest element. See k largest(or smallest) elements for more details.
21. Given an array of size n with range of numbers from 1 to n+1. find the two repeating numbers,
Use two loops. In the outer loop, pick elements one by one and count the number of occurrences of the picked element in
the inner loop.
This method doesn’t use the other useful data provided in questions like range of numbers is between 1 to n and there are
only two repeating elements.
class RepeatElement
{
13
Sat 1/6/2018
14
Sat 1/6/2018
30. Use a hashmap with string as key and list<string> as value where list of strings contain all anagrams of a key
string.
1) For each word in the file, find beta string which is its sorted version ex abd is sorted version of bad, adb and dba.
Put this word to that list whose key is this beta string. If it does not exist then create a new list with the beta string
as key in map.
2) Finally print all strings from the list whose key is the input word(sorted/beta string).
Solution
import java.util.*;
import java.io.*;
public class Anagram {
16
Sat 1/6/2018
34. Given pack of cards represented as A1,A2…A13 and B1,B2,..B13, and C1,c2,…c13 and d1,d2..d13.
35. You are given a file which has 51 card numbers. Only 1 card is missing. Find the missing card. - MetLife
It is based on following property of XOR operation:
1) If you XOR any number with itself, you will get ZERO.
i.e.. A ^ A = 2) If you XOR any number with ZERO, you get the same number
i.e. A ^ 0 = A
18
Sat 1/6/2018
36. The missing number 3 is only in X2 and not in X1, so it's becomes 0 ^ 3 = How to check if linked list contains
loop in Java?
Two pointers, fast and slow is used while iterating over linked list. Fast pointer moves two nodes in each iteration, while
slow pointer moves to one node. If linked list contains loop or cycle than both fast and slow pointer will meet at some point
during iteration. If they don't meet and fast or slow will point to null, then linked list is not cyclic and it doesn't contain any
loop. Here is the exact algorithm
Recursively:
static String reverseMe(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - + reverseMe(s.substring(0,s.length()-1));
}
42. Let’s say that you have 25 horses, and you want to pick the fastest 3 horses out of those 25. In each race,
only 5 horses can run at the same time because there are only 5 tracks. What is the minimum number of
races required to find the 3 fastest horses without using a stopwatch? – MetLife
http://www.programmerinterview.com/index.php/puzzles/25-horses-3-fastest-5-races-puzzle/
nd
2 best solution, 7 races
This question is an interesting one. Let’s start by asking ourselves, what are our limitations? Well, we don’t have a
stopwatch so we can’t time the horses. That means that we can’t compare the race times of each horse – otherwise we
19
Sat 1/6/2018
could simply have 5 races of 5 horse each and pick out the 3 fastest times to get the 3 fastest horses. Remember that we
can only race 5 horses in each race (otherwise we could just have one race with 25 horses, pick the 3 fastest, and we
would be done!).
Draw out a table
In problems like this, it helps tremendously to create some sort of visual aid that you can refer to. With that in mind, we have
created this table where each entry represents a different horse.
X1 X2 X3 X4 X5
X6 X7 X8 X9 X10
X11 X12 X13 X14 X15
X16 X17 X18 X19 X20
X21 X22 X23 X24 X25
Let’s say that we have 5 races of 5 horses each, so each row in the table above represents a race. So, “X1 X2 X3 X4 X5 ”
represents a race, and “X6 X7 X8 X9 X10 ” represents another race, etc. In each row, the fastest horses are listed in
descending order, from the fastest (extreme left) to the slowest (extreme right).
Only 5 horses each race
So, now we ask ourselves: what do we know after these 5 races? Well, we do have the 5 five fastest horses from each race
(X1, X6, X11, X16, and X21). But, does that mean we have the 5 fastest horses? Think about that for a second. Well,
actually it does not mean that we have the 5 fastest horses. Because, what if the 5 fastest horses just happened to be in
the first race – so X1 X2 X3 X4 X5 are the fastest horses. X1, X6, X11, X16, and X21 are all the fastest horses in their
individual groups, but there could be one group that just happened to have all of the fastest horses. Remember we haven’t
compared all the horses to each other since we can only run 5 horses in a race, so that is still a possibility. This is very
important to understand in this problem.
We also know the 5 fastest horses from each group – but it’s important to remember that the 5 group leaders are not
necessarily the 5 fastest horses. So what can we do with that information?
Well, we can race those 5 horses against each other (X1, X6, X11, X16, and X21) and that would be the 6th race. Let’s say
that the 3 fastest in that group are X1, X6, and X11 – automatically we can eliminate X16 and X21 since those 2 are
definitely not in the top 3.
What other horses can we eliminate after this 6th race? Well, we can automatically eliminate all the horses that X16 and
X21 competed against in the preliminary races – since X16 and X21 are not in the top 3 then we also know that any horse
that’s slower than those 2 is definitely not in the top 3 either. This means we can eliminate X17 X18 X22 and X23 along with
X16 and X21.
Now, we also know that X1 is the fastest horse in the group since he was the fastest horse out of the 5 group leaders. So,
we don’t need to race X1 anymore. Are there any other horses that we can eliminate from further races? Well, actually there
are. Think about it – if X6 and X11 are the 2nd and 3rd fastest in the group leaders, then we should be able to eliminate X8
since X6 raced against him and he was in 3rd place in that race. X7 could only possibly be the 3rd fastest, and since X8 is
slower than X7, we can safely eliminate X8. We can also eliminate X12 and X13 since X11 was the 3rd fastest in the group
leaders, and X12 and X13 were slower than X11.
So, all together we can eliminate these horses after the 6th race: X17 X18 X22 X23 X16 X21, X12, X13, X8 and X1. This
leaves us with the following horses to determine the 2nd and 3rd fastest horses:
The question is asking for the best case scenario: minimum number of races.
The best case would be if the data is sorted already, in other words, the fastest horse is horse #1 and the slowest horse is
horse #25. So that is 6 races.
Here are the races:
Race 1:
H1 – HFrom there you know the three fastest horses, but you still have to compare to the field. What you really
need to compare is horse #3 against the field. The remaining races would be:
Race 2:
H3, H6-HRace 3:
H3, H10-Race 4:
H3, H14-Race 5:
20
Sat 1/6/2018
H3, H18-Race 6:
H3, H22- http://www.mathsisfun.com/puzzles/weighing-9-balls-
solution.html
As in the example given above, DFS algorithm traverses from A to B to C to D first then to E, then to F and lastly to G. It
employs the following rules.
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the vertices from the stack,
which do not have adjacent vertices.)
Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.
21
Sat 1/6/2018
As in the example given above, BFS algorithm traverses from A to B to E to F first then to C and G lastly to D. It employs
the following rules.
Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue.
Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.
BFS explores/processes the closest vertices first and then moves outwards away from the source. Given this, you want to
use a data structure that when queried gives you the oldest element, based on the order they were inserted. A queue is
what you need in this case since it is first-in-first-out(FIFO).
DFS explores as far as possible along each branch first and then bracktracks. For this, a stack works better since it is
LIFO(last-in-first-out)
http://stackoverflow.com/questions/3929079/how-can-i-remember-which-data-structures-are-used-by-dfs-and-
bfs
5) http://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
To calculate the solution for any element at index “i” has two options
th
EITHER added to the solution found till “i-1“ index
OR start a new sum from the index “i”.
22
Sat 1/6/2018
Recursive Solution:
MS(i) = Max[MS(i-1) + A[i] , A[i]]
Solution You have N stacks of books. Each stack of books has some non zero height Hi equal to the number of
books on that stack ( considering all the books are identical and each book has a height of 1 unit ). In one move, you
can select any number of consecutive stacks of books such that the height of each selected stack of books Hi <= K .
Once such a sequence of stacks is chosen , You can collect any number of books from the chosen sequence of
stacks .
What is the maximum number of books that you can collect this way ?
Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. First line of each
test case contains two space separated integers N and K where N is the number of stacks of books. Second line of
each test case contains N space separated integers denoting the number of books Hi on each stack.
Output:
For each test case, print the maximum number of books you can collect.
Constraints:
1<=T<=11<=N<=11<=K<=11<=Hi<=1Example(To be used only for expected output):
Input
8322311183223111
Output
Explanation :
For the first test case
N=8,K=1{32231113}
We can collect maximum books from consecutive stacks numbered 5, 6 and 7 having height less than equal to K.
For the second test case
N=8,K=2{32231113}
We can collect maximum books from consecutive stacks numbered 2 and 3 having height less than equal to K.
class GfG
{
int max_Books(int a[], int n, int k)
{
// Your code here
}
}
6) In an array all elements are repeated twice except one element. Find the
element.
eg: 2, 3, 4, 4, 3 — In this 2 is the element which is not repeated.
48. “n” points are given , find the number of quadruplets which form square. - MetLife
The basic idea is to group the points by X or Y coordinate, being careful to avoid making groups that are too large.
Make a hash set of all the points. Something you can use to quickly check if a point is present.
HashSet extends AbstractSet and implements the Set INTERFACE . It creates a collection that uses a hash table for storage.
23
Sat 1/6/2018
A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used
to determine a unique value, called its hash code.
The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into
its hash code is performed automatically.
Group the points by their X coordinate. Break any groups with more than sqrt(n) points apart, and re-group those now-
free points by their Y coordinate. This guarantees the groups have at most sqrt(n) points and guarantees that for each
square there's a group that has two of the square's corner points.
For every group g, for every pair of points p,q in g, check whether the other two points of the two possible squares
containing p and q are present. Keep track of how many you find. Watch out for duplicates (are the two opposite
points also in a group?).
Why does it work? Well, the only tricky thing is the regrouping. If either the left or right columns of a square are in
groups that are not too large, the square will get found when that column group gets iterated. Otherwise both its top-
left and top-right corners get regrouped, placed into the same row group, and the square will be found when that row
group gets iterated.
49. What do you think the output of this code will be?
enum Day {
MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}
public class BuggyBread1{
public static void main (String args[]) {
Set mySet = new TreeSet();
mySet.add(Day.SATURDAY);
mySet.add(Day.WEDNESDAY);
mySet.add(Day.FRIDAY);
mySet.add(Day.WEDNESDAY);
for(Day d: mySet){
System.out.println(d);
}
}
}
Your answer: WEDNESDAY
FRIDAY
SATURDAY
Only one FRIDAY will be printed since the Set doesn’t allow duplicated.
Elements will be printed in the order that the constants are declared in in the Enum. TreeSet maintains the elements in the
ascending order which is identified by the defined compareTo method. The compareTo method in the Enum has been
defined such that the constant declared later are greater than the constants declared prior.
50.
24
Sat 1/6/2018
51. Construct Tree from given Inorder and Preorder traversals- MetLife
Construct tree from Inorder and Preorder
Let us consider the below traversals:
Inorder sequence: D B E A F C
A
/ \
/ \
DBE FC
Preorder sequence: A B D E C F
In a Preorder sequence, leftmost element is the root of the tree. So we know ‘A’ is root for given sequences. By
searching ‘A’ in Inorder sequence, we can find out all elements on left side of ‘A’ are in left subtree and elements on
right are in right subtree. So we know below structure now.
A
/ \
/ \
DBE FC
We recursively follow above steps and get the following tree.
A
/ \
/ \
B C
/\ /
/ \ /
D E F
Algorithm: buildTree()
1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element
in next recursive call.
2) Create a new tree node tNode with the data as picked element.
3) Find the picked element’s index in Inorder. Let the index be inIndex.
4) Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.
5) Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.
6) return tNode.
Mostly used in the networking programming. The objects that need to be transmitted through the network have to
be dconverted into bytes.
class GalleryImage implements Serializable
53. Could you provide some implementation of a Dictionary having a large number of words?
Your answer: The simplest implementation that can be given is that of a List wherein one can place ordered words
and perform a Binary search. The other implementation with a better search performance is HashMap where the key
is used as the first character of the word and the value as a LinkedList.
Up another level, there are HashMaps like:
hashmap {
a ( key ) -> hashmap (key-aa , value (hashmap(key-aaa,value)
b ( key ) -> hashmap (key-ba , value (hashmap(key-baa,value)
z( key ) -> hashmap (key-za , value (hashmap(key-zaa,value)
}
Up to n levels where n is the average size of the word in the dictionary.
Java Puzzles
Solution:
We all must have been faced compilation errors related to “Unreachable code” and some may have noticed “dead code
warning“. Above puzzle is related to them only.
In first method i.e. howToDoInJava_method1(), second print statement is unreachable, so compiler will complain for
oblivious reasons.
In second method howToDoInJava_method2(), second print statement is also unreachable, but strange compiler only
warns you. We will later try to get the logic here.
In third method also i.e. howToDoInJava_method3(), second print statement is unreachable, so compiler will complain
again. Strange !!
26
Sat 1/6/2018
Reasoning
The unreachable code in method 2 is called “Dead code”. This is purely Eclipse compiler reported error, and if you will
compile above class with “javac“, java inbuilt compiler will only complain for other two methods. [First and Third].
Quote from java language specification :
“The idea is that there must be some possible execution path from the beginning of the constructor, method, instance
initializer or static initializer that contains the statement to the statement itself. The analysis takes into account the structure
of statements. Except for the special treatment of while, do, and for statements whose condition expression has the constant
value true, the values of expressions are not taken into account in the flow analysis.”
What that means, is that the if block is not taken into account, since if you go through one of the paths of th e if
statement, you could reach second print statement. It all depends on compiler which determines this during compile time.
In other two statement, compiler has determined the un-reachability so it complains with error.
If we re-write second method again like this:
public void howToDoInJava_method2() {
System.out.println("how to do");
if (true) {
return;
}
else
{
return;
}
System.out.println("in java");
}
Now, compiler determine that in no way it can reach to last print statement, so it again reports unreachable code.
If you still have some doubts, please write down in comment section. I will try to resolve your queries.
55. How to create an instance of any class without using new keyword
November 28, 2012 by Lokesh Gupta
Using Class.forName()
ClassLoader loadClass()
Using clone()
Deserialization
Using reflection
Note: I am writing pseudo code only. For building complete fully working sample code, please read about related feature.
Using newInstance method of Class class
Class ref = Class.forName("DemoClass");
DemoClass obj = (DemoClass) ref.newInstance();
Class.forName() loads the class in memory. To create an instance of this class, we need to use newInstance().
Using class loader’s loadClass()
Just like above mechanism, class loader’s loadClass() method does the same thing.
instance.getClass().getClassLoader().loadClass("NewClass").newInstance();
Using clone() of java.lang.Object
This is also a way to have a new independent instance of a class.
NewClass obj = new NewClass();
NewClass obj2 = (NewClass) obj.clone();
Using Object serialization and deserialization
If you have gone through this article, you can understand that serialization and de-serialization is also a way to have another
instance of a class in system.
ObjectInputStream objStream = new ObjectInputStream(inputStream);
NewClass obj = (NewClass ) inStream.readObject();
27
Sat 1/6/2018
Using Reflection
This is also a popular way to create new instances in most of available frameworks.
constructor.newInstance(); or
class.newInstance();
c) Using object deserialization
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyClass object = (MyClass) inStream.readObject();
d) Creating string and array objects :
String s = "string object";
int[] a = {1, 2, 3, 4};
57. Puzzle : I have given a below map with the following below options,
Map map = new TreeMap();
map.put("test key 1", "test value 1");
map.put("test key 2", "test value 2");
map.put("test key 3", "test value 3");
Solution
import java.util.HashSet;
import java.util.Set;
{
duplicates.add(array[i]);
}
}
if(duplicates.size() ==
{
duplicates.add(-;
}
System.out.println(duplicates);
}
}
Solution
regex
public class GoodStringBadString
{
public static void main(String[] args)
{
String input = "Good Oops, Bad Oops";
String output = input.replaceAll("(?i)(\\p{L})\\1", "$1");
System.out.println(output);
}
}
Output: God Ops, Bad Ops
30
Sat 1/6/2018
62. Puzzle – Return all the strings with the Nth longest length
October 20, 2015 by Lokesh Gupta
Algorithm: given a list of strings, return all the strings with the nth longest length in that list for example: list – Yuri,
Ron, Interview, Longest, List, Contain and nth = 1 will return just “Interview” whereas nth = 2 will return both
“Longest” and “Contain”.
Though solution to “How to find the kth largest element in an unsorted array of length n in O(n)?” can be applied to string
length, how to translate back to print all the strings with n length?
Solution
I have written a simple java program which is able to find “all Nth longest elements” from a list of strings. Program is as
below:
package com.howtodoinjava.examples;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
System.out.println( findNthLongestElement(list, n) );
}
31
Sat 1/6/2018
It’s common puzzle asked in java interviews at beginner level. Let’s memorize their solutions for quick recall.
String sh = "HowToDoInJava.com";
System.out.println(sh + " -> " + new StringBuilder(sh).reverse( ));
Output:
While reversing string content by words, most natural way is to use a StringTokenizer and a Stack. As you
are aware that Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.
String s = "Java technology blog for smart java concepts and coding practices";
// Put words from String in Stack
Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s," ");
while (st.hasMoreTokens()) {
myStack.push(st.nextToken());
}
// Build the reverse string
StringBuilder reverseString = new StringBuilder();
32
Sat 1/6/2018
while (!myStack.empty()) {
reverseString.append(myStack.pop() + " ");
}
System.out.println(reverseString.toString());
Output:
practices coding and concepts java smart for blog technology Java
Solution in Java Above code, though simple, can be reduced by many lines using new language features such as lambda in
java 8. Let’s see how?
import java.util.Arrays;
public class FindMissingNumber {
public static void main(String[] args) {
//10 is missing
int[] numbers = {1,2,3,4,5,6,7,8,9, 11,12};
int N = 12;
int idealSum = (N * (N + ) / 2;
int sum = Arrays.stream(numbers).sum();
int missingNumber = idealSum - sum;
System.out.println(missingNumber);
}
}
Output:
Puzzles like these are simple to solve, but it is always useful to know the solution before it is asked in any interview.
33
Sat 1/6/2018
n this post, I have collected some java interview questions where you are asked to write a program or you have been
told to guess the output of a given program. I have also tried to answer them. I hope it will be helpful for you.
67. Write a Java program to find out the nearest number to 100 of the given two numbers?
68. There are two numbers ‘a’ and ‘b’. Write a java program which should print ‘a’ if ‘a’ is bigger than ‘b’ by 2 or
more or should print ‘b’ if ‘b’ is bigger than ‘a’ by 2 or more. Otherwise, it should print “INCONCLUSIVE”?
69. Given a string “JAVAJ2EE”, write java program to print this string in the below format?
JJ AJ A VJ A V AJ A V A JJ A V A J 2J A V A J 2 EJ A V A J 2 E E
70. How do you prove that String s1 = new String(“ONE”) and String s2 = “ONE” are two different objects in the
memory?
Ans : Use “==” operator to compare s1 and s2. It will return ‘false’ if they are two different objects in the memory.
Ans : Yes. Compiler will treat ‘http’ as label and remaining part (of Line will be commented.
System.out.println(s1[0] == s2[2]);
System.out.println(s1[1] == s2[1]);
System.out.println(s1[2] == s2[0]);
}
}
Ans :falsetruetrue
75. Write a Java program to print the current date in “dd MMM yyyy” format?
Description:
You have got a range of numbers between 1 to N, where one of the number is
repeated. You need to write a program to find out the duplicate number.
package com.java2novice.algos;
import java.util.ArrayList;
import java.util.List;
public class DuplicateNumber {
public int findDuplicateNumber(List<Integer> numbers){
37
Sat 1/6/2018
Output:
Duplicate Number:
Description:
Write a sample code to reverse Singly Linked List by iterating through it only once.
Recursive Method:
1) Divide the list in two parts - first node and rest of the linked list.
2) Call reverse for the rest of the linked list.
3) Link rest to first.
4) Fix head pointer.
package com.java2novice.ds.linkedlist;
public class SinglyLinkedListImpl<T> {
private Node<T> head;
public void add(T element){
Node<T> nd = new Node<T>();
nd.setValue(element);
System.out.println("Adding: "+element);
Node<T> tmp = head;
while(true){
if(tmp == null){
38
Sat 1/6/2018
Output:
Adding: Adding: Adding: Adding:
3 32 54 89
89 54 32 3
78. Program: Find out middle index where sum of both ends are equal.
Description:
You are given an array of numbers. Find out the array index or position
where sum of numbers preceeding the index is equals to sum of numbers
succeeding the index.
package com.java2novice.algos;
public class FindMiddleIndex {
public static int findMiddleIndex(int[] numbers) throws Exception {
int endIndex = numbers.length - 1;
int startIndex = 0;
int sumLeft = 0;
int sumRight = 0;
while (true) {
if (sumLeft > sumRight) {
sumRight += numbers[endIndex--];
} else {
sumLeft += numbers[startIndex++];
}
if (startIndex > endIndex) {
if (sumLeft == sumRight) {
break;
} else {
throw new Exception(
"Please pass proper array to match the requirement");
}
}
40
Sat 1/6/2018
}
return endIndex;
}
public static void main(String a[]) {
int[] num = { 2, 4, 4, 5, 4, 1 };
try {
System.out.println("Starting from index 0, adding numbers till index "
+ findMiddleIndex(num) + " and");
System.out.println("adding rest of the numbers can be equal");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Output:
Starting from index 0, adding numbers till index 2 and
adding rest of the numbers can be equal
Description:
Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor as
private, so that you can restrict the creation of the object. Provide a static method to get instance of the object, wherein you can handle
the object creation inside the class only. In this example we are creating object by using static block.
package com.java2novice.algos;
public class MySingleton {
private static MySingleton myObj;
static{
myObj = new MySingleton();
}
private MySingleton(){
}
public static MySingleton getInstance(){
return myObj;
}
public void testMe(){
System.out.println("Hey.... it is working!!!");
}
public static void main(String a[]){
MySingleton ms = getInstance();
ms.testMe();
}
}
41
Sat 1/6/2018
Description:
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlocks can occur in Java
when the synchronized keyword causes the executing thread to block while waiting to get the lock, associated with the specified
object. Since the thread might already hold locks associated with other objects, two threads could each be waiting for the other to
release a lock. In such case, they will end up waiting forever.
package com.java2novice.algos;
public class MyDeadlock {
String str1 = "Java";
String str2 = "UNIX";
Thread trd1 = new Thread("My Thread 1"){
public void run(){
while(true){
synchronized(str1){
synchronized(str2){
System.out.println(str1 + str2);
}
}
}
}
};
Thread trd2 = new Thread("My Thread 2"){
public void run(){
while(true){
synchronized(str2){
synchronized(str1){
System.out.println(str2 + str1);
}
}
}
}
};
public static void main(String a[]){
MyDeadlock mdl = new MyDeadlock();
mdl.trd1.start();
mdl.trd2.start();
}
}
Description:
Write a program to reverse a string using recursive methods.
42
Sat 1/6/2018
package com.java2novice.algos;
public class StringRecursiveReversal {
String reverse = "";
public String reverseString(String str){
if(str.length() == 1){
return str;
} else {
reverse += str.charAt(str.length()-1)
+reverseString(str.substring(0,str.length()-1));
return reverse;
}
}
public static void main(String a[]){
StringRecursiveReversal srr = new StringRecursiveReversal();
System.out.println("Result: "+srr.reverseString("Java2novice"));
}
}
Output:
Result: ecivon2avaJ
Description:
Write a program to reverse a number using numeric operations. Below example shows how to reverse a number using numeric
operations.
package com.java2novice.algos;
public class NumberReverse {
public int reverseNumber(int number){
int reverse = 0;
while(number != 0){
reverse = (reverse*10)+(number%10);
number = number/10;
}
return reverse;
}
public static void main(String a[]){
NumberReverse nr = new NumberReverse();
System.out.println("Result: "+nr.reverseNumber(17868));
}
}
43
Sat 1/6/2018
Output:
Result: 86Program:
Description:
Write a program to convert decimal number to binary format using numeric operations.
Below example shows how to convert decimal number to binary format using numeric operations.
package com.java2novice.algos;
public class DecimalToBinary {
public void printBinaryFormat(int number){
int binary[] = new int[25];
int index = 0;
while(number > 0){
binary[index++] = number%2;
number = number/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
}
public static void main(String a[]){
DecimalToBinary dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Output:
Description:
A perfect number is a positive integer that is equal to the sum
of its proper positive divisors, that is, the sum of its positive
divisors excluding the number itself. Equivalently, a perfect number
is a number that is half the sum of all of its positive divisors.
The first perfect number is 6, because 1, 2 and 3 are its proper
positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number is equal to half the sum
of all its positive divisors:
( 1 + 2 + 3 + 6 ) / 2 = 6.
44
Sat 1/6/2018
package com.java2novice.algos;
public class IsPerfectNumber {
public boolean isPerfectNumber(int number){
int temp = 0;
for(int i=1;i<=number/2;i++){
if(number%i == 0){
temp += i;
}
}
if(temp == number){
System.out.println("It is a perfect number");
return true;
} else {
System.out.println("It is not a perfect number");
return false;
}
}
public static void main(String a[]){
IsPerfectNumber ipn = new IsPerfectNumber();
System.out.println("Is perfect number: "+ipn.isPerfectNumber(28));
}
}
Output:
It is a perfect number
Is perfect number: true
Description:
Write a program to implement your own ArrayList class. It should
contain add(), get(), remove(), size() methods. Use dynamic array logic.
It should increase its size when it reaches threshold.
package com.java2novice.algos;
import java.util.Arrays;
public class MyArrayList {
private Object[] myStore;
private int actSize = 0;
public MyArrayList(){
myStore = new Object[10];
}
public Object get(int index){
if(index < actSize){
return myStore[index];
45
Sat 1/6/2018
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
public void add(Object obj){
if(myStore.length-actSize <= 5){
increaseListSize();
}
myStore[actSize++] = obj;
}
public Object remove(int index){
if(index < actSize){
Object obj = myStore[index];
myStore[index] = null;
int tmp = index;
while(tmp < actSize){
myStore[tmp] = myStore[tmp+1];
myStore[tmp+1] = null;
tmp++;
}
actSize--;
return obj;
} else {
throw new ArrayIndexOutOfBoundsException();
}
}
public int size(){
return actSize;
}
private void increaseListSize(){
myStore = Arrays.copyOf(myStore, myStore.length*2);
System.out.println("\nNew length: "+myStore.length);
}
public static void main(String a[]){
MyArrayList mal = new MyArrayList();
mal.add(new Integer(2));
mal.add(new Integer(5));
mal.add(new Integer(1));
mal.add(new Integer(23));
mal.add(new Integer(14));
for(int i=0;i<mal.size();i++){
System.out.print(mal.get(i)+" ");
}
mal.add(new Integer(29));
System.out.println("Element at Index 5:"+mal.get(5));
System.out.println("List size: "+mal.size());
System.out.println("Removing element at index 2: "+mal.remove(2));
for(int i=0;i<mal.size();i++){
System.out.print(mal.get(i)+" ");
}
}
}
Output:
2 5 1 23 14
New length: Element at Index 5:List size: Removing element at index 2: 2 5 23 14 29
46
Sat 1/6/2018
86. Program: Write a program to find maximum repeated words from a file.
Write a program to read words from a file. Count the repeated or duplicated words. Sort it by maximum repeated or
duplicated word count.
Code:
package com.java2novice.algos;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;
public class MaxDuplicateWordCount {
public Map<String, Integer> getWordCount(String fileName){
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Map<String, Integer> wordMap = new HashMap<String, Integer>();
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while((line = br.readLine()) != null){
StringTokenizer st = new StringTokenizer(line, " ");
while(st.hasMoreTokens()){
String tmp = st.nextToken().toLowerCase();
if(wordMap.containsKey(tmp)){
wordMap.put(tmp, wordMap.get(tmp)+1);
} else {
wordMap.put(tmp, 1);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{if(br != null) br.close();}catch(Exception ex){}
}
return wordMap;
}
public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap){
Set<Entry<String, Integer>> set = wordMap.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String,
Integer>>(set);
Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
{
public int compare( Map.Entry<String, Integer> o1, Map.Entry<String,
47
Sat 1/6/2018
Integer> o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
return list;
}
public static void main(String a[]){
MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
Map<String, Integer> wordMap = mdc.getWordCount("C:/MyTestFile.txt");
List<Entry<String, Integer>> list = mdc.sortByValue(wordMap);
for(Map.Entry<String, Integer> entry:list){
System.out.println(entry.getKey()+" ==== "+entry.getValue());
}
}
}
Output:
one ==== the ==== that ==== of ==== in ==== some ==== to ==== summary ==== but ==== have ==== common ====
least ==== simplest ====
Description:
Write a program to find out duplicate or repeated characters in a
string, and calculate the count of repeatation.
package com.java2novice.algos;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DuplicateCharsInString {
public void findDuplicateChars(String str){
Map<Character, Integer> dupMap = new HashMap<Character, Integer>();
char[] chrs = str.toCharArray();
for(Character ch:chrs){
if(dupMap.containsKey(ch)){
dupMap.put(ch, dupMap.get(ch)+1);
} else {
dupMap.put(ch, 1);
}
}
Set<Character> keys = dupMap.keySet();
for(Character ch:keys){
if(dupMap.get(ch) > 1){
System.out.println(ch+"--->"+dupMap.get(ch));
}
}
}
public static void main(String a[]){
DuplicateCharsInString dcs = new DuplicateCharsInString();
dcs.findDuplicateChars("Java2Novice");
}
48
Sat 1/6/2018
Output:
v--->a--->
88. Program: Write a program to find top two maximum numbers in a array.
Description:
Write a program to find top two maximum numbers in the
given array. You should not use any sorting functions. You
should iterate the array only once. You should not use any
kind of collections in java.
package com.java2novice.algos;
public class TwoMaxNumbers {
public void printTwoMaxNumbers(int[] nums){
int maxOne = 0;
int maxTwo = 0;
for(int n:nums){
if(maxOne < n){
maxTwo = maxOne;
maxOne =n;
} else if(maxTwo < n){
maxTwo = n;
}
}
System.out.println("First Max Number: "+maxOne);
System.out.println("Second Max Number: "+maxTwo);
}
public static void main(String a[]){
int num[] = {5,34,78,2,45,1,99,23};
TwoMaxNumbers tmn = new TwoMaxNumbers();
tmn.printTwoMaxNumbers(num);
}
}
Output:
First Max Number: Second Max Number:
Description:
Sort or order a HashMap or TreeSet or any map item by value. Write a comparator
which compares by value, not by key. Entry class might hleps you here.
49
Sat 1/6/2018
package com.java2novice.algos;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class OrderByValue {
public static void main(String a[]){
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("java", 20);
map.put("C++", 45);
map.put("Java2Novice", 2);
map.put("Unix", 67);
map.put("MAC", 26);
map.put("Why this kolavari", 93);
Set<Entry<String, Integer>> set = map.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String,
Integer>>(set);
Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
{
public int compare( Map.Entry<String, Integer> o1, Map.Entry<String,
Integer> o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
for(Map.Entry<String, Integer> entry:list){
System.out.println(entry.getKey()+" ==== "+entry.getValue());
}
}
}
Output:
Why this kolavari ==== Unix ==== C++ ==== MAC ==== java ==== Java2Novice ====
90. Program: Write a program to find common elements between two arrays.
Description:
Write a program to identify common elements or numbers between
two given arrays. You should not use any inbuilt methods are list to
find common values.
package com.java2novice.algos;
public class CommonElementsInArray {
public static void main(String a[]){
int[] arr1 = {4,7,3,9,2};
int[] arr2 = {3,2,12,9,40,32,4};
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i]==arr2[j]){
50
Sat 1/6/2018
System.out.println(arr1[i]);
}
}
}
}
}
Output:
91. Program: How to swap two numbers without using temporary variable?
Description:
Write a program to swap or exchange two numbers. You should
not use any temporary or third variable to swap.
package com.java2novice.algos;
public class MySwapingTwoNumbers {
public static void main(String a[]){
int x = 10;
int y = 20;
System.out.println("Before swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
x = x+y;
y=x-y;
x=x-y;
System.out.println("After swap:");
System.out.println("x value: "+x);
System.out.println("y value: "+y);
}
}
Output:
Before swap:
x value: y value: After swap:
x value: y value:
Description:
In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144... By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each
subsequent number is the sum of the previous two. Below example shows how to create fibonacci series.
package com.java2novice.algos;
51
Sat 1/6/2018
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
93. Program: Write a program to find sum of each digit in the given number using recursion.
Description:
Below example shows how to find out sum of each digit in the given number using recursion logic. For example, if the number is 259,
then the sum should be 2+5+9 = 16.
package com.java2novice.algos;
public class MyNumberSumRec {
int sum = 0;
public int getNumberSum(int number){
if(number == 0){
return sum;
} else {
sum += (number%10);
getNumberSum(number/10);
}
return sum;
}
public static void main(String a[]){
MyNumberSumRec mns = new MyNumberSumRec();
System.out.println("Sum is: "+mns.getNumberSum(223));
}
}
Output:
52
Sat 1/6/2018
Sum is:
94. Program: Write a program to check the given number is a prime number or not?
Description:
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number
greater than 1 that is not a prime number is called a composite number. For example, 5 is prime, as only 1 and 5 divide it, whereas 6 is
composite, since it has the divisors 2 and 3 in addition to 1 and 6. The fundamental theorem of arithmetic establishes the central role
of primes in number theory: any integer greater than 1 can be expressed as a product of primes that is unique up to ordering. This
theorem requires excluding 1 as a prime.
package com.java2novice.algos;
public class MyPrimeNumCheck {
public boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
public static void main(String a[]){
MyPrimeNumCheck mpc = new MyPrimeNumCheck();
System.out.println("Is 17 prime number? "+mpc.isPrimeNumber(17));
System.out.println("Is 19 prime number? "+mpc.isPrimeNumber(19));
System.out.println("Is 15 prime number? "+mpc.isPrimeNumber(15));
}
}
Output:
Is 17 prime number? true
Is 19 prime number? true
Is 15 prime number? false
95. Program: Write a program to find the given number is Armstrong number or not?
Description:
Armstrong numbers are the sum of their own digits to the power of
the number of digits. It is also known as narcissistic numbers.
53
Sat 1/6/2018
package com.java2novice.algos;
public class MyArmstrongNumber {
public boolean isArmstrongNumber(int number){
int tmp = number;
int noOfDigits = String.valueOf(number).length();
int sum = 0;
int div = 0;
while(tmp > 0)
{
div = tmp % 10;
int temp = 1;
for(int i=0;i<noOfDigits;i++){
temp *= div;
}
sum += temp;
tmp = tmp/10;
}
if(number == sum) {
return true;
} else {
return false;
}
}
public static void main(String a[]){
MyArmstrongNumber man = new MyArmstrongNumber();
System.out.println("Is 371 Armstrong number? "+man.isArmstrongNumber(371));
System.out.println("Is 523 Armstrong number? "+man.isArmstrongNumber(523));
System.out.println("Is 153 Armstrong number? "+man.isArmstrongNumber(153));
}
}
Output:
Is 371 Armstrong number? true
Is 523 Armstrong number? false
Is 153 Armstrong number? true
Description:
Write a program to convert binary format to decimal number using numeric operations. Below example shows how to convert binary
to decimal format using numeric operations.
package com.java2novice.algos;
public class BinaryToDecimal {
54
Sat 1/6/2018
Output:
11 ===> 110 ===> 100110 ===>
97. Program: Write a program to check the given number is binary number or not?
Description:
The binary numeral system, or base-2 number system, represents numeric values using two symbols: 0 and 1. More specifically, the
usual base-2 system is a positional notation with a radix of 2. Because of its straightforward implementation in digital electronic
circuitry using logic gates, the binary system is used internally by almost all modern computers.
package com.java2novice.algos;
public class MyBinaryCheck {
public boolean isBinaryNumber(int binary){
boolean status = true;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
if(tmp > 1){
status = false;
break;
}
55
Sat 1/6/2018
binary = binary/10;
}
}
return status;
}
public static void main(String a[]){
MyBinaryCheck mbc = new MyBinaryCheck();
System.out.println("Is 1000111 binary? :"+mbc.isBinaryNumber(1000111));
System.out.println("Is 10300111 binary? :"+mbc.isBinaryNumber(10300111));
}
}
Output:
Is 1000111 binary? :true
Is 10300111 binary? :false
Description:
Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of
adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed,
which indicates that the list is sorted. The algorithm gets its name from the way smaller elements bubble to the top of the list. Because
it only uses comparisons to operate on elements, it is a comparison sort. You can see the code implementation below:
package com.java2novice.algos;
public class MyBubbleSort {
// logic to sort the elements
public static void bubble_srt(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (array[i] > array[k]) {
swapNumbers(i, k, array);
}
}
printNumbers(array);
}
}
private static void swapNumbers(int i, int j, int[] array) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static void printNumbers(int[] input) {
56
Sat 1/6/2018
Output:
2, 4, 6, 9, 12, 23, 0, 1, 34,
Description:
Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists
than more advanced algorithms such as quicksort, heapsort, or merge sort. Every repetition of insertion sort removes an element from
the input data, inserting it into the correct position in the already-sorted list, until no input elements remain. The choice of which
element to remove from the input is arbitrary, and can be made using almost any choice algorithm. You can see the code
implementation below:
package com.java2novice.algos;
public class MyInsertionSort {
public static void main(String[] args) {
57
Sat 1/6/2018
Output:
2, 4, 9, 6, 23, 12, 34, 0, 1,
Description:
The hashcode of a Java Object is simply a number, it is 32-bit signed int, that allows an object to be managed by a hash-based data
structure. We know that hash code is an unique id number allocated to an object by JVM. But actually speaking, Hash code is not an
unique number for an object. If two objects are equals then these two objects should return same hash code. So we have to implement
hashcode() method of a class in such way that if two objects are equals, ie compared by equal() method of that class, then those two
objects must return same hash code. If you are overriding hashCode you need to override equals method also. The below example
shows how to override equals and hashcode methods. The class Price overrides equals and hashcode. If you notice the hashcode
58
Sat 1/6/2018
implementation, it always generates unique hashcode for each object based on their state, ie if the object state is same, then you will
get same hashcode. A HashMap is used in the example to store Price objects as keys. It shows though we generate different objects,
but if state is same, still we can use this as key.
package com.java2novice.algos;
import java.util.HashMap;
public class MyHashcodeImpl {
public static void main(String a[]){
HashMap<Price, String> hm = new HashMap<Price, String>();
hm.put(new Price("Banana", 20), "Banana");
hm.put(new Price("Apple", 40), "Apple");
hm.put(new Price("Orange", 30), "Orange");
//creating new object to use as key to get value
Price key = new Price("Banana", 20);
System.out.println("Hashcode of the key: "+key.hashCode());
System.out.println("Value from map: "+hm.get(key));
}
}
class Price{
private String item;
private int price;
public Price(String itm, int pr){
this.item = itm;
this.price = pr;
}
public int hashCode(){
System.out.println("In hashcode");
int hashcode = 0;
hashcode = price*20;
hashcode += item.hashCode();
return hashcode;
}
public boolean equals(Object obj){
System.out.println("In equals");
if (obj instanceof Price) {
Price pp = (Price) obj;
return (pp.item.equals(this.item) && pp.price == this.price);
} else {
return false;
}
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String toString(){
59
Sat 1/6/2018
Output:
In hashcode
In hashcode
In hashcode
In hashcode
Hashcode of the key: 19824796In hashcode
In equals
Value from map: Banana
101. Program: How to get distinct elements from an array by avoiding duplicate elements?
Description:
The below example shows how to avoid duplicate elements from an array and disply only distinct elements. Please use only arrays to
process it.
package com.java2novice.algos;
public class MyDisticntElements {
public static void printDistinctElements(int[] arr){
for(int i=0;i<arr.length;i++){
boolean isDistinct = false;
for(int j=0;j<i;j++){
if(arr[i] == arr[j]){
isDistinct = true;
break;
}
}
if(!isDistinct){
System.out.print(arr[i]+" ");
}
}
}
public static void main(String a[]){
int[] nums = {5,2,7,2,4,7,8,2,3};
MyDisticntElements.printDistinctElements(nums);
}
}
Output:
5 2 7 4 8 3
60
Sat 1/6/2018
102. Program: Write a program to get distinct word list from the given file.
Description:
Write a program to find all distinct words from the given file. Remove special chars like ".,;:" etc. Ignore case sensitivity.
package com.java2novice.algos;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class MyDistinctFileWords {
public List<String> getDistinctWordList(String fileName){
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
List<String> wordList = new ArrayList<String>();
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while((line = br.readLine()) != null){
StringTokenizer st = new StringTokenizer(line, " ,.;:\"");
while(st.hasMoreTokens()){
String tmp = st.nextToken().toLowerCase();
if(!wordList.contains(tmp)){
wordList.add(tmp);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{if(br != null) br.close();}catch(Exception ex){}
}
return wordList;
}
public static void main(String a[]){
MyDistinctFileWords distFw = new MyDistinctFileWords();
List<String> wordList = distFw.getDistinctWordList("C:/sample.txt");
for(String str:wordList){
System.out.println(str);
}
}
61
Sat 1/6/2018
Output:
the
while
statement
verifies
condition
before
entering
into
loop
to
see
whether
next
iteration
should
occur
or
not
do-while
executes
first
without
checking
it
after
finishing
each
will
always
execute
body
of
a
at
least
once
103. Program: Write a program to get a line with max word count from the given file.
Description:
Below example shows how to find out the line with maximum number of word count in the given file. In case if it has multiple lines
with max number of words, then it has to list all those lines.
package com.java2novice.algos;
import java.io.BufferedReader;
import java.io.DataInputStream;
62
Sat 1/6/2018
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MaxWordCountInLine {
private int currentMaxCount = 0;
private List<String> lines = new ArrayList<String>();
public void readMaxLineCount(String fileName){
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while((line = br.readLine()) != null){
int count = (line.split("\\s+")).length;
if(count > currentMaxCount){
lines.clear();
lines.add(line);
currentMaxCount = count;
} else if(count == currentMaxCount){
lines.add(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{
if(br != null) br.close();
}catch(Exception ex){}
}
}
public int getCurrentMaxCount() {
return currentMaxCount;
}
public void setCurrentMaxCount(int currentMaxCount) {
this.currentMaxCount = currentMaxCount;
}
public List<String> getLines() {
return lines;
}
public void setLines(List<String> lines) {
this.lines = lines;
}
public static void main(String a[]){
MaxWordCountInLine mdc = new MaxWordCountInLine();
mdc.readMaxLineCount("/Users/ngootooru/MyTestFile.txt");
System.out.println("Max number of words in a line is:
"+mdc.getCurrentMaxCount());
System.out.println("Line with max word count:");
63
Sat 1/6/2018
MyTestFile.txt:
true, false, and null might seem like keywords, but they are actually literals.
You cannot use them as identifiers in your programs. The servlet context
is an interface which helps to communicate with other servlets. It contains
information about the Web application and container. It is kind of
application environment. Using the context, a servlet can obtain URL
references to resources, and store attributes that other servlets in the
context can use.
Output:
Max number of words in a line is: Line with max word count:
true, false, and null might seem like keywords, but they are actually literals.
104. Program: Write a program to convert string to number without using Integer.parseInt() method.
Description:
Below example shows how to convert string format of a number to number without calling Integer.parseInt() method. We can do this
by converting each character into ascii format and form the number.
package com.java2novice.algos;
public class MyStringToNumber {
public static int convert_String_To_Number(String numStr){
char ch[] = numStr.toCharArray();
int sum = 0;
//get ascii value for zero
int zeroAscii = (int)'0';
for(char c:ch){
int tmpAscii = (int)c;
sum = (sum*10)+(tmpAscii-zeroAscii);
}
return sum;
}
public static void main(String a[]){
System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
System.out.println("\"76289\" == "+convert_String_To_Number("76289"));
System.out.println("\"90087\" == "+convert_String_To_Number("90087"));
}
}
64
Sat 1/6/2018
Output:
"3256" == 32"76289" == 762"90087" == 90Program:
105. Write a program to find two lines with max characters in descending order.
Description:
Write a program to read a multiple line text file and write the 'N' longest lines to the output console, where the file to be read is
specified as command line aruguments. The program should read an input file. The first line should contain the value of the number
'N' followed by multiple lines. 'N' should be a valid positive integer.
package com.longest.lines;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
BufferedReader br = null;
String filePath = args[0];
int topList = 0;
Set<Entries> liSet = new TreeSet<Entries>(new MyComp());
try {
br = new BufferedReader(new FileReader(new File(filePath)));
String line = br.readLine();
topList = Integer.parseInt(line.trim());
while((line = br.readLine()) != null){
line = line.trim();
if(!"".equals(line)){
liSet.add(new Entries(line.length(), line));
}
}
int count = 0;
for(Entries ent:liSet){
System.out.println(ent.line);
if(++count == topList){
break;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
65
Sat 1/6/2018
Output:
This is a test program
I know java language
My Test line
106. Program: Write a program to find the sum of the first 1000 prime numbers.
Description:
Write a program to find the sum of the first 1000 prime numbers.
package com.primesum;
public class Main {
public static void main(String args[]){
int number = 2;
int count = 0;
long sum = 0;
while(count < 1000){
66
Sat 1/6/2018
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
Output:
3682<<
Description:
Given a string, find the longest substrings without repeating characters. Iterate through the given string, find the
longest maximum substrings.
package com.java2novice.algos;
import java.util.HashSet;
import java.util.Set;
public class MyLongestSubstr {
private Set<String> subStrList = new HashSet<String>();
private int finalSubStrSize = 0;
public Set<String> getLongestSubstr(String input){
//reset instance variables
subStrList.clear();
finalSubStrSize = 0;
// have a boolean flag on each character ascii value
boolean[] flag = new boolean[256];
int j = 0;
char[] inputCharArr = input.toCharArray();
for (int i = 0; i < inputCharArr.length; i++) {
char c = inputCharArr[i];
if (flag[c]) {
extractSubString(inputCharArr,j,i);
for (int k = j; k < i; k++) {
if (inputCharArr[k] == c) {
j = k + 1;
break;
}
67
Sat 1/6/2018
flag[inputCharArr[k]] = false;
}
} else {
flag[c] = true;
}
}
extractSubString(inputCharArr,j,inputCharArr.length);
return subStrList;
}
private String extractSubString(char[] inputArr, int start, int end){
StringBuilder sb = new StringBuilder();
for(int i=start;i<end;i++){
sb.append(inputArr[i]);
}
String subStr = sb.toString();
if(subStr.length() > finalSubStrSize){
finalSubStrSize = subStr.length();
subStrList.clear();
subStrList.add(subStr);
} else if(subStr.length() == finalSubStrSize){
subStrList.add(subStr);
}
return sb.toString();
}
public static void main(String a[]){
MyLongestSubstr mls = new MyLongestSubstr();
System.out.println(mls.getLongestSubstr("java2novice"));
System.out.println(mls.getLongestSubstr("java_language_is_sweet"));
System.out.println(mls.getLongestSubstr("java_java_java_java"));
System.out.println(mls.getLongestSubstr("abcabcbb"));
}
}
Output:
[a2novice]
[uage_is]
[_jav, va_j]
[cab, abc, bca]
Description:
Given array is already sorted, and it has duplicate elements. Write a program to remove duplicate elements and return
new array without any duplicate elements. The array should contain only unique elements.
package com.java2novice.algos;
public class MyDuplicateElements {
public static int[] removeDuplicates(int[] input){
int j = 0;
68
Sat 1/6/2018
int i = 1;
//return if the array length is less than if(input.length < 2){
return input;
}
while(i < input.length){
if(input[i] == input[j]){
i++;
}else{
input[++j] = input[i++];
}
}
int[] output = new int[j+1];
for(int k=0; k<output.length; k++){
output[k] = input[k];
}
return output;
}
public static void main(String a[]){
int[] input1 = {2,3,6,6,8,9,10,10,10,12,12};
int[] output = removeDuplicates(input1);
for(int i:output){
System.out.print(i+" ");
}
}
}
Output:
2 3 6 8 9 10 12
Description:
You have a stack with full of integers. Sort it in the ascending order using another temporary array by using all stack
functionality.
package com.java2novice.algo;
import java.util.Stack;
public class StackSort {
public static Stack<Integer> sortStack(Stack<Integer> input){
Stack<Integer> tmpStack = new Stack<Integer>();
System.out.println("=============== debug logs ================");
while(!input.isEmpty()) {
int tmp = input.pop();
System.out.println("Element taken out: "+tmp);
while(!tmpStack.isEmpty() && tmpStack.peek() > tmp) {
input.push(tmpStack.pop());
}
tmpStack.push(tmp);
System.out.println("input: "+input);
System.out.println("tmpStack: "+tmpStack);
}
System.out.println("=============== debug logs ended ================");
return tmpStack;
69
Sat 1/6/2018
}
public static void main(String a[]){
Stack<Integer> input = new Stack<Integer>();
input.add(34);
input.add(3);
input.add(31);
input.add(98);
input.add(92);
input.add(23);
System.out.println("input: "+input);
System.out.println("final sorted list: "+sortStack(input));
}
}
Output:
input: [34, 3, 31, 98, 92, 23]
=============== debug logs ================
Element taken out: input: [34, 3, 31, 98, 92]
tmpStack: [23]
Element taken out: input: [34, 3, 31, 98]
tmpStack: [23, 92]
Element taken out: input: [34, 3, 31]
tmpStack: [23, 92, 98]
Element taken out: input: [34, 3, 98, 92]
tmpStack: [23, 31]
Element taken out: input: [34, 3, 98]
tmpStack: [23, 31, 92]
Element taken out: input: [34, 3]
tmpStack: [23, 31, 92, 98]
Element taken out: input: [34, 98, 92, 31, 23]
tmpStack: [3]
Element taken out: input: [34, 98, 92, 31]
tmpStack: [3, 23]
Element taken out: input: [34, 98, 92]
tmpStack: [3, 23, 31]
Element taken out: input: [34, 98]
tmpStack: [3, 23, 31, 92]
Element taken out: input: [34]
tmpStack: [3, 23, 31, 92, 98]
Element taken out: input: [98, 92]
tmpStack: [3, 23, 31, 34]
Element taken out: input: [98]
tmpStack: [3, 23, 31, 34, 92]
Element taken out: input: []
tmpStack: [3, 23, 31, 34, 92, 98]
70
Sat 1/6/2018
Bubble sort, also referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through
the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The
pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets
its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on
elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more
efficient for large lists.
71
Sat 1/6/2018
Bubble sort has worst-case and average complexity both О(n2), where n is the number of items being sorted. There
exist many sorting algorithms with substantially better worst-case or average complexity of O(n log n). Even other
О(n2) sorting algorithms, such as insertion sort, tend to have better performance than bubble sort. Therefore, bubble
sort is not a practical sorting algorithm when n is large.Performance of bubble sort over an already-sorted list (best-
case) is O(n).
package com.java2novice.algos;
public class MyBubbleSort {
72
Sat 1/6/2018
Output:
2, 4, 6, 9, 12, 23, 0, 1, 34,
73
Sat 1/6/2018
The selection sort is a combination of searching and sorting. During each pass, the unsorted element with the
smallest (or largest) value is moved to its proper position in the array. The number of times the sort passes through
the array is one less than the number of items in the array. In the selection sort, the inner loop finds the next smallest
(or largest) value and the outer loop places that value into its proper location.
Selection sort is not difficult to analyze compared to other sorting algorithms since none of the loops depend on the data
in the array. Selecting the lowest element requires scanning all n elements (this takesn − 1 comparisons) and then
swapping it into the first position. Finding the next lowest element requires scanning the remaining n − 1 elements and so
on, for (n − 1) + (n − 2) + ... + 2 + 1 = n(n − 1) / 2 ∈ Θ(n2) comparisons. Each of these scans requires one swap for n − 1
elements.
package com.java2novice.algos;
public class MySelectionSort {
public static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
74
Sat 1/6/2018
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
public static void main(String a[]){
int[] arr1 = {10,34,2,56,7,67,88,42};
int[] arr2 = doSelectionSort(arr1);
for(int i:arr2){
System.out.print(i);
System.out.print(", ");
}
}
}
Output:
2, 7, 10, 34, 42, 56, 67, 88,
Insertion sort is a simple sorting algorithm, it builds the final sorted array one item at a time. It is much less efficient on
large lists than other sort algorithms.
Advantages of Insertion Sort: 1) It is very simple.2) It is very efficient for small data sets.3) It is stable; i.e., it does not
change the relative order of elements with equal keys.4) In-place; i.e., only requires a constant amount O(1) of additional
memory space.
Insertion sort iterates through the list by consuming one input element at each repetition, and growing a sorted output list.
On a repetition, insertion sort removes one element from the input data, finds the location it belongs within the sorted list,
and inserts it there. It repeats until no input elements remain.
Image
source: “Introduction to Algorithms”, The MIT Press
The best case input is an array that is already sorted. In this case insertion sort has a linear running time (i.e., Θ(n)).
During each iteration, the first remaining element of the input is only compared with the right-most element of the sorted
75
Sat 1/6/2018
subsection of the array. The simplest worst case input is an array sorted in reverse order. The set of all worst case inputs
consists of all arrays where each element is the smallest or second-smallest of the elements before it. In these cases
every iteration of the inner loop will scan and shift the entire sorted subsection of the array before inserting the next
element. This gives insertion sort a quadratic running time (i.e., O(n2)). The average case is also quadratic, which makes
insertion sort impractical for sorting large arrays. However, insertion sort is one of the fastest algorithms for sorting very
small arrays, even faster than quicksort; indeed, good quicksort implementations use insertion sort for arrays smaller than
a certain threshold, also when arising as subproblems; the exact threshold must be determined experimentally and
depends on the machine, but is commonly around ten.
package com.java2novice.algos;
public class MyInsertionSort {
public static void main(String a[]){
int[] arr1 = {10,34,2,56,7,67,88,42};
int[] arr2 = doInsertionSort(arr1);
for(int i:arr2){
System.out.print(i);
System.out.print(", ");
}
}
public static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
}
Output:
2, 7, 10, 34, 42, 56, 67, 88,
76
Sat 1/6/2018
Quicksort or partition-exchange sort, is a fast sorting algorithm, which is using divide and conquer algorithm. Quicksort
first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively
sort the sub-lists.
Steps to implement Quick sort:1) Choose an element, called pivot, from the list. Generally pivot can be the middle index
element.2) Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements
with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its
final position. This is called the partition operation.3) Recursively apply the above steps to the sub-list of elements with
smaller values and separately the sub-list of elements with greater values.
The complexity of quick sort in the average case is Θ(n log(n)) and in the worst case is Θ(n2).
package com.java2novice.sorting;
public class MyQuickSort {
private int array[];
private int length;
77
Sat 1/6/2018
Output:
78
Sat 1/6/2018
2 2 12 20 24 45 53 56 56 75 99
79
Sat 1/6/2018
Merge sort is a fast, stable sorting routine with guaranteed O(n*log(n)) efficiency. When sorting arrays, merge sort
requires additional scratch space proportional to the size of the input array. Merge sort is relatively simple to code and
offers performance typically only slightly below that of quicksort.
package com.java2novice.sorting;
public class MyMergeSort {
private int[] array;
private int[] tempMergArr;
private int length;
public static void main(String a[]){
int[] inputArr = {45,23,11,89,77,98,4,28,65,43};
MyMergeSort mms = new MyMergeSort();
80
Sat 1/6/2018
mms.sort(inputArr);
for(int i:inputArr){
System.out.print(i);
System.out.print(" ");
}
}
public void sort(int inputArr[]) {
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex) {
for (int i = lowerIndex; i <= higherIndex; i++) {
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (tempMergArr[i] <= tempMergArr[j]) {
array[k] = tempMergArr[i];
i++;
} else {
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) {
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
Output:
4 11 23 28 43 45 65 77 89 98
81
Sat 1/6/2018
The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes
which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the
smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod,
obeying the following rules:
1) Only one disk must be moved at a time.
2) Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other
disks that may already be present on that rod.
3) No disk may be placed on top of a smaller disk.
In this example, we are solving it by using stacks.
package com.java2novice.ds.stack;
public class TowersOfHanoiImpl {
private static MyDynamicStack[] tower;
public static void towersOfHanoi(int n) {
// create three stacks, tower[0] is scratch
tower = new MyDynamicStack[4];
for (int i = 0; i <= 3; i++){
tower[i] = new MyDynamicStack(4);
}
for (int d = n; d > 0; d--){
// initialize
// add disk d to tower tower[1].push(new Integer(d));
}
// move n disks from tower 1 to 2 using 3 as
// intermediate tower
showTowerStates(n, 1, 2, 3);
}
public static void showTowerStates(int n, int x, int y, int z) {
if (n > 0) {
try{
showTowerStates(n - 1, x, z, y);
// move d from top of tower x
Integer d = (Integer) tower[x].pop();
// to top of tower y
tower[y].push(d);
System.out.println("Move disk " + d
+ " from tower "+ x + " to top of tower " + y);
showTowerStates(n - 1, z, y, x);
} catch(Exception ex){}
}
}
public static void main(String[] args) {
System.out.println("Running 3 disk problem:");
towersOfHanoi(3);
}
}
public class MyDynamicStack {
private int stackSize;
private int[] stackArr;
private int top;
82
Sat 1/6/2018
/**
* constructor to create stack with size
* @param size
*/
public MyDynamicStack(int size) {
this.stackSize = size;
this.stackArr = new int[stackSize];
this.top = -1;
}
/**
* This method adds new entry to the top
* of the stack
* @param entry
* @throws Exception
*/
public void push(int entry){
if(this.isStackFull()){
System.out.println(("Stack is full. Increasing the capacity."));
this.increaseStackCapacity();
}
this.stackArr[++top] = entry;
}
/**
* This method removes an entry from the
* top of the stack.
* @return
* @throws Exception
*/
public int pop() throws Exception {
if(this.isStackEmpty()){
throw new Exception("Stack is empty. Can not remove element.");
}
int entry = this.stackArr[top--];
return entry;
}
/**
* This method returns top of the stack
* without removing it.
* @return
*/
public long peek() {
return stackArr[top];
}
private void increaseStackCapacity(){
int[] newStack = new int[this.stackSize*2];
for(int i=0;i<stackSize;i++){
newStack[i] = this.stackArr[i];
}
this.stackArr = newStack;
this.stackSize = this.stackSize*2;
}
/**
* This method returns true if the stack is
* empty
* @return
*/
public boolean isStackEmpty() {
return (top == -1);
}
/**
* This method returns true if the stack is full
83
Sat 1/6/2018
* @return
*/
public boolean isStackFull() {
return (top == stackSize - 1);
}
public static void main(String[] args) {
MyDynamicStack stack = new MyDynamicStack(2);
for(int i=1;i<10;i++){
stack.push(i);
}
for(int i=1;i<4;i++){
try {
stack.pop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Output:
Running 3 disk problem:
Move disk 1 from tower 1 to top of tower Move disk 2 from tower 1 to top of tower Move disk 1 from tower 2 to top of tower
Move disk 3 from tower 1 to top of tower Move disk 1 from tower 3 to top of tower Move disk 2 from tower 3 to top of tower
Move disk 1 from tower 1 to top of tower
84
Sat 1/6/2018
A Stack is an abstract data type or collection where in Push,the addition of data elements to the collection, and Pop, the
removal of data elements from the collection, are the major operations performed on the collection. The Push and Pop
operations are performed only at one end of the Stack which is referred to as the 'top of the stack'.
In other words,a Stack can be simply defined as Last In First Out (LIFO) data structure,i.e.,the last element added at the
top of the stack(In) should be the first element to be removed(Out) from the stack.
Stack Operations:
Push: A new entity can be added to the top of the collection.Pop: An entity will be removed from the top of the
collection.Peek or Top: Returns the top of the entity with out removing it.
Overflow State: A stack may be implemented to have a bounded capacity. If the stack is full and does not contain enough
space to accept an entity to be pushed, the stack is then considered to be in an overflow state.
Underflow State: The pop operation removes an item from the top of the stack. A pop either reveals previously concealed
items or results in an empty stack, but, if the stack is empty, it goes into underflow state, which means no items are
present in stack to be removed.
A stack is a restricted data structure, because only a small number of operations are performed on it. The nature of the
pop and push operations also means that stack elements have a natural order. Elements are removed from the stack in
the reverse order to the order of their addition. Therefore, the lower elements are those that have been on the stack the
longest.
Efficiency of Stacks
In the stack, the elements can be push or pop one at a time in constant O(1) time. That is, the time is not dependent on
how many items are in the stack and is therefore very quick. No comparisons or moves are necessary.
package com.java2novice.ds.stack;
public class MyStackImpl {
private int stackSize;
private int[] stackArr;
private int top;
/**
* constructor to create stack with size
* @param size
*/
public MyStackImpl(int size) {
this.stackSize = size;
this.stackArr = new int[stackSize];
this.top = -1;
}
/**
* This method adds new entry to the top
* of the stack
* @param entry
* @throws Exception
*/
public void push(int entry) throws Exception {
if(this.isStackFull()){
throw new Exception("Stack is already full. Can not add element.");
}
System.out.println("Adding: "+entry);
this.stackArr[++top] = entry;
}
85
Sat 1/6/2018
/**
* This method removes an entry from the
* top of the stack.
* @return
* @throws Exception
*/
public int pop() throws Exception {
if(this.isStackEmpty()){
throw new Exception("Stack is empty. Can not remove element.");
}
int entry = this.stackArr[top--];
System.out.println("Removed entry: "+entry);
return entry;
}
/**
* This method returns top of the stack
* without removing it.
* @return
*/
public int peek() {
return stackArr[top];
}
/**
* This method returns true if the stack is
* empty
* @return
*/
public boolean isStackEmpty() {
return (top == -1);
}
/**
* This method returns true if the stack is full
* @return
*/
public boolean isStackFull() {
return (top == stackSize - 1);
}
public static void main(String[] args) {
MyStackImpl stack = new MyStackImpl(5);
try {
stack.push(4);
stack.push(8);
stack.push(3);
stack.push(89);
stack.pop();
stack.push(34);
stack.push(45);
stack.push(78);
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
stack.pop();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
86
Sat 1/6/2018
Output:
Adding: Adding: Adding: Adding: Removed entry: Adding: Adding: Stack is already full. Can
not add element.
Removed entry: Removed entry: Removed entry: Removed entry: Removed entry: Stack is
empty. Can not remove element.
87
Sat 1/6/2018
A queue is a kind of abstract data type or collection in which the entities in the collection are kept in order and the only operations on
the collection are the addition of entities to the rear terminal position, called as enqueue, and removal of entities from the front
terminal position, called as dequeue. The queue is called as First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first
element added to the queue will be the first one to be removed. This is equivalent to the requirement that once a new element is added,
all elements that were added before have to be removed before the new element can be removed. Often a peek or front operation is
also entered, returning the value of the front element without dequeuing it. A queue is an example of a linear data structure, or more
abstractly a sequential collection.
Queues provide services in computer science, transport, and operations research where various entities such as data, objects, persons,
or events are stored and held to be processed later. In these contexts, the queue performs the function of a buffer.
Queue Operations:
enqueue: Adds an item onto the end of the queue.front: Returns the item at the front of the queue.dequeue: Removes the item from
the front of the queue.
Overflow State: A queue may be implemented to have a bounded capacity. If the queue is full and does not contain enough space to
accept an entity to be pushed, the queue is then considered to be in an overflow state.
Underflow State: The dequeue operation removes an item from the top of the queue. A dequeue operation either reveals previously
concealed items or results in an empty queue, but, if the queue is empty, it goes into underflow state, which means no items are
present in queue to be removed.
Efficiency of Queue
The time needed to add or delete an item is constant and independent of the number of items in the queue. So both addition and
deletion can be O(1) operation.
package com.java2novice.ds.queue;
public class QueueImpl {
private int capacity;
int queueArr[];
int front = 0;
int rear = -1;
int currentSize = 0;
public QueueImpl(int queueSize){
this.capacity = queueSize;
queueArr = new int[this.capacity];
}
/**
* this method adds element at the end of the queue.
* @param item
*/
public void enqueue(int item) {
if (isQueueFull()) {
System.out.println("Overflow ! Unable to add element: "+item);
} else {
rear++;
if(rear == capacity-1){
rear = 0;
88
Sat 1/6/2018
}
queueArr[rear] = item;
currentSize++;
System.out.println("Element " + item+ " is pushed to Queue !");
}
}
/**
* this method removes an element from the top of the queue
*/
public void dequeue() {
if (isQueueEmpty()) {
System.out.println("Underflow ! Unable to remove element from Queue");
} else {
front++;
if(front == capacity-1){
System.out.println("Pop operation done ! removed: "+queueArr[front-
1]);
front = 0;
} else {
System.out.println("Pop operation done ! removed: "+queueArr[front-
1]);
}
currentSize--;
}
}
/**
* This method checks whether the queue is full or not
* @return boolean
*/
public boolean isQueueFull(){
boolean status = false;
if (currentSize == capacity){
status = true;
}
return status;
}
/**
* This method checks whether the queue is empty or not
* @return
*/
public boolean isQueueEmpty(){
boolean status = false;
if (currentSize == 0){
status = true;
}
return status;
}
public static void main(String a[]){
QueueImpl queue = new QueueImpl(4);
queue.enqueue(4);
queue.dequeue();
queue.enqueue(56);
queue.enqueue(2);
queue.enqueue(67);
queue.dequeue();
queue.dequeue();
queue.enqueue(24);
queue.dequeue();
queue.enqueue(98);
queue.enqueue(45);
queue.enqueue(23);
queue.enqueue(435);
}
89
Sat 1/6/2018
Output:
Element 4 is pushed to Queue !
Pop operation done ! removed: Element 56 is pushed to Queue !
Element 2 is pushed to Queue !
Element 67 is pushed to Queue !
Pop operation done ! removed: Pop operation done ! removed: Element 24 is pushed to Queue
!
Pop operation done ! removed: Element 98 is pushed to Queue !
Element 45 is pushed to Queue !
Element 23 is pushed to Queue !
Overflow ! Unable to add element:
90
Sat 1/6/2018
A linked list is a data structure consisting of a group of nodes which together represent a sequence. Each node is
composed of a data and a link or reference to the next node in the sequence. This structure allows for efficient
insertion or removal of elements from any position in the sequence.The last node is linked to a terminator used
to signify the end of the list.
Linked lists are the simplest and most common data structures. They can be used to implement several other
abstract data types, including lists, stacks, queues, associative arrays, and S-expressions, etc.
The benefits of a linked list over a conventional array is that the linked list elements can easily be inserted or
removed without reallocation or reorganization of the entire structure because the data items need not be stored
contiguously in memory or on disk. Linked lists allow insertion and removal of nodes at any point in the list.
On the other hand, simple linked lists do not allow random access to the data, or by using indexing. Thus, many
basic operations like obtaining the last node of the list, or finding a node with required data, or locating the
place where a new node should be inserted, may require scanning most of the list elements.
Singly Linked Lists are a type of data structure. It is a type of list. In a singly linked list each node in the list stores the contents of the
node and a pointer or reference to the next node in the list. It does not store any pointer or reference to the previous node. It is called a
singly linked list because each node only has a single link to another node. To store a single linked list, you only need to store a
reference or pointer to the first node in that list. The last node has a pointer to nothingness to indicate that it is the last node.
91
Sat 1/6/2018
Here is the pictorial view of inserting an element in the middle of a singly linked list:
Here is the pictorial view of deleting an element in the middle of a singly linked list:
package com.java2novice.ds.linkedlist;
public class SinglyLinkedListImpl<T> {
private Node<T> head;
private Node<T> tail;
public void add(T element){
Node<T> nd = new Node<T>();
nd.setValue(element);
System.out.println("Adding: "+element);
/**
* check if the list is empty
*/
if(head == null){
//since there is only one element, both head and
//tail points to the same object.
head = nd;
92
Sat 1/6/2018
tail = nd;
} else {
//set current tail next link to new node
tail.setNextRef(nd);
//set tail as newly created node
tail = nd;
}
}
public void addAfter(T element, T after){
Node<T> tmp = head;
Node<T> refNode = null;
System.out.println("Traversing to all nodes..");
/**
* Traverse till given element
*/
while(true){
if(tmp == null){
break;
}
if(tmp.compareTo(after) == 0){
//found the target node, add after this node
refNode = tmp;
break;
}
tmp = tmp.getNextRef();
}
if(refNode != null){
//add element after the target node
Node<T> nd = new Node<T>();
nd.setValue(element);
nd.setNextRef(tmp.getNextRef());
if(tmp == tail){
tail = nd;
}
tmp.setNextRef(nd);
} else {
System.out.println("Unable to find the given element...");
}
}
public void deleteFront(){
if(head == null){
System.out.println("Underflow...");
}
Node<T> tmp = head;
head = tmp.getNextRef();
if(head == null){
tail = null;
}
System.out.println("Deleted: "+tmp.getValue());
}
public void deleteAfter(T after){
Node<T> tmp = head;
Node<T> refNode = null;
System.out.println("Traversing to all nodes..");
/**
* Traverse till given element
*/
while(true){
if(tmp == null){
break;
}
93
Sat 1/6/2018
if(tmp.compareTo(after) == 0){
//found the target node, add after this node
refNode = tmp;
break;
}
tmp = tmp.getNextRef();
}
if(refNode != null){
tmp = refNode.getNextRef();
refNode.setNextRef(tmp.getNextRef());
if(refNode.getNextRef() == null){
tail = refNode;
}
System.out.println("Deleted: "+tmp.getValue());
} else {
System.out.println("Unable to find the given element...");
}
}
public void traverse(){
Node<T> tmp = head;
while(true){
if(tmp == null){
break;
}
System.out.println(tmp.getValue());
tmp = tmp.getNextRef();
}
}
public static void main(String a[]){
SinglyLinkedListImpl<Integer> sl = new SinglyLinkedListImpl<Integer>();
sl.add(3);
sl.add(32);
sl.add(54);
sl.add(89);
sl.addAfter(76, 54);
sl.deleteFront();
sl.deleteAfter(76);
sl.traverse();
}
}
class Node<T> implements Comparable<T> {
private T value;
private Node<T> nextRef;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNextRef() {
return nextRef;
}
public void setNextRef(Node<T> ref) {
this.nextRef = ref;
}
@Override
public int compareTo(T arg) {
if(arg == this.value){
return 0;
} else {
return 1;
94
Sat 1/6/2018
}
}
}
Output:
Adding: Adding: Adding: Adding: Traversing to all nodes..
Deleted: Traversing to all nodes..
Deleted:
Description:
You can iterate through any collection object by using Iterator object. It provides two methods to iterate. The hasNext() method
returns true if the iteration has more elements. The next() method returns the next element in the iteration. Below example shows how
to iterate through an ArrayList.
package com.java2novice.iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MyCollectionIterator {
public static void main(String a[]){
List<String> myList = new ArrayList<String>();
myList.add("Java");
myList.add("Unix");
myList.add("Oracle");
myList.add("C++");
myList.add("Perl");
Iterator<String> itr = myList.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Java
Unix
Oracle
C++
Perl
95
Sat 1/6/2018
Using ListIterator, we can iterate all elements of a list in either direction. You can access next element by calling next() method, and
also you can access previous element by calling previous() method on the list.
package com.myjava.listiterator;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class MyListIterator {
public static void main(String a[]){
List<Integer> li = new ArrayList<Integer>();
ListIterator<Integer> litr = null;
li.add(23);
li.add(98);
li.add(29);
li.add(71);
li.add(5);
litr=li.listIterator();
System.out.println("Elements in forward directiton");
while(litr.hasNext()){
System.out.println(litr.next());
}
System.out.println("Elements in backward directiton");
while(litr.hasPrevious()){
System.out.println(litr.previous());
}
}
}
Example Output
Elements in forward directiton
Elements in backward directiton
A class that implements Enumeration interface provides access to series of elements one at a time. You need to call nextElement
method to get next element in the series. Also hasMoreElements() method gives you status about the availability of next element in the
series.
package com.myjava.Enumeration;
import java.util.Enumeration;
import java.util.Vector;
public class MyEnumeration {
96
Sat 1/6/2018
Example Output
JAVA
JSP
SERVLET
EJB
PHP
PERL
Description:
Below example shows how to create vector object, adding elements to it, getting elements by specifying index, getting elements index,
getting first element, getting last element, and is vector is empty or not.
package com.java2novice.vector;
import java.util.Vector;
public class BasicVectorOperations {
public static void main(String a[]){
Vector<String> vct = new Vector<String>();
//adding elements to the end
vct.add("First");
vct.add("Second");
vct.add("Third");
System.out.println(vct);
//adding element at specified index
vct.add(2,"Random");
System.out.println(vct);
//getting elements by index
System.out.println("Element at index 3 is: "+vct.get(3));
//getting first element
System.out.println("The first element of this vector is:
"+vct.firstElement());
//getting last element
System.out.println("The last element of this vector is:
"+vct.lastElement());
//how to check vector is empty or not
System.out.println("Is this vector empty? "+vct.isEmpty());
97
Sat 1/6/2018
}
}
Output:
[First, Second, Third]
[First, Second, Random, Third]
Element at index 3 is: Third
The first element of this vector is: First
The last element of this vector is: Third
Is this vector empty? false
Description:
Below example shows basic operations on Hashtable like creating hashtable object, adding key-value pair, getting the value based on
key, checking hashtable is empty or not, removing an element, and size of the hashtable.
package com.java2novice.hashtable;
import java.util.Hashtable;
public class MyHashtableOperations {
public static void main(String a[]){
//Create hashtable instance
Hashtable<String,String> ht = new Hashtable<String,String>();
//add key-value pair to hashtable
ht.put("first", "FIRST INSERTED");
ht.put("second", "SECOND INSERTED");
ht.put("third","THIRD INSERTED");
System.out.println(ht);
//getting value for the given key from hashtable
System.out.println("Value of key 'second': "+ht.get("second"));
System.out.println("Is Hashtable empty? "+ht.isEmpty());
ht.remove("third");
System.out.println(ht);
System.out.println("Size of the Hashtable: "+ht.size());
}
}
Output:
{third=THIRD INSERTED, second=SECOND INSERTED, first=FIRST INSERTED}
Value of key 'second': SECOND INSERTED
Is Hashtable empty? false
98
Sat 1/6/2018
Description:
Below example shows how to read elements from Hashtable. You can iterate through each and every element by getting all keys as set
object. Using each element as a key from set, you can values from Hashtable.
package com.java2novice.hashtable;
import java.util.Hashtable;
import java.util.Set;
public class MyHashtableRead {
public static void main(String a[]){
Hashtable<String, String> hm = new Hashtable<String, String>();
//add key-value pair to Hashtable
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println("Value of "+key+" is: "+hm.get(key));
}
}
}
Output:
{third=THIRD INSERTED, second=SECOND INSERTED, first=FIRST INSERTED}
Value of third is: THIRD INSERTED
Value of second is: SECOND INSERTED
Value of first is: FIRST INSERTED
Description:
Below example shows basic operations on HashSet object like creating object, adding elements, verifying whether the hashset is
empty or not, removing an element, size of the hashset, and to check whether an object exists or not.
99
Sat 1/6/2018
package com.java2novice.hashset;
import java.util.HashSet;
public class MyBasicHashSet {
public static void main(String a[]){
HashSet<String> hs = new HashSet<String>();
//add elements to HashSet
hs.add("first");
hs.add("second");
hs.add("third");
System.out.println(hs);
System.out.println("Is HashSet empty? "+hs.isEmpty());
hs.remove("third");
System.out.println(hs);
System.out.println("Size of the HashSet: "+hs.size());
System.out.println("Does HashSet contains first element?
"+hs.contains("first"));
}
}
Output:
[second, third, first]
Is HashSet empty? false
[second, first]
Size of the HashSet: Does HashSet contains first element? true
Description:
Below example shows how to create LinkedHashSet object, adding elements to it, getting size of LinkedHashSet object, and is the set
empty or not.
package com.java2novice.linkedhashset;
import java.util.LinkedHashSet;
public class MyLkdHashSetOperations {
public static void main(String a[]){
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
//add elements to HashSet
lhs.add("first");
lhs.add("second");
lhs.add("third");
System.out.println(lhs);
System.out.println("LinkedHashSet size: "+lhs.size());
100
Sat 1/6/2018
Output:
[first, second, third]
LinkedHashSet size: Is LinkedHashSet emplty? : false
Description:
Below example shows basic operations on TreeSet like creating object, adding elements to it, verifies elements existance, deleting all
elements at once, size of the set and deleting a specific element.
package com.java2novice.treeset;
import java.util.TreeSet;
public class MyBasicTreeset {
public static void main(String a[]){
TreeSet<String> ts = new TreeSet<String>();
ts.add("one");
ts.add("two");
ts.add("three");
System.out.println("Elements: "+ts);
//check is set empty?
System.out.println("Is set empty: "+ts.isEmpty());
//delete all elements from set
ts.clear();
System.out.println("Is set empty: "+ts.isEmpty());
ts.add("one");
ts.add("two");
ts.add("three");
System.out.println("Size of the set: "+ts.size());
//remove one string
ts.remove("two");
System.out.println("Elements: "+ts);
}
}
Output:
Elements: [one, three, two]
Is set empty: false
Is set empty: true
101
Sat 1/6/2018
Description:
Below example shows basic HashMap functionalities like creating object, adding entries, getting values by passing key, checking is
hashmap is empty or not, deleting an element and size of the HashMap.
package com.java2novice.hashmap;
import java.util.HashMap;
public class MyBasicHashMap {
public static void main(String a[]){
HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
//getting value for the given key from hashmap
System.out.println("Value of second: "+hm.get("second"));
System.out.println("Is HashMap empty? "+hm.isEmpty());
hm.remove("third");
System.out.println(hm);
System.out.println("Size of the HashMap: "+hm.size());
}
}
Output:
{second=SECOND INSERTED, third=THIRD INSERTED, first=FIRST INSERTED}
Value of second: SECOND INSERTED
Is HashMap empty? false
{second=SECOND INSERTED, first=FIRST INSERTED}
Size of the HashMap:
Description:
Below example shows how to read add elements from HashMap. The method keySet() returns all key entries as a set object. Iterating
through each key, we can get corresponding value object.
102
Sat 1/6/2018
package com.java2novice.hashmap;
import java.util.HashMap;
import java.util.Set;
public class MyHashMapRead {
public static void main(String a[]){
HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println("Value of "+key+" is: "+hm.get(key));
}
}
}
Output:
{second=SECOND INSERTED, third=THIRD INSERTED, first=FIRST INSERTED}
Value of second is: SECOND INSERTED
Value of third is: THIRD INSERTED
Value of first is: FIRST INSERTED
Description:
Below example shows basic operations on TreeMap like creating an object, adding key-value pair objects, gtting value by passing key
object, checking whether the map has elements or not, deleting specific entry, and size of the TreeMap.
package com.java2novice.treemap;
import java.util.TreeMap;
public class MyBasicOperations {
public static void main(String a[]){
TreeMap<String, String> hm = new TreeMap<String, String>();
//add key-value pair to TreeMap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
//getting value for the given key from TreeMap
System.out.println("Value of second: "+hm.get("second"));
System.out.println("Is TreeMap empty? "+hm.isEmpty());
hm.remove("third");
System.out.println(hm);
103
Sat 1/6/2018
Output:
{first=FIRST INSERTED, second=SECOND INSERTED, third=THIRD INSERTED}
Value of second: SECOND INSERTED
Is TreeMap empty? false
{first=FIRST INSERTED, second=SECOND INSERTED}
Size of the TreeMap:
Description:
Collections.emptyList() method returns the empty list (immutable). This list is serializable.
package com.java2novice.collections;
import java.util.Collections;
import java.util.List;
public class MyEmptyList {
public static void main(String a[]){
List<String> myEmptyList = Collections.<String>emptyList();
System.out.println("Empty list: "+myEmptyList);
}
}
Output:
Empty list: []
Description:
Collections.checkedList() method returns a dynamically typesafe view of the specified list. Any attempt to insert an element of the
wrong type will result in an immediate ClassCastException. Assuming a list contains no incorrectly typed elements prior to the time a
dynamically typesafe view is generated, and that all subsequent access to the list takes place through the view, it is guaranteed that the
list cannot contain an incorrectly typed element.
104
Sat 1/6/2018
package com.java2novice.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyCheckedList {
public static void main(String a[]){
List myList = new ArrayList();
myList.add("one");
myList.add("two");
myList.add("three");
myList.add("four");
List chkList = Collections.checkedList(myList, String.class);
System.out.println("Checked list content: "+chkList);
//you can add any type of elements to myList object
myList.add(10);
//you cannot add any type of elements to chkList object, doing so
//throws ClassCastException
chkList.add(10); //throws ClassCastException
}
}
Output:
Checked list content: [one, two, three, four]
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class
java.lang.Integer element into
collection with element type class java.lang.String
at java.util.Collections$CheckedCollection.typeCheck(Collections.java:2202)
at java.util.Collections$CheckedCollection.add(Collections.java:2243)
at com.java2novice.collections.MyCheckedList.main(MyCheckedList.java:22)
Description:
Below example shows how to get enumeration object for ArrayList object. Collections.enumeration() method provides enumeration
object.
package com.java2novice.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
public class MyListEnumeration {
public static void main(String a[]){
List<String> ls = new ArrayList<String>();
ls.add("one");
ls.add("two");
105
Sat 1/6/2018
ls.add("three");
ls.add("four");
Enumeration<String> enm = Collections.enumeration(ls);
while(enm.hasMoreElements()){
System.out.println(enm.nextElement());
}
}
}
Output:
one
two
three
four
Description:
Annotations are created by using @ sign, folled by the keyword interface, and followed by annotation name as
shown in the below example.
Members can be decleared as shown in the example, it looks like methods. The example defines two members
called name and desc. We should not provide implementation for these members.
All annotations extends java.lang.annotation.Annotation interface. Annotations cannot include any extends caluse.
Below example shows how to use this annotation to method.
package com.java2novice.annotations;
public @interface MySampleAnn {
String name();
String desc();
}
class MyAnnTest{
@MySampleAnn(name = "test1", desc = "testing annotations")
public void myTestMethod(){
//method implementation
}
}
The worst case of QuickSort occurs when the picked pivot is always one of the corner elements in sorted array. In
106
Sat 1/6/2018
worst case, QuickSort recursively calls one subproblem with size 0 and other subproblem with size (n-1). So
recurrence is T(n) = T(n-1) + T(0) + O(n) The above expression can be rewritten as T(n) = T(n-1) + O(n) 1 void
exchange(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int partition(int arr[], int si, int ei) { int x = arr[ei]; int i
= (si - 1); int j; for (j = si; j <= ei - 1; j++) { if(arr[j] <= x) { i++; exchange(&arr[i], &arr[j]); } } exchange (&arr[i + 1],
&arr[ei]); return (i + 1); } /* Implementation of Quick Sort arr[] --> Array to be sorted si --> Starting index ei --> Ending
index */ void quickSort(int arr[], int si, int ei) { int pi; /* Partitioning index */ if(si < ei) { pi = partition(arr, si, ei);
quickSort(arr, si, pi - 1); quickSort(arr, pi + 1, ei); } } [/sourcecode]
137. Suppose we have a O(n) time algorithm that finds median of an unsorted array. Now consider a QuickSort
implementation where we first find median using the above algorithm, then use median as pivot. What will be
the worst case time complexity of this modified QuickSort.
O(nLogn)
If we use median as a pivot element, then the recurrence for all cases becomes T(n) = 2T(n/2) + O(n) The above
recurrence can be solved using Master Method. It falls in case 2 of master method.
Example:First Pass:( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since
5 > 1.( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2( 1 4 2 5 8 ) –> ( 1 4
2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )( 1
107
Sat 1/6/2018
2 4 5 8 ) –> ( 1 2 4 5 8 )Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )( 1 2 4 5 8 ) –> ( 1 2 4 5
8)
/ Java program for implementation of Bubble Sort
class BubbleSort
{
void bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
/* Prints the array */
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method to test above
public static void main(String args[])
{
BubbleSort ob = new BubbleSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
ob.bubbleSort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
/* This code is contributed by Rajat Mishra */
Output:
Sorted array:
11 12 22 25 34 64 90
Example:First Pass:( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since
5 > 1.( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2( 1 4 2 5 8 ) –> ( 1 4
2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )( 1
2 4 5 8 ) –> ( 1 2 4 5 8 )Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )( 1 2 4 5 8 ) –> ( 1 2 4 5
8)
Recursion Idea.
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr, arr.length);
System.out.println("Sorted array : ");
System.out.println(Arrays.toString(arr));
}
}
Output :
Sorted array :
11 12 22 25 34 64 90
Algorithm// Sort an arr[] of size ninsertionSort(arr, n)Loop from i = 1 to n-1.……a) Pick element arr[i] and insert it into
sorted sequence arr[0…i-1]
110
Sat 1/6/2018
Example:
Another Example: 12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 5 (Size of input array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 1211, 12, 13, 5, 6
i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 1311, 12, 13, 5, 6
i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position ahead of their current
position.5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead of their current
position.5, 6, 11, 12, 13
// Java program for implementation of Insertion Sort
class InsertionSort
{
/*Function to sort array using insertion sort*/
void sort(int arr[])
{
int n = arr.length;
for (int i=1; i<n; ++i)
{
int key = arr[i];
int j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j>=0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
111
Sat 1/6/2018
143. What is Binary Insertion Sort?We can use binary search to reduce the number of comparisons in normal
insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected
item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to
O(logi) by using binary search. The algorithm as a whole still has a running worst case running time of O(n2)
because of the series of swaps required for each insertion. Refer this for implementation.
How to implement Insertion Sort for Linked List?Below is simple insertion sort algorithm for linked list.
1) Create an empty sorted (or result) list
2) Traverse the given list, do following for every node.
......a) Insert current node in sorted way in sorted or result list.
3) Change head of given linked list to head of sorted (or result) list.
Merge Sort
Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for
the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The
merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-
arrays into one. See following C implementation for details.
112
Sat 1/6/2018
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
The following diagram from wikipedia shows the complete merge sort process for an example array {38, 27, 43, 3,
9, 82, 10}. If we take a closer look at the diagram, we can see that the array is recursively divided in two halves till the
size becomes 1. Once the size becomes 1, the merge processes comes into action and starts merging arrays back till
the complete array is merged.
113
Sat 1/6/2018
merge(arr, l, m, r);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};
System.out.println("Given Array");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.length-1);
System.out.println("\nSorted array");
printArray(arr);
}
}
/* This code is contributed by Rajat Mishra */
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and time complexity can
be expressed as following recurrence relation.T(n) = 2T(n/2) + The above recurrence can be solved either
using Recurrence Tree method or Master method. It falls in case II of Master Method and solution of the recurrence is
.Time complexity of Merge Sort is in all 3 cases (worst, average and best) as merge sort
always divides the array in two halves and take linear time to merge two halves.
Auxiliary Space: O(n)
Algorithmic Paradigm: Divide and Conquer
Sorting In Place: No in a typical implementation
Stable: Yes
Applications of Merge Sort
1. In case of linked lists the case is different mainly due to difference in memory allocation of arrays and linked lists.
Unlike arrays, linked list nodes may not be adjacent in memory. Unlike array, in linked list, we can insert items in
the middle in O(1) extra space and O(1) time. Therefore merge operation of merge sort can be implemented
without extra space for linked lists.
In arrays, we can do random access as elements are continuous in memory. Let us say we have an
integer (4-byte) array A and let the address of A[0] be x then to access A[i], we can directly access the
115
Sat 1/6/2018
memory at (x + i*4). Unlike arrays, we can not do random access in linked list. Quick Sort requires a lot
of this kind of access. In linked list to access i’th index, we have to travel each and every node from the
head to i’th node as we don’t have continuous block of memory. Therefore, the overhead increases for
quick sort. Merge sort accesses data sequentially and the need of random access is low.
{
array[k] = left[i];
i++;
k++;
}
while(j < right.length)
{
array[k] = right[j];
j++;
k++;
}
}
}
// Driver program to test above functions.
public static void main(String[] args)
{
int arr[] = {12, 11, 13, 5, 6, 7};
int i=0;
System.out.println("Given array is");
for(i=0; i<arr.length; i++)
System.out.print(arr[i]+" ");
mergeSort(arr);
System.out.println("\n");
System.out.println("Sorted array is");
for(i=0; i<arr.length; i++)
System.out.print(arr[i]+" ");
}
}
// Code Contributed by Mohit Gupta_OMG
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Iterative Merge Sort:The above function is recursive, so uses function call stack to store intermediate values of l
and h. The function call stack stores other bookkeeping information together with parameters. Also, function calls
involve overheads like storing activation record of the caller function and then resuming execution. Unlike Iterative
QuickSort, the iterative MergeSort doesn’t require explicit auxiliary stack.The above function can be easily
converted to iterative version. Following is iterative Merge Sort.
/* Iterative C program for merge sort */
#include<stdlib.h>
#include<stdio.h>
/* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */
void merge(int arr[], int l, int m, int r);
// Utility function to find minimum of two integers
int min(int x, int y) { return (x<y)? x :y; }
{
arr[k] = R[j];
j++;
k++;
}
}
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, n);
mergeSort(arr, n);
printf("\nSorted array is \n");
printArray(arr, n);
return 0;
}
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Time complexity of above iterative function is same as recursive, i.e., Θ(nLogn).
145. QuickSort
Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given
array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways.
The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot,
put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater
elements (greater than x) after x. All this should be done in linear time.
{
/* pi is partitioning index, arr[p] is now
at right place */
pi = partition(arr, low, high);
quickSort(arr, low, pi - 1); // Before pi
quickSort(arr, pi + 1, high); // After pi
}
}
Partition AlgorithmThere can be many ways to do partition, following pseudo code adopts the method given in
CLRS book. The logic is simple, we start from the leftmost element and keep track of index of smaller (or equal to)
elements as i. While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we ignore
current element.
pivot = arr[high];
i = (low - 1) // Index of smaller element
for (j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
swap arr[i] and arr[j]
}
}
swap arr[i + 1] and arr[high])
return (i + 1)
}
Illustration of partition() :
121
Sat 1/6/2018
pivot and recur for subarrays on left and right of pivot.Consider an array which has many redundant elements. For
example, {1, 4, 2, 4, 2, 4, 1, 2, 4, 1, 2, 2, 2, 2, 4, 1, 4, 4, 4}. If 4 is picked as pivot in Simple QuickSort, we fix only one
4 and recursively process remaining occurrences. In 3 Way QuickSort, an array arr[l..r] is divided in 3 parts:a) arr[l..i]
elements less than pivot.b) arr[i+1..j-1] elements equal to pivot.c) arr[j..r] elements greater than pivot.See this for
implementation.
How to implement QuickSort for Linked Lists?QuickSort on Singly Linked ListQuickSort on Doubly
Linked List
Can we implement QuickSort Iteratively?Yes, please refer Iterative Quick Sort.
Why Quick Sort is preferred over MergeSort for sorting ArraysQuick Sort in its general form is an in-place sort
(i.e. it doesn’t require any extra storage) whereas merge sort requires O(N) extra storage, N denoting the array size
which may be quite expensive. Allocating and de-allocating the extra space used for merge sort increases the running
time of the algorithm. Comparing average complexity we find that both type of sorts have O(NlogN) average
complexity but the constants differ. For arrays, merge sort loses due to the use of extra O(N) storage space.
Most practical implementations of Quick Sort use randomized version. The randomized version has expected time
complexity of O(nLogn). The worst case is possible in randomized version also, but worst case doesn’t occur for a
particular pattern (like sorted array) and randomized Quick Sort works well in practice.
Quick Sort is also a cache friendly sorting algorithm as it has good locality of reference when used for arrays.
Quick Sort is also tail recursive, therefore tail call optimizations is done.
Why MergeSort is preferred over QuickSort for Linked Lists?In case of linked lists the case is different mainly due
to difference in memory allocation of arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in
memory. Unlike array, in linked list, we can insert items in the middle in O(1) extra space and O(1) time. Therefore
merge operation of merge sort can be implemented without extra space for linked lists.
In arrays, we can do random access as elements are continuous in memory. Let us say we have an integer (4-byte)
array A and let the address of A[0] be x then to access A[i], we can directly access the memory at (x + i*4). Unlike
arrays, we can not do random access in linked list. Quick Sort requires a lot of this kind of access. In linked list to
access i’th index, we have to travel each and every node from the head to i’th node as we don’t have continuous block
of memory. Therefore, the overhead increases for quick sort. Merge sort accesses data sequentially and the need of
random access is low.
How to optimize QuickSort so that it takes O(Log n) extra space in worst case?Please see QuickSort Tail
Call Optimization (Reducing worst case space to Log n )
146. QuickSort
Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions
the given array around the picked pivot. There are many different versions of quickSort that pick pivot in
different ways.
The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array
as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x,
and put all greater elements (greater than x) after x. All this should be done in linear time.
Partition AlgorithmThere can be many ways to do partition, following pseudo code adopts the method given in
CLRS book. The logic is simple, we start from the leftmost element and keep track of index of smaller (or equal to)
elements as i. While traversing, if we find a smaller element, we swap current element with arr[i]. Otherwise we ignore
current element.
pivot = arr[high];
i = (low - 1) // Index of smaller element
for (j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
swap arr[i] and arr[j]
}
}
swap arr[i + 1] and arr[high])
return (i + 1)
}
Illustration of partition() :
arr[] = {10, 80, 30, 90, 40, 50, 70}
Indexes: 0 1 2 3 4 5 6
126
Sat 1/6/2018
arr[] = {10, 30, 40, 50, 70, 90, 80} // 80 and 70 Swapped
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = arr.length;
QuickSort ob = new QuickSort();
ob.sort(arr, 0, n-1);
System.out.println("sorted array");
printArray(arr);
}
}
/*This code is contributed by Rajat Mishra */
Output:
Sorted array:
1 5 7 8 9 10
The first two terms are for two recursive calls, the last term is for the partition process. k is the number of
elements which are smaller than pivot.The time taken by QuickSort depends upon the input array and
partition strategy. Following are three cases.
Worst Case: The worst case occurs when the partition process always picks greatest or smallest element as
pivot. If we consider above partition strategy where last element is always picked as pivot, the worst case
would occur when the array is already sorted in increasing or decreasing order. Following is recurrence for
worst case.
Best Case: The best case occurs when the partition process always picks the middle element as pivot.
Following is recurrence for best case.
The solution of above recurrence is (nLogn). It can be solved using case 2 of Master Theorem.
Average Case:To do average case analysis, we need to consider all possible permutation of array and
calculate time taken by every permutation which doesn’t look easy.We can get an idea of average
case by considering the case when partition puts O(n/9) elements in one set and O(9n/10) elements in other
set. Following is recurrence for this case.
128
Sat 1/6/2018
Although the worst case time complexity of QuickSort is O(n2) which is more than many other sorting
algorithms like Merge Sort and Heap Sort, QuickSort is faster in practice, because its inner loop can be
efficiently implemented on most architectures, and in most real-world data. QuickSort can be implemented
in different ways by changing the choice of pivot, so that the worst case rarely occurs for a given type of
data. However, merge sort is generally considered better when data is huge and stored in external storage.
What is 3-Way QuickSort?In simple QuickSort algorithm, we select an element as pivot, partition the
array around pivot and recur for subarrays on left and right of pivot.Consider an array which has many
redundant elements. For example, {1, 4, 2, 4, 2, 4, 1, 2, 4, 1, 2, 2, 2, 2, 4, 1, 4, 4, 4}. If 4 is picked as pivot in
Simple QuickSort, we fix only one 4 and recursively process remaining occurrences. In 3 Way QuickSort,
an array arr[l..r] is divided in 3 parts:a) arr[l..i] elements less than pivot.b) arr[i+1..j-1] elements equal to
pivot.c) arr[j..r] elements greater than pivot.See this for implementation.
148. How to implement QuickSort for Linked Lists?QuickSort on Singly Linked ListQuickSort on
Doubly Linked List
Can we implement QuickSort Iteratively?Yes, please refer Iterative Quick Sort.
149. Why Quick Sort is preferred over MergeSort for sorting Arrays
Quick Sort in its general form is an in-place sort (i.e. it doesn’t require any extra storage) whereas merge
sort requires O(N) extra storage, N denoting the array size which may be quite expensive. Allocating and
de-allocating the extra space used for merge sort increases the running time of the algorithm. Comparing
average complexity we find that both type of sorts have O(NlogN) average complexity but the constants
differ. For arrays, merge sort loses due to the use of extra O(N) storage space.
Most practical implementations of Quick Sort use randomized version. The randomized version has
expected time complexity of O(nLogn). The worst case is possible in randomized version also, but worst
case doesn’t occur for a particular pattern (like sorted array) and randomized Quick Sort works well in
practice.
Quick Sort is also a cache friendly sorting algorithm as it has good locality of reference when used for
arrays.
Quick Sort is also tail recursive, therefore tail call optimizations is done.
In case of linked lists the case is different mainly due to difference in memory allocation of arrays and
linked lists. Unlike arrays, linked list nodes may not be adjacent in memory. Unlike array, in linked list, we
can insert items in the middle in O(1) extra space and O(1) time. Therefore merge operation of merge sort
can be implemented without extra space for linked lists.
129
Sat 1/6/2018
In arrays, we can do random access as elements are continuous in memory. Let us say we have an integer
(4-byte) array A and let the address of A[0] be x then to access A[i], we can directly access the memory at
(x + i*4). Unlike arrays, we can not do random access in linked list. Quick Sort requires a lot of this kind of
access. In linked list to access i’th index, we have to travel each and every node from the head to i’th node
as we don’t have continuous block of memory. Therefore, the overhead increases for quick sort. Merge sort
accesses data sequentially and the need of random access is low.
\/
5(1) 3(2)
/ \
4(3) 1(4)
The heapify procedure calls itself recursively to build heap
in top down manner.
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.
// C++ program for implementation of Heap Sort
#include <iostream>
using namespace std;
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// main function to do heap sort
void heapSort(int arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
// Move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
for (int i=0; i<n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
// Driver program
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
131
Sat 1/6/2018
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
cout << "Sorted array is \n";
printArray(arr, n);
}
Output:
Sorted array is
5 6 7 11 12 13
Applications of HeapSort1. Sort a nearly sorted (or K sorted) array2. k largest(or smallest)
elements in an array
Heap sort algorithm has limited uses because Quicksort and Mergesort are better in practice. Nevertheless,
the Heap data structure itself is enormously used. See Applications of Heap Data Structure
132
Sat 1/6/2018
Output:
Sorted character array is eeeefggkkorss
Time Complexity: O(n+k) where n is the number of elements in input array and k is the range of
input.Auxiliary Space: O(n+k)
Points to be noted:1. Counting sort is efficient if the range of input data is not significantly greater than the
number of objects to be sorted. Consider the situation where the input sequence is between range 1 to 10K
and the data is 10, 5, 10K, 5K.2. It is not a comparison based sorting. It running time complexity is O(n)
with space proportional to the range of data.3. It is often used as a sub-routine to another sorting algorithm
like radix sort.4. Counting sort uses a partial hashing to count the occurrence of the data object in O(1).5.
Counting sort can be extended to work for negative inputs also.
133
Sat 1/6/2018
Exercise:1. Modify above code to sort the input data in the range from M to N.2. Modify above code to sort
negative input data.3. Is counting sort stable and online?4. Thoughts on parallelizing the counting sort
algorithm.
Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the
following problem. Sort a large set of floating point numbers which are in range from 0.0 to 1.0 and are
uniformly distributed across the range. How do we sort the numbers efficiently?
A simple way is to apply a comparison based sorting algorithm. The lower bound for Comparison based
sorting algorithm (Merge Sort, Heap Sort, Quick-Sort .. etc) is Ω(n Log n), i.e., they cannot do better than
nLogn.Can we sort the array in linear time? Counting sort can not be applied here as we use keys as index
in counting sort. Here keys are floating point numbers. The idea is to use bucket sort. Following is bucket
algorithm.
bucketSort(arr[], n)
1) Create n empty buckets (Or lists).
2) Do following for every array element arr[i].
.......a) Insert arr[i] into bucket[n*array[i]]
3) Sort individual buckets using insertion sort.
4) Concatenate all sorted buckets.
Following diagram (taken from CLRS book) demonstrates working of bucket sort.
Time Complexity: If we assume that insertion in a bucket takes O(1) time then steps 1 and 2 of the above algorithm
clearly take O(n) time. The O(1) is easily possible if we use a linked list to represent a bucket (In the following code,
C++ vector is used for simplicity). Step 4 also takes O(n) time as there will be n items in all buckets.The main step to
analyze is step 3. This step also takes O(n) time on average if all numbers are uniformly distributed (please refer
CLRS book for more details)
Following is C++ implementation of the above algorithm.
// C++ program to sort an array using bucket sort
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// Function to sort arr[] of size n using bucket sort
void bucketSort(float arr[], int n)
134
Sat 1/6/2018
{
// 1) Create n empty buckets
vector<float> b[n];
// 2) Put array elements in different buckets
for (int i=0; i<n; i++)
{
int bi = n*arr[i]; // Index in bucket
b[bi].push_back(arr[i]);
}
// 3) Sort individual buckets
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());
// 4) Concatenate all buckets into arr[]
int index = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < b[i].size(); j++)
arr[index++] = b[i][j];
}
/* Driver program to test above funtion */
int main()
{
float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
int n = sizeof(arr)/sizeof(arr[0]);
bucketSort(arr, n);
cout << "Sorted array is \n";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
Sorted array is
0.1234 0.3434 0.565 0.656 0.665 0.897
135
Sat 1/6/2018
Time Complexity: The algorithm as a whole still has a running worst case running time of O(n2) because of
the series of swaps required for each insertion.
This article is contributed by Amit Auddy. Please write comments if you find anything incorrect, or you
want to share more information about the topic discussed above
Algorithm:
Step 1: Take the elements input in an array.
Step 2: Create a Binary search tree by inserting data items from the array into the
binary searh tree.
Step 3: Perform in-order traversal on the tree to get the elements in sorted order.
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node *left, *right;
};
// A utility function to create a new BST Node
struct Node *newNode(int item)
{
struct Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// Stores inoder traversal of the BST
// in arr[]
void storeSorted(Node *root, int arr[], int &i)
{
if (root != NULL)
{
storeSorted(root->left, arr, i);
arr[i++] = root->key;
storeSorted(root->right, arr, i);
}
}
/* A utility function to insert a new
Node with given key in BST */
Node* insert(Node* node, int key)
{
/* If the tree is empty, return a new Node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
/* return the (unchanged) Node pointer */
return node;
}
// This function sorts arr[0..n-1] using Tree Sort
void treeSort(int arr[], int n)
{
struct Node *root = NULL;
// Construct the BST
root = insert(root, arr[0]);
for (int i=1; i<n; i++)
insert(root, arr[i]);
// Store inoder traversal of the BST
// in arr[]
int i = 0;
storeSorted(root, arr, i);
}
// Driver Program to test above functions
int main()
{
//create input array
int arr[] = {5, 4, 7, 2, 11};
137
Sat 1/6/2018
int n = sizeof(arr)/sizeof(arr[0]);
treeSort(arr, n);
cout << "Sorted Array : ";
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
2 4 5 7 11
Average Case Time Complexity : O(n log n) Adding one item to a Binary Search tree on average takes
O(log n) time. Therefore, adding n items will take O(n log n) time
Worst Case Time Complexity : O(n2). The worst case time complexity of Tree Sort can be improved by
using a self-balancing binary search tree like Red Black Tree, AVL Tree. Using self-balancing binary tree
Tree Sort will take O(n log n) time to sort the array in worst case.
Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list
makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely
impossible.
Let head be the first node of the linked list to be sorted and headRef be the pointer to head. Note that we
need a reference to head in MergeSort() as the below implementation changes next links to sort the linked
lists (not data at the nodes), so head node has to be changed if the data at original head is not the smallest
value in linked list.
MergeSort(headRef)
1) If head is NULL or there is only one element in the Linked List
then return.
2) Else divide the linked list into two halves.
FrontBackSplit(head, &a, &b); /* a and b are two halves */
3) Sort the two halves a and b.
MergeSort(a);
MergeSort(b);
4) Merge the sorted a and b (using SortedMerge() discussed here)
and update the head pointer using headRef.
*headRef = SortedMerge(a, b);
// Java program to illustrate merge sorted
// of linkedList
public class linkedList
{
node head = null;
// node a,b;
static class node
{
int val;
node next;
138
Sat 1/6/2018
140
Sat 1/6/2018
EEPROMs or Flash memory, where each write reduces the lifespan of the memory.
Among the sorting algorithms that we generally study in our data structure and algorithm courses, Selection Sort
makes least number of writes (it makes O(n) swaps). But, Cycle Sort almost always makes less number of writes
compared to Selection Sort. In Cycle Sort, each value is either written zero times, if it’s already in its correct position,
or written one time to its correct position. This matches the minimal number of overwrites required for a completed in-
place sort.
return 0;
}
Output:
This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you
can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing
on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic
discussed above
Given an array of strings arr[]. Sort given strings using Bubble Sort and display the sorted array.
In Bubble Sort, the two successive strings arr[i] and arr[i+1] are exchanged whenever arr[i]> arr[i+1]. The
larger values sink to the bottom and hence called sinking sort. At the end of each pass, smaller values
gradually “bubble” their way upward to the top and hence called bubble sort.
After all the passes, we get all the strings in sorted order. Complexity of the above algorithm will be O(N2).
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
void sortStrings(char arr[][MAX], int n)
{
char temp[MAX];
// Sorting strings using bubble sort
for (int j=0; j<n-1; j++)
{
for (int i=j+1; i<n; i++)
{
if (strcmp(arr[j], arr[i]) > 0)
{
strcpy(temp, arr[j]);
strcpy(arr[j], arr[i]);
strcpy(arr[i], temp);
}
}
}
}
int main()
{
142
Sat 1/6/2018
Output:
This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you
can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing
on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic
discussed above
Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a tree (See method
2 of this post). The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same
node again. To avoid processing a node more than once, we use a boolean visited array. For simplicity, it is
assumed that all vertices are reachable from the starting vertex.For example, in the following graph, we start
traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an
adjacent vertex of 0. If we don’t mark visited vertices, then 2 will be processed again and it will become a
non-terminating process. A Breadth First Traversal of the following graph is 2, 0, 3, 1.
Following are C++ and Java implementations of simple Breadth First Traversal from a given source.
143
Sat 1/6/2018
The C++ implementation uses adjacency list representation of graphs. STL‘s list container is used to
store lists of adjacent nodes and queue of nodes needed for BFS traversal.
144
Sat 1/6/2018
// Driver method to
public static void main(String args[])
{
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("Following is Breadth First Traversal "+
"(starting from vertex 2)");
g.BFS(2);
}
}
// This code is contributed by Aakash Hasija
Output:
Following is Breadth First Traversal (starting from vertex 2)
2 0 3 1
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only
catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid
processing a node more than once, we use a boolean visited array.
For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look
for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t mark visited vertices, then 2 will
be processed again and it will become a non-terminating process. A Depth First Traversal of the following
graph is 2, 0, 1, 3.
See this post for all applications of Depth First Traversal.Following are implementations of simple Depth
First Traversal. The C++ implementation uses adjacency list representation of graphs. STL‘s list
container is used to store lists of adjacent nodes.
// representation
class Graph
{
private int V; // No. of vertices
// Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
146
Sat 1/6/2018
g.DFS(2);
}
}
// This code is contributed by Aakash Hasija
Strings
168. Write a Java program to concatenate a given string to the end of another string.
//str1.concat(str2);
public class Exercise7 {
public static void main(String[] args)
{
String str1 = "PHP Exercises and ";
String str2 = "Python Exercises";
System.out.println("String 1: " + str1);
System.out.println("String 2: " + str2);
// Concatenate the two strings together.
String str3 = str1.concat(str2);
// Display the new String.
System.out.println("The concatenated string: " + str3);
}
}
Sample Output:
String 1: PHP Exercises and
String 2: Python Exercises
The concatenated string: PHP Exercises and Python Exercises
169. Write a Java program to test if a given string contains the specified sequence of char values.
//str1.contains(str2)
public class Exercise8 {
public static void main(String[] args){
String str1 = "PHP Exercises and Python Exercises";
String str2 = "and";
System.out.println("Original String: " + str1);
System.out.println("Specified sequence of char values: " + str2);
System.out.println(str1.contains(str2));
147
Sat 1/6/2018
}
}
Sample Output:
Original String: PHP Exercises and Python Exercises
Specified sequence of char values: and
true
170. Write a Java program to compare a given string to the specified character sequence.
//str1.contentEquals(cs)
public class Exercise9 {
public static void main(String[] args) {
String str1 = "example. com", str2 = "Example. com";
CharSequence cs = "example. com";
System.out.println("Comparing "+str1+" and "+cs+": " + str1.contentEquals(cs));
System.out.println("Comparing "+str2+" and "+cs+": " + str2.contentEquals(cs));
}
}
Sample Output:
Comparing example. com and example. com: true
Comparing Example. com and example. com: false
171. Write a Java program to compare a given string to the specified string buffer.
//str1.contentEquals(strbuf))
public class Exercise10 {
public static void main(String[] args) {
String str1 = "example. com", str2 = "Example. com";
StringBuffer strbuf = new StringBuffer(str1);
System.out.println("Comparing "+str1+" and "+strbuf+": " + str1.contentEquals(strbuf));
System.out.println("Comparing "+str2+" and "+strbuf+": " + str2.contentEquals(strbuf));
}
}
Sample Output:
Comparing example. com and example. com: true
Comparing Example. com and example. com: false
172. Write a Java program to check whether a given string ends with the contents of another string.
//str1.endsWith(end_str);
public class Exercise12 {
public static void main(String[] args)
{
String str1 = "Python Exercises";
String str2 = "Python Exercise";
// The String to check the above two Strings to see
// if they end with this value (se).
String end_str = "se";
// Check first two Strings end with end_str
boolean ends1 = str1.endsWith(end_str);
boolean ends2 = str2.endsWith(end_str);
// Display the results of the endsWith calls.
System.out.println("\"" + str1 + "\" ends with " +
"\"" + end_str + "\"? " + ends1);
System.out.println("\"" + str2 + "\" ends with " +
"\"" + end_str + "\"? " + ends2);
}
}
Sample Output:
"Python Exercises" ends with "se"? false
148
Sat 1/6/2018
173. Write a Java program to check whether two String objects contain the same data.
// columnist1.equals(columnist2);
public class Exercise13 {
public static void main(String[] args)
{
String columnist1 = "Stephen Edwin King";
String columnist2 = "Walter Winchell";
String columnist3 = "Mike Royko";
// Are any of the above Strings equal to one another?
boolean equals1 = columnist1.equals(columnist2);
boolean equals2 = columnist1.equals(columnist3);
// Display the results of the equality checks.
System.out.println("\"" + columnist1 + "\" equals \"" +
columnist2 + "\"? " + equals1);
System.out.println("\"" + columnist1 + "\" equals \"" +
columnist3 + "\"? " + equals2);
}
}
Sample Output:
174. Write a Java program to compare a given string to another string, ignoring case considerations.
public class Exercise14 {
public static void main(String[] args)
{
String columnist1 = "Stephen Edwin King";
String columnist2 = "Walter Winchell";
String columnist3 = "stephen edwin king";
// Test any of the above Strings equal to one another
boolean equals1 = columnist1.equalsIgnoreCase(columnist2);
boolean equals2 = columnist1.equalsIgnoreCase(columnist3);
// Display the results of the equality checks.
System.out.println("\"" + columnist1 + "\" equals \"" +
columnist2 + "\"? " + equals1);
System.out.println("\"" + columnist1 + "\" equals \"" +
columnist3 + "\"? " + equals2);
}
}
Sample Output:
175. Write a Java program to get the contents of a given string as a byte array.
import java. util.Calendar;
public class Exercise16 {
149
Sat 1/6/2018
176. Write a Java program to get the contents of a given string as a character array.
public class Exercise17 {
178. Write a Java program to get the index of all the characters of the alphabet.
150
Sat 1/6/2018
Sample string of all alphabet: "The quick brown fox jumps over the lazy dog."
public class Exercise19 {
151
Sat 1/6/2018
a b c d e f g h i j
=========================
36 10 7 40 2 16 42 1 6 20
k l m n o p q r s t
===========================
8 35 22 14 12 23 4 11 24 31
u v w x y z
================
5 27 13 18 38 3
179. Write a Java program to get the canonical representation of the string object.
public class Exercise20 {
public static void main(String[] args)
{
// Create three strings in three different ways.
String str1 = "Java Exercises";
String str2 = new StringBuffer("Java").append(" Exercises").toString();
String str3 = str2.intern();
// Determine which strings are equivalent using the ==
// operator (as compared to calling equals(), which is
// a more expensive operation.
System.out.println("str1 == str2? " + (str1 == str2));
System.out.println("str1 == str3? " + (str1 == str3));
}
}
Sample Output:
180. Write a Java program to get the last index of a string within a string.
Sample string of all alphabet: "The quick brown fox jumps over the lazy dog."
public class Exercise21 {
public static void main(String[] args)
{
String str = "The quick brown fox jumps over the lazy dog.";
// Get the index of all the characters of the alphabet
// starting from the beginning of the String.
int a = str.lastIndexOf("a", str.length() - 1);
int b = str.lastIndexOf("b", str.length() - 1);
int c = str.lastIndexOf("c", str.length() - 1);
int d = str.lastIndexOf("d", str.length() - 1);
int e = str.lastIndexOf("e", str.length() - 1);
int f = str.lastIndexOf("f", str.length() - 1);
int g = str.lastIndexOf("g", str.length() - 1);
int h = str.lastIndexOf("h", str.length() - 1);
int i = str.lastIndexOf("i", str.length() - 1);
int j = str.lastIndexOf("j", str.length() - 1);
int k = str.lastIndexOf("k", str.length() - 1);
int l = str.lastIndexOf("l", str.length() - 1);
152
Sat 1/6/2018
a b c d e f g h i j
===========================
36 10 7 40 33 16 42 32 6 20
k l m n o p q r s t
===========================
8 35 22 14 41 23 4 29 24 31
u v w x y z
=================
21 27 13 18 38 3
}
Sample Output:
182. Write a Java program to find whether a region in the current string matches a region in another string.
public class Exercise23 {
183. Write a Java program to replace all the 'd' characters with 'f' characters.
public class Exercise24 {
Original string: The quick brown fox jumps over the lazy dog.
New String: The quick brown fox jumps over the lazy fog.
184. Write a Java program to replace each substring of a given string that matches the given regular
expression with the given replacement.
154
Sat 1/6/2018
Sample string: "The quick brown fox jumps over the lazy dog."
In the above string replace all the fox with cat.
public class Exercise25 {
Original string: The quick brown fox jumps over the lazy dog.
New String: The quick brown cat jumps over the lazy dog.
185. Write a Java program to check whether a given string starts with the contents of another string.
public class Exercise26 {
186. Write a Java method to find the smallest number among three numbers.
Test Data:
155
Sat 1/6/2018
Flowchart:
Test Data:
Flowchart:
157
Sat 1/6/2018
Note: a) If the length of the string is odd there will be two middle characters.
b) If the length of the string is even there will be one middle character.
Test Data:
Input a string: 35
import java. util.Scanner;
public class Exercise3 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input a string: ");
String str = in.nextLine();
System.out.print("The middle character in the string: " + middle(str)+"\n");
}
public static String middle(String str)
{
int position;
int length;
if (str.length() % 2 == 0)
{
position = str.length() / 2 - 1;
length = 2;
}
else
{
position = str.length() / 2;
length = 1;
}
return str.substring(position, position + length);
}
}
Sample Output:
Flowchart:
158
Sat 1/6/2018
Test Data:
159
Sat 1/6/2018
Flowchart:
Test Data:
Input the string: The quick brown fox jumps over the lazy dog.
import java. util.Scanner;
public class Exercise5 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();
System.out.print("Number of words in the string: " + count_Words(str)+"\n");
}
public static int count_Words(String str)
{
int count = 0;
160
Sat 1/6/2018
Input the string: The quick brown fox jumps over the lazy dog
Number of words in the string: 9
Flowchart:
191. Write a Java method to compute the sum of the digits in an integer.
Test Data:
Input an integer: 2
import java. util.Scanner;
public class Exercise6 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input an integer: ");
int digits = in.nextInt();
System.out.println("The sum is " + sumDigits(digits));
}
public static int sumDigits(long n) {
int result = 0;
while(n > 0) {
result += n % 10;
n /= 10;
}
return result;
}
}
Sample Output:
Input an integer: 25
The sum is
161
Sat 1/6/2018
A pentagonal number is a figurate number that extends the concept of triangular and square numbers to the
pentagon, but, unlike the first two, the patterns involved in the construction of pentagonal numbers are not rotationally
symmetrical.
import java. util.Scanner;
public class Exercise7 {
public static void main(String[] args) {
int count = 1;
for(int i = 1; i <= 50; i++){
System.out.printf("%-6d",getPentagonalNumber(i));
if(count % 10 == 0) System.out.println();
count++;
}
}
public static int getPentagonalNumber(int i) {
return (i * (3 * i - 1))/2;
}
}
Sample Output:
1 5 12 22 35 51 70 92 117 145
176 210 247 287 330 376 425 477 532 590
651 715 782 852 925 1001 1080 1162 1247 1335
1426 1520 1617 1717 1820 1926 2035 2147 2262 2380
2501 2625 2752 2882 3015 3151 3290 3432 3577 372
Flowchart:
162
Sat 1/6/2018
193. Write a Java method to compute the future investment value at a given interest rate for a specified
number of years.
163
Sat 1/6/2018
rate *= 0.01;
System.out.println("Years FutureValue");
for(int i = 1; i <= year; i++) {
int formatter = 19;
if (i >= 10) formatter = 18;
System.out.printf(i + "%"+formatter+".2f\n", futureInvestmentValue(investment, rate/12,
i));
}
}
Flowchart:
164
Sat 1/6/2018
194. Write a Java method to print characters between two characters (i.e. A to P ).
if (ctr % n == 0) System.out.println("");
}
System.out.print("\n");
}
}
Sample Output:
( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ;
< = > ? @ A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c
d e f g h i j k l m n o p q r s t u v w
x y z
Flowchart:
166
Sat 1/6/2018
195. Write a Java method to check whether an year (integer) entered by the user is a leap year or not.
import java. util.Scanner;
public class Exercise10 {
Flowchart:
Password rules:
167
Sat 1/6/2018
Flowchart:
168
Sat 1/6/2018
197. Write a Java method (takes a number n as input) to displays an n-by-n matrix.
import java. util.Scanner;
public class Exercise12 {
System.out.println();
}
}
}
Sample Output:
Input a number: 10
1 0 0 1 1 0 0 0 1 1
0 0 1 0 1 0 1 0 0 0
0 1 0 1 0 0 0 0 0 1
1 1 1 0 0 0 0 1 1 1
1 1 0 1 1 1 0 1 0 0
1 0 0 0 1 1 0 0 0 0
0 0 1 0 0 0 0 1 1 1
1 1 0 1 0 1 0 0 1 0
0 0 1 0 0 0 0 1 1 0
1 1 1 0 0 1 1 1 1
Flowchart:
170
Sat 1/6/2018
Input Side-1: 10
Input Side-2: 15
Input Side-3: 20
The area of the triangle is 72.61843774138907
Flowchart:
172
Sat 1/6/2018
return (n * s * s) / (4 * Math.tan(Math.PI/n));
}
}
Sample Output:
Flowchart:
200. Write a Java method to find all twin prime numbers less than 100.
import java. util.Scanner;
public class Exercise16 {
173
Sat 1/6/2018
Sample Output:
(3, 5)
(5, 7)
(11, 13)
(17, 19)
(29, 31)
(41, 43)
(59, 61)
(71, 73)
Flowchart :
174
Sat 1/6/2018
202. Write a Java program to iterate through all elements in a array list.
import java. util.*;
public class Exercise2 {
public static void main(String[] args) {
// Creae a list and add some colors to the list
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
// Print the list
for (String element : list_Strings) {
System.out.println(element);
}
}
}
Sample Output:
Red
Green
Orange
White
Black
203. Write a Java program to insert an element into the array list at the first position.
175
Sat 1/6/2018
204. Write a Java program to retrieve an element (at a specified index) from a given array list.
import java. util.*;
public class Exercise4 {
public static void main(String[] args) {
// Creae a list and add some colors to the list
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
// Print the list
System.out.println(list_Strings);
// Retrive the first and third element
String element = list_Strings.get(0);
System.out.println("First element: "+element);
element = list_Strings.get(2);
System.out.println("Third element: "+element);
}
}
Sample Output:
176
Sat 1/6/2018
205. Write a Java program to update specific array element by given element.
import java. util.*;
public class Exercise5 {
public static void main(String[] args) {
// Creae a list and add some colors to the list
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
// Print the list
System.out.println(list_Strings);
// Update the third element with "Yellow"
list_Strings.set(2, "Yellow");
// Print the list again
System.out.println(list_Strings);
}
}
Sample Output:
206. Write a Java program to remove the third element from a array list.
import java. util.*;
public class Exercise6 {
public static void main(String[] args) {
// Creae a list and add some colors to the list
List<String> list_Strings = new ArrayList<String>();
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
// Print the list
System.out.println(list_Strings);
// Remove the third element from the list.
list_Strings.remove(2);
// Print the list again
System.out.println("After removing third element from the list:\n"+list_Strings);
}
}
Sample Output:
177
Sat 1/6/2018
209. Write a Java program to copy one array list into another.
import java. util.*;
public class Exercise9 {
public static void main(String[] args) {
List<String> List1 = new ArrayList<String>();
List1.add("1");
178
Sat 1/6/2018
List1.add("2");
List1.add("3");
List1.add("4");
System.out.println("List1: " + List1);
List<String> List2 = new ArrayList<String>();
List2.add("A");
List2.add("B");
List2.add("C");
List2.add("D");
System.out.println("List2: " + List2);
// Copy List1 to List Collections.copy(List1, List2);
System.out.println("Copy List to List2,\nAfter copy:");
System.out.println("List1: " + List1);
System.out.println("List2: " + List2);
}
}
Sample Output:
List1: [1, 2, 3, 4]
List2: [A, B, C, D]
Copy List to List2,
After copy:
List1: [A, B, C, D]
List2: [A, B, C, D]
list_Strings.add("Red");
list_Strings.add("Green");
list_Strings.add("Orange");
list_Strings.add("White");
list_Strings.add("Black");
System.out.println("List before reversing :\n" + list_Strings);
Collections.reverse(list_Strings);
System.out.println("List after reversing :\n" + list_Strings);
}
}
Sample Output:
180
Sat 1/6/2018
}
}
Sample Output:
}
}
Sample Output:
216. Write a Java program to append the specified element to the end of a linked list.
217. Write a Java program to iterate through all elements in a linked list.
import java. util.LinkedList;
public class Exercise2 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> l_list = new LinkedList<String>();
182
Sat 1/6/2018
Red
Green
Black
White
Pink
218. Write a Java program to iterate through all elements in a linked list starting at the specified position.
Green
Black
White
Pink
183
Sat 1/6/2018
Iterator it = l_list.descendingIterator();
// Print list elements in reverse order
System.out.println("Elements in Reverse Order:");
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Sample Output:
220. Write a Java program to insert the specified element at the specified position in the linked list.
import java. util.LinkedList;
public class Exercise5 {
public static void main(String[] args) {
// create an empty linked list
LinkedList <String> l_list = new LinkedList <String> ();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
l_list.add("White");
l_list.add("Pink");
System.out.println("Original linked list: ");
System.out.println("Let add the Yellow color after the Red Color: " + l_list);
l_list.add(1, "Yellow");
// print the list
System.out.println("The linked list:" + l_list);
}
}
184
Sat 1/6/2018
Sample Output:
221. Write a Java program to insert elements into the linked list at the first and last position.
import java. util.LinkedList;
public class Exercise6 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> l_list = new LinkedList<String>();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
System.out.println("Original linked list:" + l_list);
// Add an element at the beginning
l_list.addFirst("White");
222. Write a Java program to insert the specified element at the front of a linked list.
import java. util.LinkedList;
public class Exercise7 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> l_list = new LinkedList<String>();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
System.out.println("Original linked list:" + l_list);
// Add an element to front of LinkedList
l_list.offerFirst("Pink");
System.out.println("Final linked list:" + l_list);
}
}
185
Sat 1/6/2018
Sample Output:
223. Write a Java program to insert the specified element at the end of a linked list.
import java. util.LinkedList;
public class Exercise8 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> l_list = new LinkedList<String>();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
System.out.println("Original linked list:" + l_list);
// Add an element at the end of a linked list
l_list.offerLast("Pink");
System.out.println("Final linked list:" + l_list);
}
}
Sample Output:
224. Write a Java program to insert some elements at the specified position into a linked list.
import java. util.LinkedList;
public class Exercise9 {
public static void main(String[] args) {
// create an empty linked list
LinkedList <String> l_list = new LinkedList <String> ();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
// print original list
System.out.println("Original linked list:" + l_list);
// create a new collection and add some elements
LinkedList <String> new_l_list = new LinkedList <String> ();
new_l_list.add("White");
new_l_list.add("Pink");
// Add the collection in the second position of the existing linked list
l_list.addAll(1, new_l_list);
// print the new list
System.out.println("LinkedList:" + l_list);
}
}
Sample Output:
186
Sat 1/6/2018
225. Write a Java program to remove a specified element from a linked list.
import java. util.*;
public class Exercise12 {
public static void main(String[] args) {
// create an empty linked list
LinkedList <String> l_list = new LinkedList <String> ();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
l_list.add("Pink");
l_list.add("orange");
// print the list
System.out.println("The Original linked list: " + l_list);
// Remove the element in third position from the said linked list
l_list.remove(2);
System.out.println("The New linked list: " + l_list);
}
}
Sample Output:
226. Write a Java program to remove all the elements from a linked list.
import java. util.*;
public class Exercise14 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> l_list = new LinkedList<String>();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
l_list.add("Pink");
l_list.add("orange");
228. Write a Java program to clone an linked list to another linked list.
import java. util.*;
public class Exercise18 {
public static void main(String[] args) {
// create an empty linked list
LinkedList <String> c1 = new LinkedList <String> ();
c1.add("Red");
c1.add("Green");
c1.add("Black");
c1.add("White");
c1.add("Pink");
System.out.println("Original linked list: " + c1);
LinkedList <String> newc1 = new LinkedList <String> ();
newc1 = (LinkedList)c1.clone();
System.out.println("Cloned linked list: " + newc1);
}
}
Sample Output:
229. Write a Java program to retrieve but does not remove, the first element of a linked list.
import java. util.*;
public class Exercise20 {
public static void main(String[] args) {
// create an empty linked list
LinkedList <String> c1 = new LinkedList <String> ();
c1.add("Red");
c1.add("Green");
c1.add("Black");
c1.add("White");
c1.add("Pink");
System.out.println("Original linked list: " + c1);
// Retrieve but does not remove, the first element of a linked list
String x = c1.peekFirst();
System.out.println("First element in the list: " + x);
System.out.println("Original linked list: " + c1);
}
}
Sample Output:
189
Sat 1/6/2018
Red
Green
Black
White
Pink
HashSet
232. Write a Java program to append the specified element to the end of a hash set.
import java. util.HashSet;
public class Exercise1 {
public static void main(String[] args) {
// Create a empty hash set
HashSet<String> h_set = new HashSet<String>();
// use add() method to add values in the hash set
h_set.add("Red");
h_set.add("Green");
h_set.add("Black");
h_set.add("White");
h_set.add("Pink");
h_set.add("Yellow");
// print the hash set
System.out.println("The Hash Set: " + h_set);
}
}
Sample Output:
190
Sat 1/6/2018
233. Write a Java program to iterate through all elements in a hash list.
import java. util.*;
import java. util.Iterator;
public class Exercise2 {
public static void main(String[] args) {
// Create a empty hash set
HashSet<String> h_set = new HashSet<String>();
// use add() method to add values in the hash set
h_set.add("Red");
h_set.add("Green");
h_set.add("Black");
h_set.add("White");
h_set.add("Pink");
h_set.add("Yellow");
// set Iterator
Iterator<String> p = h_set.iterator();
// Iterate the hash set
while (p.hasNext()) {
System.out.println(p.next());
}
}
}
Sample Output:
Red
White
Pink
Yellow
Black
Green
234. Write a Java program to get the number of elements in a hash set.
import java. util.*;
import java. util.Iterator;
public class Exercise3 {
public static void main(String[] args) {
// Create a empty hash set
HashSet<String> h_set = new HashSet<String>();
// use add() method to add values in the hash set
h_set.add("Red");
h_set.add("Green");
h_set.add("Black");
h_set.add("White");
h_set.add("Pink");
h_set.add("Yellow");
System.out.println("Original Hash Set: " + h_set);
System.out.println("Size of the Hash Set: " + h_set.size());
}
}
Sample Output:
191
Sat 1/6/2018
192
Sat 1/6/2018
237. Write a Java program to clone a hash set to another hash set.
import java. util.*;
public class Exercise6 {
public static void main(String[] args) {
// Create a empty hash set
HashSet<String> h_set = new HashSet<String>();
// use add() method to add values in the hash set
h_set.add("Red");
h_set.add("Green");
h_set.add("Black");
h_set.add("White");
h_set.add("Pink");
h_set.add("Yellow");
System.out.println("Original Hash Set: " + h_set);
HashSet <String> new_h_set = new HashSet <String> ();
new_h_set = (HashSet)h_set.clone();
System.out.println("Cloned Hash Set: " + new_h_set);
}
}
Sample Output:
Sample Output:
194
Sat 1/6/2018
Yes
No
Yes
No
195
Sat 1/6/2018
TreeSet
242. Write a Java program to compare two sets and retain elements which are same on both sets.
243. Write a Java program to remove all of the elements from a hash set.
import java. util.*;
public class Exercise12 {
public static void main(String[] args) {
// Create a empty hash set
HashSet<String> h_set = new HashSet<String>();
// use add() method to add values in the hash set
h_set.add("Red");
h_set.add("Green");
h_set.add("Black");
h_set.add("White");
System.out.println("Original hash set contains: "+ h_set);
// clear() method removes all the elements from a hash set
// and the set becomes empty.
h_set.clear();
}
}
Sample Output:
244. Write a Java program to create a new tree set, add some colors (string) and print out the tree set.
import java. util.TreeSet;
public class Exercise1 {
public static void main(String[] args) {
TreeSet<String> tree_set = new TreeSet<String>();
tree_set.add("Red");
tree_set.add("Green");
tree_set.add("Orange");
tree_set.add("White");
tree_set.add("Black");
System.out.println("Tree set: ");
System.out.println(tree_set);
}
}
Sample Output:
Tree set:
[Black, Green, Orange, Red, White]
245. Write a Java program to iterate through all elements in a tree set.
import java. util.TreeSet;
public class Exercise2 {
public static void main(String[] args) {
TreeSet<String> tree_set = new TreeSet<String>();
tree_set.add("Red");
tree_set.add("Green");
tree_set.add("Orange");
tree_set.add("White");
tree_set.add("Black");
// Print the tree list
for (String element : tree_set) {
System.out.println(element);
}
}
}
Sample Output:
Black
Green
Orange
Red
White
197
Sat 1/6/2018
246. Write a Java program to add all the elements of a specified tree set to another tree set.
import java. util.TreeSet;
public class Exercise3 {
public static void main(String[] args) {
TreeSet<String> tree_set1 = new TreeSet<String>();
tree_set1.add("Red");
tree_set1.add("Green");
tree_set1.add("Orange");
System.out.println("Tree set1: "+tree_set1);
TreeSet<String> tree_set2 = new TreeSet<String>();
tree_set2.add("Pink");
tree_set2.add("White");
tree_set2.add("Black");
System.out.println("Tree set2: "+tree_set2);
// adding treetwo to treeone
tree_set1.addAll(tree_set2);
System.out.println("Tree set1: "+tree_set1);
}
}
Sample Output:
247. Write a Java program to create a reverse order view of the elements contained in a given tree set.
import java. util.TreeSet;
import java. util.Iterator;
public class Exercise4 {
public static void main(String[] args) {
// create an empty tree set
TreeSet<String> t_set = new TreeSet<String>();
// use add() method to add values in the tree set
t_set.add("Red");
t_set.add("Green");
t_set.add("Black");
t_set.add("Pink");
t_set.add("orange");
// print original list
System.out.println("Original tree set:" + t_set);
Iterator it = t_set.descendingIterator();
// Print list elements in reverse order
System.out.println("Elements in Reverse Order:");
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Sample Output:
Red
Pink
Green
Black
248. Write a Java program to get the first and last elements in a tree set.
import java. util.TreeSet;
public class Exercise5 {
public static void main(String[] args) {
TreeSet<String> tree_set = new TreeSet<String>();
tree_set.add("Red");
tree_set.add("Green");
tree_set.add("Orange");
tree_set.add("White");
tree_set.add("Black");
System.out.println("Tree set: ");
System.out.println(tree_set);
// Find first element of the tree set
Object first_element = tree_set.first();
System.out.println("First Element is: "+first_element);
Tree set:
[Black, Green, Orange, Red, White]
First Element is: Black
Last Element is: White
249. Write a Java program to clone a tree set list to another tree set.
import java. util.TreeSet;
import java. util.Iterator;
public class Exercise6 {
public static void main(String[] args) {
// create an empty tree set
TreeSet<String> t_set = new TreeSet<String>();
// use add() method to add values in the tree set
t_set.add("Red");
t_set.add("Green");
t_set.add("Black");
t_set.add("Pink");
t_set.add("orange");
}
Sample Output:
250. Write a Java program to get the number of elements in a tree set.
import java. util.TreeSet;
import java. util.Iterator;
public class Exercise7 {
public static void main(String[] args) {
// create an empty tree set
TreeSet<String> t_set = new TreeSet<String>();
// use add() method to add values in the tree set
t_set.add("Red");
t_set.add("Green");
t_set.add("Black");
t_set.add("Pink");
t_set.add("orange");
System.out.println("Original tree set: " + t_set);
System.out.println("Size of the tree set: " + t_set.size());
}
}
Sample Output:
251. Write a Java program to retrieve and remove the first element of a tree set.
import java. util.TreeSet;
import java. util.Iterator;
public class Exercise14 {
public static void main(String[] args) {
// creating TreeSet
TreeSet <Integer>tree_num = new TreeSet<Integer>();
TreeSet <Integer>treeheadset = new TreeSet<Integer>();
200
Sat 1/6/2018
Original tree set: [10, 14, 16, 22, 25, 36, 70, 82, 89]
Removes the first(lowest) element: 10
Tree set after removing first element: [14, 16, 22, 25, 36, 70, 82, 89]
252. Write a Java program to retrieve and remove the last element of a tree set.
import java. util.TreeSet;
import java. util.Iterator;
public class Exercise15 {
public static void main(String[] args) {
// creating TreeSet
TreeSet <Integer>tree_num = new TreeSet<Integer>();
TreeSet <Integer>treeheadset = new TreeSet<Integer>();
Original tree set: [10, 14, 16, 22, 25, 36, 70, 82, 89]
Removes the last element: 89
Tree set after removing last element: [10, 14, 16, 22, 25, 36, 70, 82]
253. Write a Java program to remove a given element from a tree set.
import java. util.TreeSet;
import java. util.Iterator;
public class Exercise16 {
public static void main(String[] args) {
// creating TreeSet
TreeSet <Integer>tree_num = new TreeSet<Integer>();
TreeSet <Integer>treeheadset = new TreeSet<Integer>();
201
Sat 1/6/2018
Original tree set: [10, 14, 16, 22, 25, 36, 70, 82, 89]
Removes 70 from the list: true
Tree set after removing last element: [10, 14, 16, 22, 25, 36, 82, 89]
254. Write a Java program to create a new priority queue, add some colors (string) and print out the elements
of the priority queue.
import java. util.PriorityQueue;
public class Exercise1 {
public static void main(String[] args) {
PriorityQueue<String> queue=new PriorityQueue<String>();
queue. add("Red");
queue. add("Green");
queue. add("Orange");
queue. add("White");
queue. add("Black");
System.out.println("Elements of the Priority Queue: ");
System.out.println(queue);
}
}
Sample Output:
255. Write a Java program to iterate through all elements in priority queue.
import java. util.PriorityQueue;
public class Exercise2 {
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("Red");
pq.add("Green");
202
Sat 1/6/2018
pq.add("Orange");
pq.add("White");
pq.add("Black");
System.out.println("Elements of the Priority Queue: ");
// iterate the Priority Queue
for (String element : pq) {
System.out.println(element);
}
}
}
Sample Output:
Priority Queue
256. Write a Java program to add all the elements of a priority queue to another priority queue.
import java. util.PriorityQueue;
public class Exercise3 {
public static void main(String[] args) {
PriorityQueue<String> queue1 = new PriorityQueue<String>();
queue1.add("Red");
queue1.add("Green");
queue1.add("Orange");
System.out.println("Priority Queue1: "+queue1);
PriorityQueue<String> queue2 = new PriorityQueue<String>();
queue2.add("Pink");
queue2.add("White");
queue2.add("Black");
System.out.println("Priority Queue2: "+queue2);
// adding queue2 to queue queue1.addAll(queue2);
System.out.println("New Priority Queue1: "+queue1);
}
}
Sample Output:
257. Write a Java program to remove all the elements from a priority queue.
import java. util.*;
public class Example5 {
public static void main(String[] args) {
// Create Priority Queue
PriorityQueue<String> pq1 = new PriorityQueue<String>();
203
Sat 1/6/2018
204
Sat 1/6/2018
259. Write a Java program to retrieve the first element of the priority queue.
import java. util.PriorityQueue;
public class Example8 {
public static void main(String[] args) {
// Create Priority Queue
PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>();
PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>();
Original Priority Queue: [10, 14, 36, 16, 22, 70, 82, 89, 25]
The first element of the Queue: 1
260. Write a Java program to retrieve and remove the first element.
import java. util.PriorityQueue;
public class Exercise9 {
public static void main(String[] args) {
// Create Priority Queue
PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>();
PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>();
// Add numbers in the Priority Queue
pq1.add(10);
pq1.add(22);
pq1.add(36);
pq1.add(25);
pq1.add(16);
pq1.add(70);
pq1.add(82);
pq1.add(89);
pq1.add(14);
System.out.println("Original Priority Queue: "+pq1);
System.out.println("Removes the first element: "+pq1.poll());
System.out.println("Priority Queue after removing first element: "+pq1);
}
}
Sample Output:
205
Sat 1/6/2018
Original Priority Queue: [10, 14, 36, 16, 22, 70, 82, 89, 25]
Removes the first element: 10
Priority Queue after removing first element: [14, 16, 36, 25, 22, 70, 2, 89]
Map
261. Write a Java program to associate the specified value with the specified key in a HashMap.
import java. util.*;
public class Example1 {
public static void main(String args[]) {
HashMap<Integer,String> hash_map= new HashMap<Integer,String>();
hash_map.put(1, "Red");
hash_map.put(2, "Green");
hash_map.put(3, "Black");
hash_map.put(4, "White");
hash_map.put(5, "Blue");
for(Map.Entry x:hash_map.entrySet()){
System.out.println(x.getKey()+" "+x.getValue());
}
}
}
Sample Output:
1 Red
2 Green
3 Black
4 White
5 Blue
262. Write a Java program to count the number of key-value (size) mappings in a map.
import java. util.*;
public class Example2 {
public static void main(String args[]){
HashMap<Integer,String> hash_map= new HashMap<Integer,String>();
hash_map.put(1, "Red");
hash_map.put(2, "Green");
hash_map.put(3, "Black");
hash_map.put(4, "White");
hash_map.put(5, "Blue");
System.out.println("Size of the hash map: "+hash_map.size());
}
}
Sample Output:
263. Write a Java program to copy all of the mappings from the specified map to another map.
import java. util.*;
public class Example3 {
206
Sat 1/6/2018
264. Write a Java program to remove all the mappings from a map.
import java. util.*;
public class Example4 {
public static void main(String args[]) {
HashMap <Integer,String> hash_map = new HashMap <Integer,String> ();
hash_map.put(1, "Red");
hash_map.put(2, "Green");
hash_map.put(3, "Black");
hash_map.put(4, "White");
hash_map.put(5, "Blue");
// print the map
System.out.println("The Original linked map: " + hash_map);
// Removing all the elements from the linked map
hash_map.clear();
System.out.println("The New map: " + hash_map);
}
}
Sample Output:
265. Write a Java program to check whether a map contains key-value mappings (empty) or not.
import java. util.*;
public class Example5 {
207
Sat 1/6/2018
267. Write a Java program to test if a map contains a mapping for the specified key.
import java. util.*;
public class Example7 {
208
Sat 1/6/2018
268. Write a Java program to test if a map contains a mapping for the specified value.
import java. util.*;
public class Example8 {
public static void main(String args[]) {
HashMap < Integer, String > hash_map = new HashMap < Integer, String > ();
hash_map.put(1, "Red");
hash_map.put(2, "Green");
hash_map.put(3, "Black");
hash_map.put(4, "White");
hash_map.put(5, "Blue");
// print the map
System.out.println("The Original map: " + hash_map);
System.out.println("1. Is value \'Green\' exists?");
if (hash_map.containsValue("Green")) {
//value exists
System.out.println("Yes! ");
} else {
//value does not exists
System.out.println("no!");
209
Sat 1/6/2018
}
System.out.println("\n2. Is value \'orange\' exists?");
if (hash_map.containsValue("orange")) {
System.out.println("yes! - " );
} else {
System.out.println("No!");
}
}
}
Sample Output:
269. Write a Java program to create a set view of the mappings contained in a map.
import java. util.*;
public class Example9 {
public static void main(String args[]) {
HashMap < Integer, String > hash_map = new HashMap < Integer, String > ();
hash_map.put(1, "Red");
hash_map.put(2, "Green");
hash_map.put(3, "Black");
hash_map.put(4, "White");
hash_map.put(5, "Blue");
// create set view for the map
Set set = hash_map.entrySet();
// check set values
System.out.println("Set values: " + set);
}
}
Sample Output:
270. Write a Java program to get the value of a specified key in a map.
import java. util.*;
public class Example10 {
public static void main(String args[]){
HashMap<Integer,String> hash_map= new HashMap<Integer,String>();
hash_map.put(1,"Red");
hash_map.put(2,"Green");
hash_map.put(3,"Black");
hash_map.put(4,"White");
hash_map.put(5,"Blue");
// get value of key String val=(String)hash_map.get(3);
// check the value
System.out.println("Value for key 3 is: " + val);
210
Sat 1/6/2018
}
}
Sample Output:
271. Write a Java program to get a set view of the keys contained in this map.
import java. util.*;
public class Example11 {
public static void main(String args[]){
hash_map.put(1,"Red");
hash_map.put(2,"Green");
hash_map.put(3,"Black");
hash_map.put(4,"White");
hash_map.put(5,"Blue");
272. Write a Java program to get a collection view of the values contained in this map.
import java. util.*;
public class Example12 {
public static void main(String args[]){
211
Sat 1/6/2018
273. Write a Java program to get the first (lowest) key and the last (highest) key currently in a map.
import java. util.*;
import java. util.Map.Entry;
public class Example9 {
public static void main(String args[]) {
// Create a tree map
TreeMap <String,String> tree_map1 = new TreeMap <String,String> ();
// Put elements to the map
tree_map1.put("C2", "Red");
tree_map1.put("C1", "Green");
tree_map1.put("C4", "Black");
tree_map1.put("C3", "White");
System.out.println("Orginal TreeMap content: " + tree_map1);
System.out.println("Greatest key: " + tree_map1.firstKey());
System.out.println("Least key: " + tree_map1.lastKey());
}
}
Sample Output:
274. Write a Java program to get a reverse order view of the keys contained in a given map.
import java. util.*;
import java. util.Map.Entry;
public class Example10 {
public static void main(String args[]) {
// Create a tree map
TreeMap <String,String> tree_map1 = new TreeMap <String,String> ();
// Put elements to the map
tree_map1.put("C2", "Red");
tree_map1.put("C1", "Green");
tree_map1.put("C4", "Black");
tree_map1.put("C3", "White");
System.out.println("Orginal TreeMap content: " + tree_map1);
System.out.println("Reverse order view of the keys: " + tree_map1.descendingKeySet());
}
}
Sample Output:
275. Write a Java program to get the portion of a map whose keys are strictly less than a given key.
import java. util.*;
import java. util.Map.Entry;
public class Example13 {
public static void main(String args[]) {
// Create a tree map
TreeMap < Integer, String > tree_map1 = new TreeMap < Integer, String > ();
212
Sat 1/6/2018
276. Write a Java program to get the portion of this map whose keys are less than (or equal to, if inclusive is
true) a given key.
import java. util.*;
import java. util.Map.Entry;
public class Example14 {
public static void main(String args[]) {
// Create a tree map
TreeMap < Integer, String > tree_map1 = new TreeMap < Integer, String > ();
// Put elements to the map
tree_map1.put(10, "Red");
tree_map1.put(20, "Green");
tree_map1.put(40, "Black");
tree_map1.put(50, "White");
tree_map1.put(60, "Pink");
System.out.println("Orginal TreeMap content: " + tree_map1);
System.out.println("Checking the entry for 10: ");
System.out.println("Key(s): " + tree_map1.headMap(10, true));
System.out.println("Checking the entry for 20: ");
System.out.println("Key(s): " + tree_map1.headMap(20, true));
System.out.println("Checking the entry for 70: ");
System.out.println("Key(s): " + tree_map1.headMap(70, true));
}
}
Sample Output:
277. Write a Java program to get NavigableSet view of the keys contained in a map.
import java. util.*;
import java. util.Map.Entry;
public class Example18 {
public static void main(String args[]) {
// Create a tree map
TreeMap < Integer, String > tree_map1 = new TreeMap < Integer, String > ();
// Put elements to the map
tree_map1.put(10, "Red");
tree_map1.put(20, "Green");
tree_map1.put(40, "Black");
tree_map1.put(50, "White");
tree_map1.put(60, "Pink");
System.out.println("Orginal TreeMap content: " + tree_map1);
System.out.println("Orginal TreeMap content: " + tree_map1.navigableKeySet());
}
}
Sample Output:
278. Write a Java program to remove and get a key-value mapping associated with the least key in a map.
import java. util.*;
import java. util.Map.Entry;
public class Example19 {
public static void main(String args[]) {
// Create a tree map
TreeMap < Integer, String > tree_map = new TreeMap < Integer, String > ();
// Put elements to the map
tree_map.put(10, "Red");
tree_map.put(20, "Green");
tree_map.put(40, "Black");
tree_map.put(50, "White");
tree_map.put(60, "Pink");
// polling first entry
System.out.println("Value before poll: " + tree_map);
System.out.println("Value returned: " + tree_map.pollFirstEntry());
System.out.println("Value after poll: " + tree_map);
}
}
Sample Output:
214
Sat 1/6/2018
279. Write a Java program to get the portion of a map whose keys range from a given key to another key.
import java. util.*;
import java. util.Map.Entry;
public class Example22 {
public static void main(String args[]) {
// Declare tree maps
TreeMap < Integer, String > tree_map = new TreeMap < Integer, String > ();
SortedMap < Integer, String > sub_tree_map = new TreeMap < Integer, String > ();
// Put elements to the map
tree_map.put(10, "Red");
tree_map.put(20, "Green");
tree_map.put(30, "Black");
tree_map.put(40, "White");
tree_map.put(50, "Pink");
System.out.println("Orginal TreeMap content: " + tree_map);
sub_tree_map = tree_map.subMap(20, true, 40, true);
System.out.println("Sub map key-values: " + sub_tree_map);
}
}
Sample Output:
280. Write a Java program to get a key-value mapping associated with the least key greater than or equal to
the given key. Return null if there is no such key.
import java. util.*;
import java. util.Map.Entry;
public class Example25 {
public static void main(String args[]) {
// Declare tree maps
TreeMap < Integer, String > tree_map = new TreeMap < Integer, String > ();
// Put elements to the map
tree_map.put(10, "Red");
tree_map.put(20, "Green");
tree_map.put(30, "Black");
tree_map.put(40, "White");
tree_map.put(50, "Pink");
System.out.println("Orginal TreeMap content: " + tree_map);
System.out.println("Keys greater than or equal to 20: " + tree_map.ceilingEntry(20));
System.out.println("Keys greater than or equal to 40: " + tree_map.ceilingEntry(40));
System.out.println("Keys greater than or equal to 50: " + tree_map.ceilingEntry(50));
}
}
Sample Output:
281. Write a Java program to get the least key greater than or equal to the given key. Returns null if there is no
such key.
import java. util.*;
import java. util.Map.Entry;
public class Example26 {
public static void main(String args[]) {
// Declare tree maps
TreeMap < Integer, String > tree_map = new TreeMap < Integer, String > ();
// Put elements to the map
tree_map.put(10, "Red");
tree_map.put(20, "Green");
tree_map.put(40, "Black");
tree_map.put(50, "White");
tree_map.put(60, "Pink");
System.out.println("Orginal TreeMap content: " + tree_map);
System.out.println("Keys greater than or equal to 20: " + tree_map.ceilingKey(20));
System.out.println("Keys greater than or equal to 30: " + tree_map.ceilingKey(30));
System.out.println("Keys greater than or equal to 50: " + tree_map.ceilingKey(50));
}
}
Sample Output:
sum = sum * 10 + r;
num /= 10;
}
System.out.println(is_positive * sum);
216
Sat 1/6/2018
}
}
Sample Output:
if (ch == 'M') {
result += 1000;
} else if (ch == 'C') {
if (next_char == 'M') {
result += 900;
i++;
} else if (next_char == 'D') {
result += 400;
i++;
} else {
result += 100;
}
} else if (ch == 'D') {
result += 500;
} else if (ch == 'X') {
if (next_char == 'C') {
result += 90;
i++;
} else if (next_char == 'L') {
result += 40;
i++;
} else {
result += 10;
}
} else if (ch == 'L') {
result += 50;
} else if (ch == 'I') {
if (next_char == 'X') {
result += 9;
i++;
} else if (next_char == 'V') {
result += 4;
i++;
} else {
result++;
}
} else { // if (ch == 'V')
result += 5;
}
}
System.out.println("\nRoman Number: "+str);
System.out.println("Equivalent Integer: "+result+"\n");
}
}
217
Sat 1/6/2018
Sample Output:
285. Write a Java program to find the length of the longest sequence of zeros in binary representation of an
integer.
Sample example:
Number 7 has binary representation 111 and has no binary gaps.
Number 8 has binary representation 1000 and contains a binary gap of length 0.
Number 457 has binary representation 111001001 and contains a binary gap of length 2.
Number 40 has binary representation 101000 and contains one binary gap of length 1.
Number 12546 has binary representation 11000100000010 and contains highest binary gap of length 6.
218
Sat 1/6/2018
quot = dec_num;
while(quot != 0)
{
bin_num[i++] = quot%2;
quot = quot/2;
}
String binary_str="";
System.out.print("Binary number is: ");
for(j=i-1; j>0; j--)
{
binary_str = binary_str + bin_num[j];
}
System.out.print(binary_str);
i = binary_str.length()-1;
while(binary_str.charAt(i)=='0') {
i--;
}
int length = 0;
int ctr = 0;
for(; i>=0; i--) {
if(binary_str.charAt(i)=='1') {
length = Math.max(length, ctr);
ctr = 0;
} else {
ctr++;
}
}
length = Math.max(length, ctr);
System.out.println("\nLength of the longest sequence: "+length);
}
}
Sample Output:
286. Write a Java program to convert temperature from Fahrenheit to Celsius degree.
Test Data
287. Write a Java program to calculate the average value of array elements.
public class Exercise4 {
public static void main(String[] args) {
int[] numbers = new int[]{20, 30, 25, 35, -16, 60, -100};
//calculate sum of all array elements
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
//calculate average value
double average = sum / numbers.length;
System.out.println("Average value of the array elements is : " + average);
}
}
Sample Output:
Flowchart:
220
Sat 1/6/2018
Original Array : [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]
221
Sat 1/6/2018
After removing the second element: [25, 56, 15, 36, 56, 77, 18, 29, 49, 49]
289. Write a Java program to insert an element (specific position) into an array.
import java. util.Arrays;
public class Exercise9 {
int Index_position = 2;
int newValue = 5;
System.out.println("Original Array : "+Arrays.toString(my_array));
Sample Output:
Original Array : [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]
New Array: [25, 14, 5, 56, 15, 36, 56, 77, 18, 29]
Flowchart:
222
Sat 1/6/2018
Original array : [1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254, 1472, 2365, 1456,
2165, 1457, 2456]
Reverse array : [2456, 1457, 2165, 1456, 2365, 1472, 1254, 2458, 1458, 2013, 1456,
1899, 2035, 1789]
Flowchart:
223
Sat 1/6/2018
291. Write a Java program to find the duplicate values of an array of string values.
public class Exercise13 {
public static void main(String[] args)
{
String[] my_array = {"bcd", "abd", "jude", "bcd", "oiu", "gzw", "oiu"};
292. Write a Java program to find the duplicate values of an array of integer values.
import java. util.Arrays;
public class Exercise12 {
public static void main(String[] args)
{
int[] my_array = {1, 2, 5, 5, 6, 6, 7, 2};
225
Sat 1/6/2018
}
}
}
}
}
Sample Output:
Duplicate Element : 2
Duplicate Element : 5
Duplicate Element :
Flowchart:
226
Sat 1/6/2018
293. Write a Java program to find the common elements between two arrays (string values).
import java. util.*;
public class Exercise14 {
public static void main(String[] args)
{
String[] array1 = {"Python", "JAVA", "PHP", "C#", "C++", "SQL"};
227
Sat 1/6/2018
System.out.println("Array1 : "+Arrays.toString(array1));
System.out.println("Array2 : "+Arrays.toString(array2));
Flowchart:
228
Sat 1/6/2018
229
Sat 1/6/2018
if(my_array[i] == my_array[j])
{
//Replace duplicate element with last unique element
my_array[j] = my_array[no_unique_elements-1];
no_unique_elements--;
j--;
}
}
}
//Printing arrayWithoutDuplicates
System.out.println();
System.out.println();
System.out.println("---------------------------");
}
}
}
Sample Output:
Original Array :
230
Sat 1/6/2018
0 3 -2 4 3 2
Array with unique values :
0 3 -2 4 2
---------------------------
Original Array :
10 22 10 20 11 22
Array with unique values :
10 22 11 20
---------------------------
Flowchart:
295. Write a Java program to add two matrices of the same size.
Java Code :
import java. util.Scanner;
public class Exercise19 {
public static void main(String args[])
231
Sat 1/6/2018
{
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println();
}
}
}
Sample Output:
232
Sat 1/6/2018
8
Sum of the matrices:-
6 8
10 12
Flowchart:
233
Sat 1/6/2018
234
Sat 1/6/2018
Java Code :
import java. util.ArrayList;
import java. util.Arrays;
public class Exercise20 {
public static void main(String[] args)
{
String[] my_array = new String[] {"Python", "JAVA", "PHP", "Perl", "C#", "C++"};
ArrayList<String> list = new ArrayList<String>(Arrays.asList(my_array));
System.out.println(list);
}
}
Sample Output:
Flowchart:
Java Code :
import java. util.ArrayList;
import java. util.Arrays;
public class Exercise21 {
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add("Python");
list.add("Java");
235
Sat 1/6/2018
list.add("PHP");
list.add("C#");
list.add("C++");
list.add("Perl");
list.toArray(my_array);
Python
Java
PHP
C#
C++
Perl
Flowchart:
236
Sat 1/6/2018
237
Sat 1/6/2018
Flowchart:
299. Write a Java program to move all 0's to the end of an array. Maintain the relative order of the other (non-
zero) array elements.
import java. util.*;
public class Exercise26 {
public static void main(String[] args) throws Exception {
int[] array_nums = {0,0,1,0,3,0,5,0,6};
int i = 0;
System.out.print("\nOriginal array: \n");
for (int n : array_nums)
System.out.print(n+" ");
238
Sat 1/6/2018
array_nums[i++] = 0;
System.out.print("\nAfter moving 0's to the end of the array: \n");
for (int n : array_nums)
System.out.print(n+" ");
System.out.print("\n");
}
}
Sample Output:
Original array:
0 0 1 0 3 0 5 0 6
After moving 0's to the end of the array:
1 3 5 6 0 0 0 0 0
Flowchart:
239
Sat 1/6/2018
300. Write a Java program to compute the average value of an array of integers except the largest and smallest
values.
import java. util.*;
import java. io.*;
public class Exercise29 {
public static void main(String[] args)
240
Sat 1/6/2018
{
int[] array_nums = {5, 7, 2, 4, 9};
System.out.println("Original Array: "+Arrays.toString(array_nums));
int max = array_nums[0];
int min = array_nums[0];
float sum = array_nums[0];
for(int i = 1; i < array_nums.length; i++)
{
sum += array_nums[i];
if(array_nums[i] > max)
max = array_nums[i];
else if(array_nums[i] < min)
min = array_nums[i];
}
float x = ((sum-max-min) / (array_nums.length - 2));
System.out.printf("Compute the average value of an array of integers except the largest and
smallest values: %.2f",x);
System.out.print("\n");
}
}
Sample Output:
Flowchart:
241
Sat 1/6/2018
301. Write a Java program to check if an array of integers contains two specified elements 65 and 77.
import java. util.*;
import java. io.*;
public class Exercise32 {
public static void main(String[] args)
{
int[] array_nums = {77, 77, 65, 65, 65, 77};
System.out.println("Original Array: "+Arrays.toString(array_nums));
int num1 = 77;
int num2 = 65;
Flowchart:
302. Write a Java program to find the length of the longest consecutive elements sequence from a given
unsorted array of integers.
Sample array: [49, 1, 3, 200, 2, 4, 70, 5]
The longest consecutive elements sequence is [1, 2, 3, 4, 5], therefore the program will return its length 5.
import java. util.HashSet;
public class Exercise34 {
public static void main(String[] args) {
int nums[] = {49, 1, 3, 200, 2, 4, 70, 5};
System.out.println("Original array length: "+nums.length);
System.out.print("Array elements are: ");
for (int i = 0; i < nums.length; i++)
{
System.out.print(nums[i]+" ");
}
243
Sat 1/6/2018
Flowchart:
244
Sat 1/6/2018
303. Write a Java program to find all the unique triplets such that sum of all the three elements [x, y, z (x ≤ y ≤
z)] equal to a specified number.
Sample array: [1, -2, 0, 5, -1, -4]
Target value: 2.
import java. util.ArrayList;
import java. util.List;
public class Exercise36 {
public static void main(String[] args) {
int[] input = {1, -2, 0, 5, -1, -4};
int target = 2;
Exercise36 r = new Exercise36();
System.out.println(r.threeSum(input,target));
}
public List<List<Integer>> threeSum(int[] nums, int target) {
245
Sat 1/6/2018
Flowchart:
246
Sat 1/6/2018
Write a Java program to create an array of its anti-diagonals from a given square
matrix.
Example:
Input :
12
34
Output:
[
[1],
[2, 3],
[4]
]
Input:
[10, 20, 30]
[50, 60, 70]
[90, 100, 110]
247
Sat 1/6/2018
Output:
[10]
[20, 50]
[30, 60, 90]
[70, 100]
[110]
//https://github. com/nagajyothi/Arrays/blob/master/Diagonal.java
import java. util.*;
public class Exercise3{
public static ArrayList<ArrayList<Integer>> Exercise37(ArrayList<ArrayList<Integer>> A) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
int m = a. size();
int n = a. get(0).size();
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(a. get(0).get(0));
result.add(new ArrayList<Integer>(temp));
int i = 0;
while(i < m){
System.out.printf("For i : %d \n", i );
int j = i+1;
while(j < n){
int k = i;
int l = j;
temp.clear();
System.out.printf("\t For j : %d \n", j );
while(l >= 0 && k < m){
System.out.printf("\t \t For k : %d and l : %d add \n", k, l, a.
get(k).get(l) );
temp.add(a. get(k).get(l));
k++;
l--;
}
System.out.println("\t \t Temp : " + temp);
result.add(new ArrayList<Integer>(temp));
j++;
}
i++;
}
temp.clear();
temp.add(a. get(m-1).get(n-1));
result.add(new ArrayList<Integer>(temp));
return result;
}
248
Sat 1/6/2018
result.add(new ArrayList<Integer>(temp));
int j;
int i = 0;
j = i+1;
while(j < n){
int k = i;
int l = j;
temp.clear();
while(k < m && l >= 0){
temp.add(a. get(k).get(l));
k++;
l--;
}
result.add(new ArrayList<Integer>(temp));
j++;
}
i = 1;
j = n-1;
while(i < m){
int k = i;
int l = j;
temp.clear();
while(k < m && l >= 0){
temp.add(a. get(k).get(l));
k++;
l--;
}
result.add(new ArrayList<Integer>(temp));
i++;
}
temp.clear();
return result;
}
public static void main(String[] args){
ArrayList<ArrayList<Integer>> A = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(10);
temp.add(20);
temp.add(30);
a. add(new ArrayList<Integer>(temp));
temp.clear();
temp.add(50);
temp.add(60);
temp.add(70);
a. add(new ArrayList<Integer>(temp));
temp.clear();
temp.add(90);
249
Sat 1/6/2018
temp.add(100);
temp.add(110);
a. add(new ArrayList<Integer>(temp));
temp.clear();
for(ArrayList<Integer> t : A)
System.out.println(t);
[
[1],
[2, 3],
[4]
]
304. Write a Java program that reads a number and display the square, cube, and fourth power.
Test Data
Input the side length value: 1
import java. util.Scanner;
public class Exercise8 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the side length value: ");
double val = in.nextDouble();
System.out.printf("Square: %12.2f\n", val * val);
System.out.printf("Cube: %14.2f\n", val * val * val);
System.out.printf("Fourth power: %6.2f\n", Math.pow(val, 4));
}
}
Sample Output:
250