Showing posts with label Linked-List. Show all posts
Showing posts with label Linked-List. Show all posts

Monday, September 12, 2016

Nagarro Coding Questions for Experienced Interview Android

1)Given an unsorted list of repeated elements in an array, Find the element with maximum frequency.
Solution:

There are two approaches for this:
1)Naive Approach: Need two loop,outer-inner and outer loop will pick element and will traverse and inner loop will just count the duplicate.

Time Complexity: o(n^2)

2)Better Approach: 

Time Complexity: o(n) and o(k) for space where k=size;
/*
 * @author Abhinaw.Tripathi
 *
 */
public class MaxRepeatingApp
 {
public static void main(String[] args)
{
int arr[] = {2, 3, 3, 5, 3, 4, 1, 7};
                int n = arr.length;
                int k=8;
                System.out.println("Maximum repeating element is: " +maxRepeating(arr,n,k));
}
public static int maxRepeating(int[] arr,int n,int k)
{
for(int i=0;i<n;i++)
arr[(arr[i])%k] +=k;

int max=arr[0],result=0;
for(int i=0;i<n;i++)
{
if(arr[i] > max)
{
max=arr[i];
result=i;
}
}
return result;
}
}
Result: Maximum repeating element is: 3

2) Given a string containing characters and brackets, find if the brackets are paired in the string.

Solution: 
public static boolean pairedNotpaired(String str)
{
Stack stack=new Stack();
boolean result=true;
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i);
switch (c) 
{
 case ')':
 if((Character)stack.pop()!=null)
 {
 return false;
 }
 
 case '}':
 
 if((Character)stack.pop()!=null)
 {
 return false;
 }
 
break;
 case ']' :
 {
 if((Character)stack.pop()!=null)
 {
 return false;
 }
 }

default:
stack.push(c);
break;
}
}
return result;

}


3) Given a set of integers, find the third maximum sum of two elements from the set.
Solution:
/**
 * @author Abhinaw.Tripathi
 *
 */
public class ThirdlargestSumApp {

public static int swap(int a, int b)
{
return a;
}
public static void main (String[] args) throws java.lang.Exception
{
   int k = 3;                            //Finding kth largest pair sum in array "a".
   int []a = {-2, 3, 4, -1, 5, 7, 8};   //input array
   int []b = new int[k]; //Holds the calculated pair sum. Not more than k highest pair-sum arerequired at any moment.  
   
   for(int i = 0; i < k; i++) 
    b[i] = Integer.MIN_VALUE;
   
   for(int i = 0; i < a.length-1; i++)
   {
       int pair = a[i] + a[i+1];
       if(pair > b[0]) 
       {                                //Compare with the Min Value i.e. b[0].
           b[0] = pair;
           System.out.println("All Sum:" +b[0]);                                                      
           if(b[1] < b[0]) 
           {
               b[1] = swap(b[0], b[0]=b[1]); // To satisfy parent(b[0]) <= left_child(b[1]) constraint for MinHeap
           }
           if(b[2] < b[0])
           {
               b[2] = swap(b[0], b[0]=b[2]); // To satisfy parent(b[0]) <= right_child(b[1]) constraint for MinHeap
           }
       }
   }
   System.out.println( "\n" +"3rd Sum:" +b[0]);
}
}

4)Find middle element efficiently of a Circular Linked List.
Solution:

class LinkedList
{
Node head; 
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}

void printMiddle()
{
Node slow_ptr = head;
Node fast_ptr = head;
if (head != null)
{
while (fast_ptr != null && fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
System.out.println("The middle element is [" +
slow_ptr.data + "] \n");
}
}

public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}

public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+"->");
tnode = tnode.next;
}
System.out.println("NULL");
}

public static void main(String [] args)
{
LinkedList llist = new LinkedList();
for (int i=5; i>0; --i)
{
llist.push(i);
llist.printList();
llist.printMiddle();
}
}
}

5) Given a string ,find the longest sub-string with all distinct characters in it.If there are multiple such strings,print them all.

Solution:
/**
 * 
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
import java.util.*;
 
public class UniqueSubStringApp
  static boolean isValid(int count[],int k)
   {
int val = 0;
    for (int i=0; i<26; i++)
        if (count[i] > 0)
            val++;
 
    return (k >= val);
   }
static int uniquesubstring(String s,int k)
{
int u=0;
int max=0,max_start=0;
int cur_start=0;
int cur_end=0;
int n=s.length();
int count[]=new int[27];
Arrays.fill(count,0);
for(int i=0;i<n;i++)
{
if(count[s.charAt(i)-'a']==0)
{
u++;
}
count[s.charAt(i)-'a']++;
}
if(u<k)
{
System.out.printf("k is greater than no of characters");
return 0;
}
Arrays.fill(count,0);
count[s.charAt(0)-'a']++;
for(int i=1;i<n;i++)
{
count[s.charAt(i)-'a']++;
cur_end++;
while(!isValid(count,k))
{
count[s.charAt(cur_start)-'a']--;
cur_start++;
}
 
if(cur_end-cur_start+1>max)
{
max=cur_end-cur_start+1;
max_start=cur_start;
}
 
}
 
System.out.println("Max substring "+s.substring(max_start,cur_end+1));
System.out.println("length "+max);
return 0;
}
public static void main (String[] args) throws java.lang.Exception
{
String s="aabacbebebe";
int k=3;
uniquesubstring(s,3);
}
}

Friday, June 17, 2016

LinkedList Collection Class example java

LinkedList Class

A Linked list contains a group of elements in the form of nodes.Each node will have three fields---the data field contains data and the link fields contain references to previous and next nodes.

Linked List is very convenient to store data.Inserting the elements into the linked list and removing the elements from the linked list is done quickly and takes same amount of time.

LinkedList Class Methods

  • boolean add(element obj)
  • void add(int position,element obj)
  • void addFirst(element obj
  • void addLast(element obj)
  • element removeFirst()
  • element removeLast()
  • element remove(int position)
  • void clear()
  • element get(int position)
  • element getFirst()
  • element getLast()
  • element set(int position,element obj)
  • int size()
  • int indexOf(Object obj)
  • int lastIndexOf(Object obj)
  • Object[] toArray()
Program:


/**
 * 
 */
package com.collectionpack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;

/**
 * @author Abhinaw.Tripathi
 *
 */
public class LinkedListApp
{
/**
* @param args
* @throws IOException 
* @throws NumberFormatException 
*/
public static void main(String[] args) throws NumberFormatException, IOException
{
LinkedList<String> ll=new LinkedList<>();
ll.add("America");
ll.add("India");
ll.add("japan");
System.out.println("list= "+ll);
int choice = 0;
int position;
String element;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(choice < 4)
{
System.out.println("LinkedList  Operation");
System.out.println("1 Add an element");
System.out.println("2 Remove an element");
System.out.println("3 Change an element?");
System.out.println("4 Exist");
System.out.println("Your Choice: ");
choice=Integer.parseInt(br.readLine());
switch (choice) 
{
case 1:
System.out.println("Enter element: ");
element=br.readLine();
position=Integer.parseInt(br.readLine());
ll.add(position - 1,element);
break;
case 2:
System.out.println("Enter position:");
position=Integer.parseInt(br.readLine());
ll.remove(position-1);
break;
case 3:
System.out.println("Eneter element?");
position=Integer.parseInt(br.readLine());
System.out.println("Eneter new element?");
element=br.readLine();
ll.set(position-1, element);
break;
default:
return;
}
}
}

}

Output:

list= [America, India, japan]
LinkedList  Operation
1 Add an element
2 Remove an element
3 Change an element?
4 Exist
Your Choice: 
1
Enter element: 
20


Thursday, June 9, 2016

Doubly Linked Lists operation example in core java

Doubly Linked List basic operation example:

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */

class Link
{
 public long dData;
 public Link next;
 public Link previous;

 public Link(long d)
 {
this.dData=d;
 }

 public void displayLink()
 {
 System.out.println(dData+ " ");
 }

}

class DoublyLinkedList
{
  private Link first;
  private Link last;

  public DoublyLinkedList()
  {
first=null;
last=null;
  }
  public boolean isEmpty()
  {
return (first==null);
  }

  public void insertFirst(long dd)
  {
 Link newLink=new Link(dd);
 if(isEmpty())
 {
 last=newLink;

 }
 else
  first.previous=newLink;
 newLink.next=first;
 first=newLink;
  }

  public void insertLast(long dd)
  {
 Link newLink=new Link(dd);
 if(isEmpty())
 first=newLink;
 else
 {
 last.next=newLink;
    newLink.previous=last;
 }
 last=newLink;
  }

  public Link deleteFirst()
  {
 Link temp=first;
 if(first.next == null)
 last=null;
 else
 first.next.previous=null;
 first=first.next;
 return temp;
  }

  public Link deleteLast()
  {
 Link temp=last;
 if(first.next == null)
 first=null;
 else
 last.previous.next=null;
 last=last.previous;
 return temp;
  }


  public boolean insertAfter(long key,long dd)
  {
 Link current =first;
 while(current.dData!=key)
 {
 current=current.next;
 if(current == null)
 return false;
 }

 Link newLink=new Link(dd);

 if(current==last)
 {
 newLink.next=null;
     last=newLink;
 }
 else
 {
 newLink.next=current.next;
 current.next.previous=newLink;
 }

 newLink.previous=current;
 current.next=newLink;
 return true;
  }

  public Link deletekey(long key)
  {
 Link current=first;
 while(current.dData!=key)
 {
 current=current.next;
 if(current==null)
 return null;
 }
 if(current == first)
 first=current.next;
 else
 current.previous.next=current.next;

 if(current==last)
 last=current.previous;
 else
 current.next.previous=current.previous;
 return current;
  }

  public void displayForward()
  {

 System.out.println("List (first-----.last:)");
 Link current =first;
 while(current!=null)
 {
 current.displayLink();
 current=current.next;
 }
 System.out.println(" ");
  }

  public void displayBackward()
  {
 System.out.println("List (last---->first)");
 Link current=last;
 while(current!=null)
 {
 current.displayLink();
 current=current.previous;
 }
 System.out.println("  " );
  }

}


public class DoublyLinkedApp
{
public static void main(String[] args)
{
DoublyLinkedList theList=new DoublyLinkedList();
theList.insertFirst(22);
theList.insertFirst(44);
theList.insertFirst(66);

theList.insertLast(11);
theList.insertLast(33);
theList.insertLast(55);

theList.displayForward();
theList.displayBackward();

theList.deleteFirst();
theList.deleteLast();
theList.deletekey(11);

theList.displayForward();
theList.displayBackward();

theList.insertAfter(22, 77);
theList.insertAfter(33, 88);

theList.displayForward();

}

}


The desire output will be

List (first-----.last:)
66 
44 
22 
11 
33 
55 

List (last---->first)
55 
33 
11 
22 
44 
66 
  
List (first-----.last:)
44 
22 
33 

List (last---->first)
33 
22 
44 
  
List (first-----.last:)
44 
22 
77 
33 
88 



Queue implemented by a Linked List in core-java example

Queue implemented by a Linked List:

/**
 * @author Abhinaw.Tripathi
 *
 */

class Link
{

 public long dData;
 public Link next;

 public Link(long dd)
 {
dData=dd;
 }

 public void displayLink()
 {
 System.out.println(dData+ " ");
 }

}

class FirstLastList
{
  private Link first;
  private Link last;

  public FirstLastList()
  {
first=null;
last=null;
  }

  public boolean isEmpty()
  {
return (first==null);
  }

  public void insertLast(long dd)
  {
 Link newLink=new Link(dd);
 if(isEmpty())
 first=newLink;
 else
 last.next=newLink;
 last=newLink;
  }

  public long deleteFirst()
  {
 long temp=first.dData;
 if(first.next == null)
 last=null;
 first=first.next;
 return temp;
  }

  public void displayList()
  {
Link current=first;
while(current!=null)
{
current.displayLink();
current=current.next;
}

System.out.println(" ");
   }

}

class LinkQueue
{
private FirstLastList theList;

public LinkQueue()
{
theList=new FirstLastList();
}

public boolean isEmpty()
{
return (theList.isEmpty());
}

public void insert(long j)
{
theList.insertLast(j);

}

public long remove()
{
return theList.deleteFirst();
}

public void displayQueue()
{
System.out.println("Queue (front ---> rear:)");
theList.displayList();
}
}

public class LinkQueueApp {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
     LinkQueue theQueue=new LinkQueue();
     theQueue.insert(20);
     theQueue.insert(40);
   
     theQueue.displayQueue();
   
     theQueue.insert(60);
     theQueue.insert(80);
   
     theQueue.displayQueue();
   
     theQueue.remove();
     theQueue.remove();
   
     theQueue.displayQueue();
}


}

The desire output will be

Stack  (top---->bottom:)
40 
20 

Stack  (top---->bottom:)
80 
60 
40 
20 

Stack  (top---->bottom:)
40 
20 



Stack Implemented by a Linked List in core-java example

Stack implementation by a Linked List:


/**
 * @author Abhinaw.Tripathi
 *
 */
class Link
{

 public long dData;
 public Link next;

 public Link(long dd)
 {
dData=dd;
 }

 public void displayLink()
 {
 System.out.println(dData+ " ");
 }

}

class LinkList
{
private Link first;

public LinkList()
{
first=null;
}

public boolean isEmpty()
{
return (first==null);
}

public void insertFirst(long dd)
{
Link newLink=new Link(dd);
newLink.next=first;
first=newLink;
}

public Link deleteFirst()
{
Link temp=first;
first=first.next;
return temp;
}

public void displayList()
{
Link current=first;
while(current!=null)
{
current.displayLink();
current=current.next;
}
System.out.println(" ");
}

}

class LinkStack
{
 private LinkList theList;

 public LinkStack()
 {
theList=new LinkList();
 }

 public void push(long j)
 {
theList.insertFirst(j);
 }

 public Link pop()
 {
return (theList.deleteFirst());
 }

 public boolean isEmpty()
 {
return (theList.isEmpty());
 }

 public void displayStack()
 {
System.out.println("Stack  (top---->bottom:)");
theList.displayList();
 }

}



public class LinkStackApp
{
public static void main(String[] args)
{
LinkStack theStack=new LinkStack();
theStack.push(20);
theStack.push(40);

theStack.displayStack();

theStack.push(60);
theStack.push(80);
        theStack.displayStack();
     
        theStack.pop();
        theStack.pop();
     
        theStack.displayStack();
}


}

The desire output will be 

Stack  (top---->bottom:)
40 
20 
Stack  (top---->bottom:)
80 
60 
40 
20 
Stack  (top---->bottom:)
40 
20 


Sorted Link List example in core-java

Sorted Linked List:

/**
 * @author Abhinaw.Tripathi
 *
 */
class Link
{
 public long dData;
 public Link next;

 public Link(long dd)
 {
dData=dd;
 }

 public void displayLink()
 {
 System.out.println(dData+ " ");
 }
}

class SortedList
{
private Link first;

public SortedList()
{
first=null;
}
public boolean isEmpty()
{
return (first == null);
}

public void insert(long key)
{
Link newLink=new Link(key);
Link prev=null;
Link current=first;

while(current!=null && key > current.dData)
{
prev=current;
current=current.next;

}
if(prev==null)
first=newLink;
else
prev.next=current;
}

public Link remove()
{
Link temp=first;
first=first.next;
return temp;
}

public void displayList()
{
System.out.println("List (first to last-----> ):");
Link current=first;
while(current!=null)
{
current.displayLink();
current=current.next;
}
System.out.println(" ");
}

}
public class SortedLinkedListApp {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

SortedList thesortedList=new SortedList();
thesortedList.insert(20);
thesortedList.insert(40);
thesortedList.displayList();
thesortedList.insert(30);
thesortedList.insert(50);
thesortedList.displayList();
thesortedList.remove();
thesortedList.displayList();
}


}

Wednesday, June 8, 2016

Double-Ended Lists in core-java

Double-Ended List

A double-ended lists is similar to an ordinary linked list but it has one additional feature that a reference to the last link as well as the first.
The reference to the last link permits you to insert a new link directly at the end of the list as well as at the beginning.

Demonstration on Double-Ended Linked List:

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
class Link
{
 public long dData;
 public Link next;

 public Link(long d)
 {
this.dData=d;
 }

 public void displayLink()
 {
 System.out.println(dData+ " ");
 }

}

class FirstLastList
{
private Link first;
private Link last;

public FirstLastList()
{
first=null;
last=null;
}

public boolean isEmpty()
{
return first== null;
}

public void insertFirst(long dd)
{
Link newLink=new Link(dd);
if(isEmpty())
first=newLink;

else
last=newLink;
last=newLink;
}


public void insertLast(long dd)
{
Link newLink=new Link(dd);
if(isEmpty())
first=newLink;
else
last.next =newLink;
last=newLink;
}

public long deleteFirst()
{
long temp=first.dData;
if(first.next == null)
last=null;
first=first.next;

return temp;
}

public void displayList()
{
 System.out.println("First----->Last : ");
 Link current=first;
 while(current!=null)
 {
 current.displayLink();
 current=current.next;
 }
 System.out.println(" ");
}

}

public class DoubleEndedTestApp {

public static void main(String[] args) {

FirstLastList theList=new FirstLastList();
theList.insertFirst(22);
theList.insertFirst(44);
theList.insertFirst(66);
theList.insertLast(11);
theList.insertLast(33);

theList.displayList();
theList.deleteFirst();
theList.displayList();
}


}