Three color sort


Given a linear integer array (which has only 0s, 1s, 2s) in unsorted fashion, you need to sort that array with very minimal swaps and visit to the node. public class Answer implements ThreeColorSortInterface { @Override public void PerformThreeColorSort(ColorArray colArray) { // WRITE YOUR CODE HERE return ; } public static void main(String [] args) { // write code here to test } } Here is the ColorArray.java class (only for reference). public class ColorArray { private int[] mArr; private int mSize; public ColorArray(int [] arr, int size){ this.mArr = arr; this.mSize = size; } public int GetSize(){ return this.mSize; } public int GetColor(int index){ if(index <0 || index >= this.mSize) return -1; return this.mArr[index]; } // return true on successful swap public boolean Swap(int index1, int index2){ if(index1 <0 || index1 >= this.mSize) return false; if(index2 <0 || index2 >= this.mSize) return false; int temp = this.mArr[index1]; this.mArr[index1] = this.mArr[index2]; this.mArr[index2] = temp; return true; } } Example1: Input: {0, 1, 1, 0, 2} Output:{0, 0, 1, 1, 2} Example2: Input: {2,2,1,1,0,0,1,1,2,2} Output:{0,0,1,1,1,1,2,2,2,2}

Answer

Swap every two nodes in a single linked list


Write code to swap every two nodes in a single linked list. Example: Input: 2 -> 3 -> 31 -> 21 -> 5 Output: 3 -> 2 -> 21 -> 31 -> 5 public class Answer implements SwapEveryTwoNodesInLinkedListInterface{ @Override public Node SwapEveryTwoNodesInLinkedList(Node head) { // WRTIE YOUR CODE HERE return ; } } // Here is the Node.java public class Node { public int nodeValue; public Node nextNode; }

Answer

Base2 number system conversion


Given a number, you need to return a string which has the base 2 representation. Dont use any built-in methods to convert public class Answer implements Base2SystemInterface { @Override public String GetBase2System(int num) { // WRITE YOUR CODE HERE return ; } public static void main(String [] args) { // write code here to test } } Example1: Input: 6 Output:"110" Example2: Input: 16 Output:"10000"

Answer

Reverse words in a line


Given a string reverse the words in that line. public class Answer implements ReverseStringInLineInterface { @Override public String PerformReverseStringInLine(String str) { // WRITE YOUR CODE HERE return ; } public static void main(String [] args) { // write code here to test } } Example1: Input: "Hello World" Output:"World Hello" Example2: Input: "A B C" Output:"C B A"

Answer

Next immediate greatest number which has all the digits

Given a integer, find the next immediate greatest number which has all the digits in the given number public class Answer implements NextLargeNumberInterface { @Override public int GetNextLargeNumber(int num) { // WRITE YOUR CODE HERE return ; } public static void main(String [] args) { // write code here to test } } Example1: Input: 2586 Output:2658 Example2: Input: 469 Output:496

Answer

Run length encoding of a string

Given a string, you need to count the consecutive characters and show the count in the string for each character. If there is only one character, you dont need to show the count. public class Answer implements RunLengthEncodingInterface { @Override public String DoRunLengthEncoding(String str) { // WRITE YOUR CODE HERE return ; } public static void main(String [] args) { // write code here to test } } Example1: Input: "aaaabbbcddddaa" Output:"a4b3cd4a2"

Answer

Three Number Sum

Given a integer array and magic number, if there are any three numbers in the array sum up to magic number return true, else return false. Input: Array: {-10, -9, -7, 5, 0, 99} Arraylength: 6 MagicNumber: -17 Output: true Input: Array: {0, 1, 3, 5, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0} Arraylength: 14 MagicNumber: 21 Output: false public class Answer implements ThreeNumberSumInterface { @Override public boolean ThreeNumberSum(final int [] arr, int arrlen, int magicNumber) { // WRITE YOUR CODE HERE return true; } public static void main(String [] args) { // write code here to test } }

Answer

Maximum ascending sequence length



Given a integer array, find the maximum length of ascending order sequence. Input: Array: {0, 1, 3, 5, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0} Arraylength: 14 Output: Maximum Ascending sequence length: 7 Input: Array: {2, -2, 2, -2, 2} Arraylength: 5 Output: Maximum Ascending sequence length: 1 public class Answer implements GetMaxAscSequenceLengthInterface { @Override public int GetMaxAscSequenceLength(final int [] arr, int arrlen) { // WRITE YOUR CODE HERE return 0; } public static void main(String [] args) { // write code here to test } }

Answer

Minimum distance between chars

Given a String, start char and end char, find the minimum distance between these two chars. If one of the strings is null or if the characters are not present we should return 0 Input 1: String: "hello world" Char1: ' ' Char 2: 'o' Output: 2 Input 2: String: "can I go to zoo" Char1: 'o' Char 2: 'o' Output: 1 public class Answer implements MinDistanceBetweenCharsInterface { @Override public int MinDistanceBetweenChars(String str, char startChar, char endChar) { // WRITE YOUR CODE HERE return 0; } public static void main(String [] args) { // write code here to test } }

Answer

Substring Same sequence

Given a String and substing, check whether the character in substring are present in the main string in the SAME SEQUENCE. If yes, return true. Input 1: String: "Hello" Substring: "elo" Output: true Input 2: String: "hi friends" Substring: "hiiids" Output: false public class Answer implements SubStringSameSequenceInterface { @Override public boolean SubStringSameSequence(String str, String subStr) { // WRITE YOUR CODE HERE return ; } public static void main(String [] args) { // write code here to test } }

Answer

Shuffle Merge two lists to form a new list

Given two linked lists of integers, shuffle merge those two lists to form a new linked list. Example: List1 : 1->3->5->7->9->10 List2: 2->4->6->8 Output: 1->2->3->4->5->6->7->8->9->10 Please note that after you pick elements alternatively from 2 lists, if one of the lists run out of elements, you need to pick the remaining elements from the other list and append. public class Answer implements ShuffleMergeListsInterface { @Override public Node ShuffleMergeLists(Node node1, Node node2) { //WRITE YOUR CODE HERE } } // Here is the Node.java public class Node { public int nodeValue; public Node nextNode; }

Answer

Remove Duplicates from the list

Given a linked list of integers, remove all the duplicate elements in the list. Elements are not necessarily in a sorted order. Input: 1->2->2->3->4->3 Output: 1->2->3->4 Input: 2->2->2->2->2 Ouput: 2 Please note that the sequence should be maintained in the list after the duplicate removal. public class Answer implements RemoveDuplicatesInterface { @Override public void DuplicateRemoval(Node headNode) { //WRITE YOUR CODE HERE } } // Here is the Node.java public class Node { public int nodeValue; public Node nextNode; }

Answer

Check if the linked list of integers is Palindrome

Given a singly linked list of integers, check if the values of the nodes are symmetrical(Palindrome). Example: 1->23->45->6->45->23->1->null is symmetrical 1->23->4->32->1->null is not symmetrical null is not symmetrical 1->null is symmetrical public class Answer implements PalindromeListInterface { @Override public boolean CheckPalindrome(Node node) { // WRITE YOUR CODE HERE } } // Here is the Node.java public class Node { public int nodeValue; public Node nextNode; }

Answer

Fully sort the list which is sorted in parts

You have a singly linked list in which the first part and the second part(not exactly split in the middle) are sorted independently. You need to return a fully sorted list merging these two parts. For example: Input: 1->3->5->7->2->4->6->8 Output: 1->2->3->4->5->6->7->8 Your Answer.java need to implement the following interface public class Answer implements FullySortSLLInterface { @Override public Node FullySortSLL(Node node) { //WRITE YOUR CODE HERE } } Here is the Node.java. You don't need to upload this class. public class Node { public int nodeValue; public Node nextNode; }

Answer

Finding first non repeated character in the String using Hash map

You are given a String and a hashmap. You need to use the Hashmap to find the first non repeated character in the String. Input : aaabbcd Result: c Input : null Result: ' ' Input: HelloKHello Result: K You MUST use the hashmap passed as an argument in your solution. Otherwise, your test cases won't succeed. Your Answer.java must implement the following interface. import java.util.Map; public interface FirstNonRptedCharInterface { public char FindFirstNonRepeatedCharacter(String inputString, Map<Character, Integer> inputMap); }

Answer

Ransom Note from Magazine using Hash table

Kidnapper kidnaps you and writes a ransom note. He does not write it with hand, as handwriting can put him in, so reaches to a magazine at table and creates ransom note. We need to find out given ransom string and magazine string, is it possible to create given ransom note. Kidnapper can use individual characters of words. We need to check if magazine string contains all characters and in equal or greater number, present in ransom note. You MUST use hashmap passed as an argument to solve the problem. Otherwise testcases will fail. Magazine : abcdefgab Note: baba Output: true Magazine: abcdedf Note: baba Output: false Your Answer.java should implement the following interface. import java.util.Map; public interface RansomNoteInterface { public boolean CheckIfRansomNoteCanbeFormed(String magazine, String note, Map<Character, Integer> inputMap); }

Answer

Two numbers sum upto a given value using Hashmap

Find if there are two elements in the array sum up to given value. You MUST use the hashmap passed as an argumentto solve the problem. If you don't your test cases will fail. Input: {1, 2, 3, 4, 5} Value: 6 Output : true Input: {1, 2, 3, 4, 5} Value: 2 Output : false Your Answer.java should implement the following interface import java.util.Map; public interface TwoNumbersSumInterface { public boolean TwoNumbersSumWithHashInterface(int[] array, int value, Map<Integer, Integer> hashMap); }

Answer


Find all the extreme nodes of a binary tree in a zigzag order

Find the extreme nodes of each level of Binary Tree in alternate order. For example, for the following binary tree, 1 2 3 4 5 6 7 8 Should have output 1->2->7->8 Your Answer.java should implement following interface. import java.util.List; public interface ExtremeNodesInterface { public List<Integer> PrintExtremeNodesZigZag(Node root); } Sample Node.java (No need to upload this) public class Node { public int nodeValue; public Node lChild; public Node rChild; }

Answer

Check if Binary tree is symmetric

Given a binary tree you need to check if the left sub-tree from the root is a mirror image of the right sub-tree. Please note that the symmetric nature is evaluated purely based on the structure of the tree and not based on any node values. For example. 1 2 3 4 5 Is a symmetric binary tree. Where as 1 2 3 4 5 is not a symmetric binary tree. Your Answer.java should implement the following interface. public interface SymmetricBinaryTree { boolean IsBinaryTreeSymmetricAtRoot(Node node); } Here is the Node.java. You don't need to upload this file. public class Node { public int nodeValue; public Node lChild; public Node rChild; }

Answer

Boundary traverse a binary tree

Find all the boundary nodes in a given binary tree. The boundary traversal should start from root, then go clockwise (root->right->left) For example 1 2 3 4 4 6 7 8 9 1 1 2 3 3 4 This should return: 1->3->7->4->3->3->2->1->1->9->8->4->2 Your Answer.java should implement the following interface import java.util.List; public interface BoundaryTraverseTree { public List<Integer> BoundaryTraverse(Node root); } Here is the sample Node.java (No need to upload this file) public class Node { public int nodeValue; public Node lChild; public Node rChild; }

Answer

Check element in Binary Search Tree

Given a binary search tree with positive integers, check if given element is present in the given tree. for eg: 14 / \ / \ 3 17 / \ / \ 2 4 16 18 k = 9 Output: false k = 16 Output: true Here is sample Node.java (No need to upload this) public class Node { public int nodeValue; public Node lChild; public Node rChild; }

Answer

Sum of Kth Largest Element in Binary Search Tree

Given a binary search tree with positive integers, find the sum of k largest elements of the BST. (given k <= number of elements in BST) for eg: 5 / \ / \ 3 7 / \ / \ 2 4 6 8 k = 3 Sum = 6 + 7 + 8 = 21 Output: 21 Here is sample Node.java (No need to upload this) public class Node { public int nodeValue; public Node lChild; public Node rChild; }

Answer


Chocolate distribution problem

Given an array of n integers where each value represents number of chocolates in a packet. Each packet can have variable number of chocolates. There are m students, the task is to distribute chocolate packets such that : 1) Each student gets one packet. 2) The difference between the number of chocolates in packet with maximum chocolates and packet with minimum chocolates given to the students is minimum. Input : arr[] = {7, 3, 2, 4, 9, 12, 56} m = 3 Output: Minimum Difference is 2 We have seven packets of chocolates and we need to pick three packets for 3 students If we pick 2, 3 and 4, we get the minimum difference between maximum and minimum packet sizes.

Answer

Print Palindromic Paths

Given a matrix containing lower alphabetical characters only, we need to find all palindromic paths in given matrix. A path is defined as a sequence of cells starting from top-left cell and ending at bottom-right cell. We are allowed to move to right and down only from current cell. You cannot go down diagonally. Input : mat[][] = {"aaab”, "baaa” “abba”} aaaaaa (0, 0) -> (0, 1) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 3) aaaaaa (0, 0) -> (0, 1) -> (0, 2) -> (1, 2) -> (1, 3) -> (2, 3) abaaba (0, 0) -> (1, 0) -> (1, 1) -> (1, 2) -> (2, 2) -> (2, 3) Output = {"aaaaaa","aaaaaa","abaaba"} Order of elements in the output array doesn't matter. Your Answer.java should implement following interface. public String[] findPalindromicPaths(String[] input) { return null; }

Answer

Minimum number of hops to reach end of array or beyond

Given an array of integers where each element represents the max number of steps that can be made forward from that element. Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then cannot move through that element. Example: Input: arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9} Output: 3 (1-> 3 -> 8 ->9) First element is 1, so can only go to 3. Second element is 3, so can make at most 3 steps eg to 5 or 8 or 9. If there is no path, return 0. Your Answer.java should implement following interface public interface NumberOfHopsInterface { public int numberOfHops(int[] array); }

Answer

Find the indices with anagram match

Given a String and a pattern find all the indices at which where we find an anagram match. For example: String : BACDGABCDA Pattern : ABCD We can find a match at {0, 5, 6} In other words, if we find 4 consecutive characters from these indices, it contains the characters needed to match the pattern. Your solution should implement the following interface: public interface AnagramSearchIndexInterface { public List<Integer> anagramSubstringSearch(String source, String pattern); }

Answer

Find if there are three elements in BST that sums up to zero

Given a binary tree, check if there are three elements in binary tree which will sum up to zero. Return true if triplet exists, if not return false. For example: 4 2 6 -5 3 In this binary tree, {-5, 2, 3} sum up to zero and you should return true. 0 -1 1 In this binary tree, {-1, 1, 0} sum up to zero and you should return true 1 -1 2 In this binary tree, there doesn't exist a triplet that sum to zero and the result should be false. Your Answer.java should implement the following interface, public interface TripletSummingToZeroInterface { public boolean doesTripletSumToZero(Node root); } Node.java (No need to submit this, just for reference) public class Node { public int nodeValue; public Node lChild; public Node rChild; }

Answer

Substring for given two chars

Given a string, determine the length of the smallest substring that contains exactly one occurrence of 'a' and one occurrence of 'b' If there are no such substrings, return 0 Input : ahhhxb Output : 6 Input : ahobpa Output : 3 Input : qqqop Output : 0

Answer



Find Max Continuous Repeating Char

Given a string, return the character that is repeated the most number of times continuously. Note: Do not count the character that occurs most overall, but count only the character that occurs most number of times continuously Note: If two characters occur the same number of times continuously, return the first such in the string. Input : AABBBC Output : B Input : AAABBB Output : A

Answer

Pattern Problem | Right angle Triangle



Output

Sample 1



Enter the limit:
5
*
==========
*
**
==========
*
**
***
==========
*
**
***
****
==========
*
**
***
****
*****

==========

Sample 2

Enter the limit:
10
*
==========
*
**
==========
*
**
***
==========
*
**
***
****
==========
*
**
***
****
*****
==========
*
**
***
****
*****
******
==========
*
**
***
****
*****
******
*******
==========
*
**
***
****
*****
******
*******
********
==========
*
**
***
****
*****
******
*******
********
*********
==========
*
**
***
****
*****
******
*******
********
*********
**********
==========

Program to find FLAMES in java


Output

Enter your name: 
Jothibasu
Enter your partner's name: 
people
The number is : 13

people is your Affection


Enter your name: 
Jothibasu
Enter your partner's name: 
Google
the number is : 11

Google is going to marry You


Odd numbers in odd index of array | Even numbers in even index of array

This logic is written only for equal number of odd and even numbers




Sample Output 

Enter array size:
6
Enter array elements:
1 2 3 4 5 6
After Shifting array elements :
5

Source Code


Pattern Problem | Rectangle Pattern


Test Case #1

Enter length:
10
Enter breadth:
4

Output

**********
*               *
*               *
**********

Test Case #2

Enter length:
50
Enter breadth:
10

Output

**************************************************
*                                                                                         *
*                                                                                         *
*                                                                                         *
*                                                                                         *
*                                                                                         *
*                                                                                         *
*                                                                                         *
*                                                                                         *
**************************************************

Program

import java.util.*;

package jothibasu.com;

public class RectanglePattern {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int length,breadth;
System.out.println("Enter length:");
length = scan.nextInt();
System.out.println("Enter breadth:");
breadth = scan.nextInt();
//First Line
for (int i = 0 ; i < length ; i++)
System.out.print("*");
//Moving to next line
System.out.println();
/*Execute the loop up to breadth
  Here [breadth-2] given because
  of considering 1st and last line*/
for (int j = 0 ; j < breadth - 2 ; j++) {
//First * of breadth
System.out.print("*");
//Printing the space inside rectangle
for (int k = 0 ; k < length - 2 ; k++)
System.out.print(" ");
//Last * of breadth
System.out.print("*");
//Moving to next line
System.out.println();
}
//Last line
for (int l = 0 ; l < length ; l++)
System.out.print("*");
//Closing the scanner object
scan.close();
}
}

Pattern Problem | Alphabets

Test Case #1

Enter limit:
Z
Enter difference:
1

Output 

A
C
E
G
I
K
M
O
Q
S
U
W
Y

Test Case #2

Enter limit:
Z
Enter difference:
2

Output

AD
GJ
MP
SV
Y

Test Case #3

Enter limit:
Z
Enter difference:
3

Output

AEI
MQU
Y

Program


import java.util.*;

package jothibasu.com;

public class Pattern {

   public static void main(String[] args) {
int counter = 1;
char limit;
int difference;
Scanner scan = new Scanner(System.in);
System.out.println("Enter limit:");
limit = scan.next().charAt(0);
System.out.println("Enter difference:");
difference = scan.nextInt();
//Loop will execute up to the given limit
for (char value = 'A'; value <= limit ; value++) {
System.out.print(value);
//Converting character into integer 
                  [Type Conversion, ASCII value]
int charToInteger = (int) value;
//Add the difference to that integer value
charToInteger = charToInteger + difference;
//Converting integer to character
value = (char) charToInteger;
//Move to new line based on the difference given
if (counter % difference == 0)
System.out.println("");
counter++;
//Closing the scanner class object
scan.close();
}
}
}