0% found this document useful (0 votes)
7 views53 pages

Data Structure and Algorithms

The document provides an overview of data structures and algorithms, defining key concepts such as data structures, algorithms, and their analysis. It categorizes data structures into linear and non-linear types, explains time and space complexity, and discusses asymptotic analysis and notations. Additionally, it includes practical examples and Java code snippets for implementing various data structures like arrays and linked lists.

Uploaded by

Ashlesha Karande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views53 pages

Data Structure and Algorithms

The document provides an overview of data structures and algorithms, defining key concepts such as data structures, algorithms, and their analysis. It categorizes data structures into linear and non-linear types, explains time and space complexity, and discusses asymptotic analysis and notations. Additionally, it includes practical examples and Java code snippets for implementing various data structures like arrays and linked lists.

Uploaded by

Ashlesha Karande
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Data Structure and Algorithms

1.what is the Data Structure?

 Data structure is the way to organize data.


 After organizing data it becomes easy to process it.
 For example
Let’s say if you go to a library and finds unorganized books now if someone ask you
Find algorithms and data structure book.It is very difficult to find the book and it takes the lots of
time.

2.Types of the data Structure-

There are the two types of data structure-

 Linear data Structure-


 In Linear data structure structure data stored in sequential,Linear Manner.
 Examples-Array,Linked List,Stack,Queue

 Non-Linear Data structure


 In Non-Linear Data structure data stored in Non-Linear manner.
 For exapmpe-Tree and graph

3.what is the algorithms?

 An algorithms is the set of instructuction to perform the task or to solve a given problem.
 For example-A recipe book is a collection of recipes in which each recipe provides an step by
step instructions to prepare food.
 Lets say you want to prepare a tea.so,the steps would be-
1.Boil Water
2.put tea in tea pot.
3.Add hot water.
4.put hot tea into tea cups.
5.do you need sugar?
1.if yes,put it into tea cups
2.if no,do nothing.
6.stir,drink,and enjoy the tea.

4.what is the Analysis of Algorithms?

 Analysis of Algorithms deals in finding best Algorithms which runs fast and takes in less memory.
 Analysis of algorithm can be done using time complexity and space complexity.
5.What is the time complexity?

 Time complexity is the amount of time taken by algorithms to run.


 The input processed by an algorithm helps in determining the time complexity.

6.what is the space complexity?

 Its amount of memory or space taken by algorithms to run.


 The memory required to process the input by an algorithm helps in determining the space
complexity.

7. what is the Asymptotic Analysis?

 Asymptotic analysis helps in evaluating performance of an algorithms in terms of input size and
its increases.
 Using asymptotic analysis we don’t’ measure actual running time of algorithms.
 It helps in determining how time and space taken by algorithm increases with input size.

8.what is the Asymptotic Notations?

 Asymptotic Notations are the mathematical tools used to describe the running time of an
algorithm in terms of input size.
 Example-performance of car in 1 litre of petrol
 HighWay(min traffic)-25 km/litre.
 City(max traffic)-15 km/litre.
 City+Highway(avg traffic)-20 km/litre.
 Asymptotic Notations help us in determining-
 Best case
 Average case
 Worst case

9.what are the types of the asymptotic Notations?

 There are three notations for performing runtime analysis of an algorithms-


1.Omega Notation
2.Big O Notation
3.Theta Notation

10. what is the Omega Notation?(best case)

 It is the formal way to express the lower bound of an algorithms running time.
 Lower bound means for any given input this notation determines best amount of time an
algorithm can take to complete.
 For example-
If we say certain algorithm takes 100 secs as best amount of time.so,100 secs will be lower
bound of that algorithm.The algorithm can take more than 100 sec but it will not take less than
100 sec.

11.what is the Big O Notation?


 It is the formal way to express the upper bound of an algorithms running time.
 Upper bound means for any given input this notation determines longest amount of time an
algorithm can take to complete.
 For example-
If we say certain algorithm takes 100 secs as longest amount of time.so,100 secs will be upper
bound of that algorithm.The algorithm can take less than 100 sec but it will not take more than
100 sec.
 Provides the worst case time

12.what is the theta notation?(average case)

 It is the formal way to express both the upper and lower bound of an algorithm’s running time.
 By Lower and Upper bound means for any given input this notation determines average
amount of time an algorithm can take to complete.
For example-
 If we run certain algorithm and it takes 100 sec for first run,120 secs for second run,110 for third
run and so on. So,theta notations gives an average of running time of that algorithms.

13.Rules of the Big O Notations-

 It’s a single processor


 It performs sequential execution of statements.
 Assignment operator,return statement,arithmetical operation,logical operation ,other small
operations takes 1 unit of time.
 Drop lower order term
 Drop constant multipliers.

14.calculating the time complexity of linear Algorithms-

 Time complexity will be O(n).

15.calculating the time complexity of the polynomial algorithms?

 Time complexity of the the polynomial terms are the O(n^2).

16.what is an array?

 Array is the collection of the similar data types.


 All data holding partitions have contiguous memory locations.
 Each partitions has two neighbors except first and last.
 Size of array is fixed and cannot be modified once it is created.
 Being adjacent each partition is indexed and can be determined by its position.
 Index starts at 0 and for ends at (length-1).

17.real world example of the Array-


1.Photo Gallery Apps
 Usage: Arrays store the list of image file paths or image objects.
 Example: An array might hold the file paths to all the images in a user's photo gallery. When the
app loads, it can iterate through the array to display the images.

2. Music Player Apps


 Usage: Arrays store playlists, songs, or albums.
 Example: An array might contain a list of song objects, where each object holds information like
the song's title, artist, and file path. This array is used to play songs sequentially or randomly.

3. Contact List Apps


 Usage: Arrays store contacts.
 Example: An array of contact objects, each containing a name, phone number, and email
address.

18.remove even integers from an array see the =vs code array 3

19.how to reverse an array in java-vs code array-4

20.find the mimimum value in an array-vs code array-5

21.find second maximum value in an array-vs code array-7

22.moving all the zeroes at the end of the array-vs code array-8

23.how to resize array in java-vs code array9

24.find the missing number in an array array-10

 Mathematical approach can be used finding the missing number in given array.
 The sum of first n natural numbers-1+2+3+4……+n=n*(n+1)/2.

25.how to check the given string is palindrome or not.

 we using the two pointer approach.

26.what is the singlyLinked list?

 A singly linked list is a data structure that consists of a sequence of nodes, where each node
contains some data and a reference (or link) to the next node in the sequence.
 The first node is called the head, and the last node's next reference points to null, indicating the
end of the list.

27.what is the real world use cases o f the singly linked list?
Undo/Redo Functionality-Manymobile applications, such as text editors and image editors,
implement undo and redo features using linked lists. Each action is stored as a node.

Operating System Kernels:Mobile operating systems often use linked lists in their kernels to
manage process scheduling

26-how to create singly linked list in java? See vscode singly1

 head = new ListNode(10);


ListNode second=new ListNode(1);
ListNode third=new ListNode(8);
ListNode fourth=new ListNode(11);
head.next=second;
second.next=third;
third.next=fourth;

27.how to print the elements in singly Linked List?

 ListNode current=head;
While(current!=null)
{
System.out.println(current.data+””);
Current=current.next;
}
System.out.println(“null”);

28.how to find length of a singly linked List in java- vs code singly2

 int count=0;
ListNode current=head;
While(current!=null)
{
count++;
current=current.next;
}
Return count;

29.how to insert node at the beginning of the singly linked List in java- see vs code

 ListNode newNode=new ListNode(value);


newNode.next=head;
head=newNode;

30.how to insert the node at the end of a singly Linked List in java? See vs code

 ListNode newNode=new ListNode(value);


If(head==null)
Head=newNode;
Return;
}
ListNode current=head;
While(null!=current.next)
{
Current=current.next;
}
Current.next=newNode;

31.insert a node in a singly Linked List at a given position? See vs code

 ListNode node=new ListNode(data);


If(position==1)
{
Node.next=head;
Head=node;
}
Else if
{
ListNode previous=head;
Int count=1;
While(count<position-1)
{
Previous=previous.next;
Count++;
}
Listnode current= previous.next;
Node.next=current;
Previous.next=node;
}

32.how to delete first node of a singly Linked List? See vs code

 Public Listnode deleteFirst(){


If(head==null)
{
Return null;
}
Head=head.next;
Temp.next=null;
Return temp;
}

33.how to delete last node of a singly Linked List? See vs code

 Public ListNode deleteLast()


{
If(head==null||head.next==null)
{
Return head;
}
Listnode current=head;
Listnode previous=null;
While(current.next!=null)
{
Previous=current;
Current=current.next;
}
Previous.next=null;
Return current;
}
34.Delete a node from a singly Linked List at a given position- see vs code
 If(position==1){
Head=head.next;
}
Else{
ListNode previous=head;
Int count=1;
While(count<position-1)
{
Previous=previous.next;
Count++;
}
Listnode current=previous.next;
Previous.next=current.next;
}
35.how to search elements in singly Linked list in java?
 See the vs code- codes
 Listnode current=head;
While(current!=null)
{
If(current.data=searchkey)
{
Return true;
}
Current=current.next;
}
Return false;
}
36.how to reverse singly linked list in java? Vs code
 ListNode current=head;
ListNode previous=null;
ListNode next=null;
While(current!=null)
{
Next=current.next;
Current.next=previous;
Previous=current;
Current=next;
}
Head=previous;

37.find the nth node of end of the Linked List?


 ListNode mainptr=head;
ListNode refptr=head;
Int count=0;
While(count<n)
{
refPtr=refptr.next;
count++;
}
While(refptr!=null)
{
Refptr=refptr.next;
Mainptr=mainptr.next;
}
Return mainptr;

38.How to remove duplicates from sorted Linked List in java?


 ListNode current=head;
While(current !=null && current.next!=null)
{
If(current.data==current.next.data){
Current.next=current.next.next;
}
Else
{
Current=current.next;
}
}

39.how to insert a node in a sorted singly Linked List in java?


 ListNode current=head;
ListNode temp=null;
While(current !=null && current.data<newnode.data)
{
Temp=current;
Current=current.next;
}
Newnode next=current;
Temp.next=newnode;
Return head;
}

40.How to remove a given key from singly linked List in java vs code.
 ListNode current=head;
Listnode temp=null;
While(current!=null && current.data!=key)
{
Temp=current;
Current=current.next;
}
If(current==null)
{
Return
}
Temp.next=current.next;
}

41.how to detect loop in a linked list in java?vs code singly10


 Listnode fastptr=head;
Listnode slowptr=head;
While(fastptr!=null && fastptrnext!=null)
{
Fastptr=fastptr.next.next;
Slowptr=slowptr.next;
If(slowptr==fastptr){
Return true;
}
}
Return false;

42.how to find start of loop in a singly Linked List? We are using thr floyds cycle detection algorithms
 Listnode fastptr=head;
Listnode slowptr=head;
While(fastptr!=null && fastptrnext!=null)
{
Fastptr=fastptr.next.next;
Slowptr=slowptr.next;
If(slowptr==fastptr){
Return getStartingNode(slowptr);
}
Return null;
}

 Public ListNode getStartingNode(ListNode slowptr)


{
ListNode temp=head;
While(slowptr!=null)
{
Temp=temp.next;
Slowptr=slowptr.next;
}
Return temp;
}
43.How to remove loop from a singly Linked List in java-
 Listnode fastptr=head;
Listnode slowptr=head;
While(fastptr!=null && fastptrnext!=null)
{
Fastptr=fastptr.next.next;
Slowptr=slowptr.next;
If(slowptr==fastptr){
remove(slowptr);
Return;
}
}
 Public void removeLoop(ListNode slowptr)
{
ListNode temp=head;
While(slowptr.next!=temp.next)
{
Temp=temp.next;
Slowptr=slowptr.next;
}
Slowptr.next=null;
}

44.Merge Two sorted singly Linked Lists-


 ListNode merge(ListNode a,ListNode b)
{
ListNode dummy=new ListNode(0);
ListNode tail=dummy;
While(a!=null && b!=null)
{
If(a.data<=b.data)
{
tail.next=a;
a=a.next;
}
Else
{
tail.next=b;
b=b.next;
}
Tail=tail.next;
}
If(a==null)
{
Tail.next=b;
}
Else
{
Tail.next=a;
}
Return dummy.next;
}
 Here we using the dummy List to avoid the null pointer exception.
45.how to add the two singly Linked List?(perform the addition)-
 First we cheking the digit is null or not in while loop.
ListNode add(ListNode a,ListNode b)
{
ListNode dummy=new ListNode(0);
ListNode tail=dummy;
Int carry=0;
While(a!=null || b!=null)
{
Int x=(a!=null)?a.value:0;
Int y=(b!=null)?b.value:0;
Int sum=carray+x+y;
Carray=sum/10;
Tail.next=new ListNode(sum%10);
Tail=tail.next;
If(a!=null)
{
A=a.next;
}
If(b!=null)
{
B=b.next;
}
If(carray>0)
{
Tail.next=new ListNode(carry);
}
Return dummy.next;
}

46.How to represent Doubly Linked List in java?


 It is called two way linked list.
 Doubly Linked List is the one type of linked List in which node containing the data,address of the
next pointer and previous pointer.
 Given a node ,we can navigate list in both forword and backward direction,which is not possible
in singly Linked List.
47.implementation of the Doubly Linked List-
 Public class ListNode{
Int data;
ListNode previous;
ListNode next;

Public ListNode(int data)


{
This.data=data;
}
}
48.How to implement doubly Linked List in java?
 Public class DoublyLinkedList{
Private ListNode head;
Private ListNode tail;
Private int length;

Private class ListNode{


Private int data;
Private ListNode next;
Private ListNode previous;

Public ListNode(int data)


{
This.data=data;
}
}
Public doublyLinkedList()
{
This.head=null;
This.tail=null;
This.length=0;
}
49.how to print the elements in doubly Linked List in java?
 For forword direction
 ListNode temp=head;
While(temp!=null)
{
System.out.println(temp.data+””);
Temp=temp.next;
}
System.out.print(“null”);
}

 For backword direction algorithm


 ListNode temp=tail;
While(temp!=null)
{
System.out.println(temp.data+””);
Temp=temp.previous;
}
System.out.println(“null”);
}

50.how to insert node at the beginning of a doubly Linked List in java-


 ListNode newNode=new ListNode(value);
If(isEmpty()){
Tail=newNode;
}
Else
{
Head.previous=newNode;
}
Tail.next=head;
Head=newNode;
}

51.How to insert node at the end of the the linked list;


 ListNode newNode=new ListNode(value);
If(isEmpty()){
head=newNode;
}
Else
{
Tail.next=newNode;
Newnode.previous=tail;
}
Tail=newNode;
}

52.How to delete first node in a doubly Linked List in java-


 If(isEmpty())
{
Throw new NoSuchElementException
}
ListNode temp=head;
If(head==tail)
{
Tail=null;
}
Else
{
Head.next.previous=null;
}
Head=head.next;
Temp.next=null;
Return temp;
}

53.How to delete last node in a doubly Linked list in java-


 If(isEmpty(){
Throw new NoSuchElementException();
}
ListNode temp=tail;
If(head==tail)
{
Head=null;
}
Else
{
Tail.previous.next=null;
}
Tail=tail.previous;
Temp.previous=null;
Return temp;
}

54.what is the circular Singly Linked List?


 It is similar to the singly Linked List,with a difference that in circular Linked List the last node
points to first node and not null.
 Instead of head,we keep track of last node in circular singly List.
55.how to implement circular Linked List in java?
 See the vs code
56.How to traverse and print a circular singly Linked List in java?
 If(last==null)
{
Return;
}
ListNode first=last.next;
While(first!=last)
{
System.out.println(first.data+””);
First=first.next;
}
System.out.println(first.data+””);

57.how to insert node at the beginning of a circular singly Linked List in java.
 ListNode temp=new ListNode(data);
If(last==null)
{
Last=temp;
}
Else
{
Temp.next=last.next;
}
Last.next=temp;
Length++;

58.how to insert node at the end of a circular Singly Linked List in java?
 ListNode temp=new ListNode(data);
If(last==null)
{
Last=temp;
Last.next=last;
}
Else
{
Temp.next=last.next;
Last.next=temp;
Last=temp;
}
Length++;

59.How to remove first node from a circular singly Linked List in java?
 if(isEmpty())
{
Throw new NoSuchElementException();
}
ListNode temp=last.next;
If(last.next==last)
{
Last=null;
}
Else
{
Last.next=temp.next;
}
Temp.next=null;
Length--;
Return temp;
}
60.what is the stack?
 In Java, a Stack is a data structure that follows the Last In, First Out (LIFO) principle. This means
that the last element added to the stack is the first one to be removed. Think of it like a stack of
plates; you add new plates to the top and take plates off the top.
 It is the linear data structure used for storing the data.

61.what is the real world use cases of the stack?

Browser History Management:

 Web Browsers: Browsers use a stack to keep track of the pages visited in the current
session. The back button pops the current page from the stack and returns to the previous
one.

Expression Evaluation and Syntax Parsing:

 Compilers: Compilers use stacks for parsing expressions, evaluating arithmetic


expressions, and managing operator precedence.

62.how to implement stack in java push operation?


 Private ListNode top;
Private int length;

Public void push(int data)


{
ListNode temp=new ListNode(data);
Temp.next=top;
Top=temp;
Length++;
}

63.implementing the pop operation in the stack?


 Private ListNode top;
Private int length;

Public int pop()


{
Int result=top.data;
Top=top.next;
Length--;
Return result;
}

64.implementing the stack using the Array-see vs code


65.How to reverse a string using a stack in java?
 Stack<Character>stack=new Stack<>();
Char[] chars=str.toCharArray();
For(char c:chars)
{
Stack.push(c);
}

For(int i=0;i<str.length;i++)
{
Chars[i]=stack.pop();
}
Return new string(chars);
66.next greater element
 Int[] nextGreaterElement[int[] arr)
{
Int[] result=new int[arr.length];
Stack<Integer>stack=new Stack<>();
For(int i=arr.length-1;i>=0;i--)
{
If(!stack.isEmpty()){
While(!stack.isEmpty() && stack.peek()<=arr[i]){
Stack.pop()
}
If(stack.isEmpty()){
Result[i]=-1;
}
Else
{
Result[i]=stack.peek();
}
Stack.push(arr[i]);
}
Return result;
}

67.valid parentheses-
 Boolean isvalid(String s)
{
Stack<character>stack=new Stack<>();
For(char c:s.toCharArray())
{
If(c==’(‘ ||c==’{‘||c==’[‘)
{
Stack.push(c);
}
Else
{
If(stack.isEmpty()){
Return false;
}
Else
{
Char top=stack.peek();
If(c==’)’ && top==’(‘)||(c==’}’ &&top==’{‘)||(c==’]’&&top==’[‘))
{
Stack.pop();
}
Else
{
Return false;
}
}
}
}
Return stack.isEmpty();
}

68.what is the queue?


 Queue is the one type of linear data structure .
 Queue is the ordered list in which insertion is done at the one end is called as rear and delection
is done at other end called as front.
 The first element is inserted is the first element which is removed.
 Hence it is called first in first out list.
69.how to implement queue in java?
 See vs code
70.how to insert element an element in a queue in java?(enqueue)-
 Public void enqueue(int data)
{
ListNode temp=new ListNode (data);
If(isEmpty())
{
Front=temp;
}
Else
{
Rear.next=temp;
}
Rear=temp;
Length++;
71.printing the elements in queue?
 If(isEmpty())
{
Return;
}
ListNode current=front;
While(current!=null)
{
System.out.println(current.data+”-”);
Current=current.next;
}
System.out.println(“null”);

72.How to remove an element in a queue in java?


 Public int dequeue()
{
If(isEmpty())
{
Throw new NoSuchElementException();
}
Int result=front.data;
Front=front.next;
If(front==null)
{
Rear=null;
}
Length--;
Return result;
}

73.generate binary numbers from 1 to n-


 String[] generateBinaryNumbers(int n)
{
String[] result =new String[n];
Queue<String>q=new LinkedList<>();
q.offer(“1”);
for(int i=0;i<n;i++)
{
Result[i]=q.poll();
String n1=result[i]+”0”;
String n2=result[i]+”1”;

q.offer(n1);
q.offer(n2);
}
Return result;
}

74.What is a Tree?
 Tree is a non-linear Data structure used for storing data.
 It is made up of nodes and edges without having any cycle.
 Each node in a tree can point to n numbers of nodes in a tree.
 It is a way of representing hierarchical structure with in parent node called as root.
75.what is the Binary tree?
 A tree is called as binary tree,if each node has zero,one or two children.
76.structure of the treeNode in a binary tree?
 Public class TreeNode{
Private int data;
Private TreeNode left;
Private TreeNode right;

Public TreeNode(int data)


{
This.data=data;
}
}
77.recursive pre-order traversal of a binary tree in java-
 Visit the root node.
 Traverse the left subtree in preorder fashion.
 Traverse the right subtree in preorder fashion.
Implementation-
Public void preorder(TreeNode root)
{
If (root==null)
{
Return;
}
System.out.println(root.data+” ”);
Preorder(root.left);
Preorder(root.right);

}
78.iterative pre-order traversal of a binary tree in java?
 If(root==null)
{
Return;
}
Stack<TreeNode>stack=new Stack<>();
Stack.push(root);
While(!stack.isEmpty())
{
TreeNode temp=stack.pop();
System.out.println(temp.data);
If(temp.right!=null)
{
Stack.push(temp.right);
}
If(temp.left!=null)
{
Stack.push(temp.left);
}
}

79.Recursive in-order traversal of a Binary tree in java?


 Traverse the left subtree in order fashion.
 Visit the root node
 Traverse the right subtree in order fashion.
80.implemetation of the code in-order-traversal
 Public void in-order(TreeNode root)
 {
 If (root==null)
 {
 Return;
 }
 inorder(root.left);
 System.out.println(root.data+” ”);
 inorder(root.right);
 }
81. iterative approach in-order traversal of a binary tree in java?
 If(root==null)
{
Return;
}
Stack<TreeNode>Stack=new Stack<>();
TreeNode temp=root;
While(!stack.isEmpty()||temp!=null)
{
If(temp!=null)
{
Stack.push(temp);
Temp=temp.left;
}
Else
{
Temp=stack.pop();
System.out.println(temp.data+” “);
Temp=temp.right;
}
}
82. Recursive in-order traversal of a Binary tree in java?
 Traverse the left subtree in order fashion.
 Traverse the right subtree in order fashion.
 Visit the root node
83.implementation of the post-order traversal-
 public void post_order(TreeNode root)
 {
 if(root==null)
 {
 return;
 }

 post_order(root.left);
 post_order(root.right);
 System.out.println(root.data+" ");

 }
84. implementation of the post-order traversal using iterative approach
 If(root==null)
{
Return;
}
Stack<TreeNode>Stack=new Stack<>();
TreeNode current=root;
While(!stack.isEmpty()||current!=null)
{
If(current!=null)
{
Stack.push(current);
current=current.left;
}
Else
{
TreeNode temp=stack.peek().right;
If(temp==null)
{
Temp=stack.poll();
System.out.println(temp.data+” ”);
While(!stack.isEmpty() && temp==stack.peek().right)
{
Temp=stack.poll();
System.out.println(temp.data+” ”);
}
Else
{
Current=temp;}
}
}
85.Level order traversal of a Binary tree in java?
 If(root==null)
 {
 Return;
 }
 Queue<TreeNode> queue=new LinkedList<>();
 Queue.offer(root);
 While(!queue.isEmpty())
 {
 TreeNode temp=queue.poll();
 System.out.println(temp.data+” “);
 {
 If(temp.left!=null)
 {
 Queue.offer(temp.left);
 }
 If(temp.right!=null)
 {
 Queue.offer(temp.right);
 }
 }
86.find maximum value in a binary tree?
 Public int maximum(TreeNode root)
{
If(root==null)
{
Return Integer.MIN_VALUE;
}
Int result=root.data;
Int left=maximum(root.left);
Int right=maximum(root.right);
If(left>result)
{
Result=left;
}
If(right>result)
{
Result=right;
}
Return result;
}
}
87.How to represent a Binary search tree in java?
 It is type of Binary tree in which data is organized in orderd manner which helps in
faster seach and insertion of data.
 It satisfies following properties-
1.The left subtree of a node contains only nodes with values lesser than the node’s
value.
2. The right subtree of a node contains only nodes with values greater than the node’s
value;
3.The left and right subtree must be a binary search tree.

88.How to insert a value in a binary search tree in java(Recursive approach)


 Public TreeNode insert(TreeNode root,int value)
{
If(root==null)
{
Root=new TreeNode(value);
}
If(value<root.data)
{
Root.left=insert(root.left,value);
}
Else
{
Root.right=insert(root.right,value);
}

Return root;
}
89.How to search a given key in Binary search tree(Recursive approach)
 Public TreeNode search(TreeNode root,int key)
{
If(root==null||root.data==key)
{
Return root;
}
If(key<root.data)
{
Return search(root.left,key);
}
Else
{
Return search(root.right,key);
}
}

90.validate Binary Search Tree?


 Boolean isvalid(TreeNode root,long min,long max)
{
If(root==null)
{
Return true;
}
If(root.value<=min||root.value>=max)
{
Return false;
}

Boolean left=isvalid(root.left,min,root.value);
If(left)
{

Boolean right=isvalid(root.left,min,root.value);
Return right;
}
Return false;
}
91.search in a row and column wise sorted matrix?
 Public void search(int[][] matrix,int n,int X)
{
Int i=0;
Int j=n-1;
While(i<=n && j>=0)
{
If(matrix[i][j]==x)
{
System.out.println(“X found at”+i+” ,”+j);
Return;
}
If(matrix[i][j]>x)
{
j--;
}
Else
{
I++;
}
}
System.out.println(“Not Found”);
}
92.print a given matrix in spiral form?
 Here we are using the four for loops.
 First for loop for =left->right
 Second for loop for=top->bottom
 Third for loop for=right->left
 Fourth for loop for=botton->top
Void spiralPrint(int[][] matrix,int r,int c)
{
Int i,k=0,l=0;
While(k<r && l<c)
{
For(i=l;i<c;i++)
{
s.o.p(matrix[k][i]+””);
}
K++;
For(i=k;i<r;i++)
{
s.o.p(matrix[i][c-1]+” “);
}
c--;
if(k<r)
{
For(i=c-1;i>=l;i--)
{
s.o.p(matrix[r-1][i]+””);
}
r--;
}
if(l<c)
{
For(i=r-1;i>=k;i--)
{
s.o.p(matrix[i][l]+””);
}
l++;
}
}
}

93. what is the priority queue?


 Priority queue is a data structure that allows us to finds minimum/maximum element
among a collection of elements in constant time.it supports following operations-
1.insert(key)-insert a key into the priority queue.
2.deleteMax()/deleteMin()-return and remove largest/smallest key.
3.getMax()/getMin()-return largest/smallest key

94.what is the binary heap?


 The binary heap is a data structure that helps us to implementing the priority queue
operations efficiently.
 A binary heap is a complete binary tree in which each node valueis >= or<= the value of
its childrens.
 Two types-
Min heap
 Max heap.
95.what is Complete Binary tree-
 A complete binary tree is a binary tree where all levels are completely filled except last
level and last level has nodes in such a way that left side is never empty.
96.how to represent the binary heap in java?
 Binary heap usually implemented using arrays.
 The first entry of array taken as empty.
 As binary heaps are complete binary tree,the values are stored in array by traversing
tree level by level from left to right.
97. formula of the children of kth index=2*K,2*k+1;
98.formula of the kth index=k/2.
99.How to implement the max heap in java?
 A max heap is a complete binary tree in which each node value is >=than the values of
its children.
 The maximum value is at top which is root of complete binary tree.
 For its array representation its at index 1 .heap[1].
100.implementation of the max heap algorithms-
 Public class MaxPQ{
Integer[] heap;
Int n;
Public maxPQ(int capacity)
{
Heap=new Integer[capacity+1];
N=0;
}
public Boolean isEmpty()
{
Return n==0;
}
Public int size()
{
Return n;
}
Public static void main(String[] args)
{
MaxPQ pq=new MaxPQ(3);
System.out.println(pq.size());
System.out.print(pq.isEmpty());
101.Bottom-up reheapify in max heap-
 We adjusting the locations of the nodes in binary heap(max heap)
102.how to insert maxheap in java?
 Public void insert(int x){
If(n==heap.length-1)
{
Resize(2*heap.length);
}
N++;
Heap[n]=x;
Swim(n);
}
Private void swim(int k)
{
while(k>1 && heap[k/2]<heap[k])
{
Int temp=heap[k];
Heap[k]=heap[k/2];
Heap[k/2]=temp;
K=k/2;
}
}

103.Top-down reheapify(sink) in max Heap-


 DeleteMax();
 DeleteMin();
104.how to delete maximum elements in a Max Heap-
 Public int deleteMax()
{
Int max=heap[1];
n--;
sink(1);
heap[n+1]=null;
if(n>0 &&(n==(heap.length-1)/4))
{
Resize(heap.length/2);
}
Return max;
}

 Private void sink(int k)


{
While(2*k<=n)
{
Int j=2*k;
If(j<n&& heap[j]<heap[j+1];
{
J++;
}
If(heap[k]>=heap[j])
{
Break;
}
Swap(k,j);
K=j;
}
}

 Public void swap(int a,int b)


{
Int temp=heap[a];
Heap[a]=heap[b];
Heap[b]=temp;
}

105.Linear search algorithms in java?


 Public int search(int[] arr,int n,int x)
{
For(int i=0;i<n;i++)
{
If(arr[i]==x)
{
Return i;
}
Return -1;
}

106.Binary search in java?


 Binary search algorithms are the divide and conquere algorithm.
 Int low=0;
Int high=nums.length-1;
While(low<=high)
{
Int mid=(high+low)/2;
If(nums[mid]==key)
Return mid;
If(key<nums[mid]
{
High=mid-1;
}
Else
{
Low=mid+1;
}
}
Return -1;
}

107.search insert position-


 Int low=0;
Int high=nums.length-1;
While(low<=high)
{
Int mid=low+(high-low)/2;
If(nums[mid]==key)
Return mid;
If(target<nums[mid]
{
High=mid-1;
}
Else
{
Low=mid+1;
}
}
Return low;
}
108.what is the bubble sort?
 It is also called as sinking sort.
 While applying this sorting algorithm on unsorted array,largest element placed at the
end of the array.
 It repedetly compares the pair of adjacent elements and swap them if they are in wrong
order.
109.implementation of the bubble sort see in vscode
 Outer for loop keeping track of each iteration
 Inner for loop comparing the pair of adjacent elements.
Boolean is swapped;
For(int i=0;i<n-1;i++)
{
Isswapped=false;
For(int j=0;j<n-1-I;j++)
{
If(arr[j]>arr[j+1])
{
Int temp=arr[j];
Arr[j]=arr[j+1];
Arr[j+1]=temp;
Isswapped=true;
}
}
If(isswapped==false)
Break;
}
}

110.insertion sort in java-


 Insertion sort is a simplest sorting algorithm that works the way we sorts playing cards
in our hands.
 It divides the array in two parts sorted part and unsorted part.
 It picking the elements from unsored array and placing it at correct position in sorted
part.
111.implementation of the insertion sort-
 For(int i=1;i<n;i++){
Int temp=arr[i];
Int j=i-1;
While(j>=0 && arr[j]>temp)
{
Arr[j+1]=arr[j];
J=j-1;
}
Arr[j+1]=temp;
}

112.selection sort in java?


 In selection sort we divide the array into two parts-sorted parts and unsorted parts.
 In selection sort we picking the minimum element from unsorted array and placing it
correct position of the sorted array.
113.implementation of the selection sort-
 Public void sort(int[] arr)
{
Int n=arr.length;
For(int i=0;i<n-1;i++)
{
Int min=i;
For(int j=i+1;j<n;j++)
{
If(arr[j]<arr[min]
{
Min=j;
}
}
Int temp=arr[min];
Arr[min]=arr[i];
Arr[i]=temp;
}
}

114. merge two sorted arrays in java? See the vs code-


115.what is the merge sort in java?
 Merge sort is a divide and conquer algorithm.
 Divide and conquer recursively breaks down a problem into two or more sub-problems
of the same or related type,until these becomes simple to be solved.the solution to the
sub-problems are combined to a give a solution to the original problem.
116.implementation of the merge sort-
 Void sort(int[] arr,int[] temp,int low,int high)
{
If(low<high)
{
Int mid=low +(high-low)/2;
Sort(arr,temp,low,mid);
Sort(arr,temp,mid+1,high);
Merge(arr,temp,low,mid,high);
}
}
 Void merge(int[] arr,int[] temp,int low,int mid,int high)
{
For(int i=low;i<=high;i++)
{
Temp[i]=arr[i];
}
Int i=low;int j=mid+1;int k=low;
While(i<=mid && j<=high)
{
If(temp[i]<=temp[j])
{
Arr[k]=temp[i];
I++;
}
Else
{
Arr[k]=temp[j];
J++;
}
K++;
}
While(i<=mid)
{
Arr[k]=temp[i];
I++;
K++;
}
}

117.Sort an array of 0’s,1’s and 2’s


 Void threeNumberssort(int[] arr)
 {
Int i=0;
int j=0;
int k=arr.length-1;
while(i<=k)
{
If(arr[i]==0)
{
Swap(arr,i,j);
I++;
J++;
}
Else if(arr[i]==1)
{
I++;
}
Else if(arr[i]==2)
{
Swap(arr,I,k);
k--;
}
}
}
 Public void swap(int[] arr,int I,int j)
Int temp=arr[i];
Arr[i]=arr[j];
Arr[j]=temp;
118.what is the quick sort?
 Quick sort followes the divide and conquer strategy.
 It selects the element and mark as pivot .pivot may be the first,last and random
elements.
 The elements which are lesser of the pivot are shifted left side and larger of the
elements are the right side of the pivot.
 The elements are the equal to the pivot are either shifted to the right side or left side.
 Partitioning
 Recursion
119.implementation of the quick sort-
 int partition(int[] arr,int low,int high)
{
Int pivot=arr[high];
Int i=low;
Int j=low;
While(i<=high)
{
If(arr[i]<=pivot)
{
Int temp=arr[i];
Arr[i]=arr[j];
Arr[j]=temp;
J++;
}
I++;
}
Return j-1;
}
120-quick sort recursion-
 sort(int[] arr,int low,int high)
{
If(low<high)
{
Int p=partition(arr,low,high);
Sort(arr,low,p-1);
Sort(arr,p+1,high);
}
}

121.squares of a sorted Array in java?


 Public int[] sortedsquares(int[] arr)
{
Int n=arr.length;
Int[] result=new int[n];
Int i=0,j=n-1;
For(int k=n-1;k>=0;k--)
{
If(Math.abs(arr[i])>Math.abs(arr[j]))
{
Result[k]=arr[i]*arr[i];
I++;
}
Else
{
Result[k]=arr[j]*arr[j];
j--;
}
}
Return result;
}

122.Rearrange sorted array in max/min form-


 Void arrangemaxmin(int[] arr)
{
Int maxidx=arr.length-1;
Int minindex=0;
Int max=arr[maxidx]+1;
For(int i-0;i<arr.length;i++)
{
If(i%2==0)
{
Arr[i]=arr[i]+(arr[maxidx] % max)*max);
Maxidx--;
}
Else
{
Arr[i]=arr[i]+(arr[minidx] % max)*max);
Minidx++;
}
}
For(int i=0;i<arr.length;i++)
{
Arr[i]=arr[i]/max;
}
}
123.what is a Graph?
 It is non-linear data structure used for storing data.
 It is the set of vertices and collection of edges that connects a pair of vertices.

124.applications-social Networks
 Graphs help us implement social Networking sites such as facebook,twitter etc.
 It can be called as social networking graph.
 Names of people represents the vertices of graph.
 Friendship between two people can be represented as edge of the graph.
125.Adjacency matrix Representation(undirected graph)-
 Undirected graph is the one type of graph having no direction.
 Example-social Networking graph is an undirected graph.
 If john(vertex) is friend(edge) to ram,than ram(vertex) is also friend(edge) of john.
126.Adjacency Matrix implementation(undirected graph)-
 Public class graph{
Int[][] adjmatrix;

Public graph(int nodes)


{
This.adjMatrix=new int[nodes][nodes];
}

Public void addEdge(int u,int v)


{
This.adjmatrix[u][v]=1;
This.adjmatrix[v][u]=1;
}
Public static void main(String[] args)
{
Graph g=new Graph(4);
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(2,3);
g.addEdge(3,0);
}
127.Adjecency List Representation(undirected graph);
 Public class Graph
{
LinkedList<INTEGER>[] adj;

Public Graph(int nodes)


{
This.adj=new LinkedList[nodes];
For(int i=0;i<nodes;i++)
{
This.adj[i]=new LinkedList<>();
}
}
Public void addEdge(int u,int v)
{
This.adj[u].add(v);
This.adj[v].add(u);
}
Public static void main(String[] args)
{
Graph g=new Graph(4);
g.addEdge(0,1);
g.addEdge(1,2);
g.addEdge(2,3);
g.addEdge(3,0);
}
}
128.Breadth first search(undireced graph)
 Bfs is also known as the level by traversal.
 We traversing the nodes level by level.
 We using the queue data structure.
 Algorithms-
Public void bfs(int s)
{
Boolean[] visited=new Boolean[vertices];
Queue<Integer>q=new LinkedList<>();
Visited[s]=true;
q.offer(s);
while(!q.isEmpty())
{
Int u=q.poll();
System.out.println(u+” “);
For(int v:adj[u])
{
If(!visited[v])
{
Visited[v]=true;
q.offer(v);
}
}
}
}
129.Depth first search (undirected graph)
 public void dfs(int s)
 {
 boolean[] visited=new boolean[V];
 Stack<Integer> stack=new Stack<>();
 stack.push(s);
 while (!stack.isEmpty()) {
 int u=stack.pop();

 if(!visited[u])
 {
 visited[u]=true;
 System.out.println(u);
 }
 for(int v:adj[u])
 {
 if(!visited[v])
 {
 stack.push(v);
 }
 }

130.recursive depth first search(undirected graph)


 Public void dfs()
{
Boolean[] visited=new Boolean[V];
For(int v=0;v<V;v++)
{
If(!visited[v])
{
Dfs(v,visited);
}
}
}
Public void dfs(int v,Boolean[] visited)
{
Visited[v]=true;
System.out.println(v+” “);
For(int w:adj[v])
{
If(!visited[w])
{
Dfs(w,visited);
}
}
}
131. find the connected components(undirected graph)-
 Public void dfs()
{
Boolean[] visited=new Boolean[V];
Int count=0;
Int[] compId=new int[v];
For(int v=0;v<V;v++)
{
If(!visited[v])
{
Dfs(v,visited,compid,count);
Count++;
}
}
 Void dfs(int v,Boolean[] visited,int[] comid,int count)
{
Visited[v]=true;
Compid[v]=count;
For(int w:adj[v])
{
If(!visited[w])
{
Dfs(w,visited,compId,count);
}
}

132.number of islands
 Public int numislands(char[][]grid)
{
Int m=grid.length;
Int n=grid[0].length;
Boolean[][] visited=new Boolean[m][n];
Int numsoffilands=0;
For(int i=0;i<m;i++)
{
For(int j=0;j<n;j++)
{
If(!visited[i][j] &&grid[i][j]==’1’)
{
Dfs(grid,i,j,visited);
Numsofislands++;
}
}
}
Return numsofislands;
}
 Void dfs(char[][] grid,int row,int col,Boolean[][] visited)
{
If(row<0||col<0||row>=grid.length||col>=grid[0].length||visited[row][col]||grid[row]
[col]==’0’)
{
Return;
}
Visited[row][col]=true;
Dfs(grid,row,col-1,visited)//goes left
Dfs(grid,row-1,col,visited)//goes up
Dfs(grid,row,col+1,visited)//goes right
Dfs(grid,row+1,col,visited)//goes down
133.introduction to hashing?
 Hashing is a technique used for storing,retriving and removing information as quick as
possible.
 It’s a process of converting a arbitrary size key into fixed sized value.conversion is done
by the using hash functions.
 The operation supported by hashing such as storing,retriving,and removing information
have average runtime complexity of O(1).
134.what are hash function?
 A hash function simply takes an arbitry size key and provides fixed size value also called
as index.
135.Modular Hash Function?
 A modular hash function simply takes a key and size,returns remainder by dividing key
by size.
 The remainder is used as an index to store the key in an array of provided size.
136.Introduction to the Hash Table-
 It is a generalized form of an array.
 It stores the data in form of key-value pair.
 Primary operations supported by hashTable are-
1.put(key,value)-Add key-value pair against unique key.
2.get(key)-get value for the provided key.
3.remove(key)-remove the key-value pair from hashtable
 Average running time is O(1);
137.how to resolve collision in hash table(technique)-separate chaning
 When we encountering the collision we resolving the collision using separate chaning.
 We creating hash nodes -key,value,references to the next node.
138.how to represent hash Nodes.
 Hashnode class in hash table consists of a three data members
1.key-it is unique value which helps in storing data.
2.value.-it is the data based on location computed by key.
3.HashNode Next.-it takes references of the next hashnode in chain of hash nodes

139.how to implement the hashtable(separate chaining)-


 Public class HashTable{
Private HashNode[] buckets;
Private int numofBuckets;
Private int size;

Public hashTable(int capacity)


{
This.numsofbuckets=capacity;
Buckets=new HashNode[capacity];
}

Private class HashNode{


Private Integer key;
Private string value;
Private Hashnode next;

Public hashnode(Integer key,string value)


{
This.key=key;
This.value=value;
}
}

140.how to put key-value pair in a HashTable-(separate chaining)


 Following are the hash function-
Public int getBucketindex(Integer Key)
{
Return key % buckets.length;
}
 Public void put(Integer key,String value)
{
Int bucketindex=getBucketindex(key);
HashNode head=buckets[bucketindex];
While(head!=null)
{
If(head.key.equals(key))
{
Head.value=value;
Return;
}
Head=head.next;
}
Size++;
head=buckets[bucketindex];
hashNode node=new HashNode(key,value);
node.next=head;
buckets[bucketindex]=node;
}
}

141.how to get a value by key in a Hashtable-separate chaining-


 Public void put(Integer key,String value)
{
Int bucketindex=getBucketindex(key);
HashNode head=buckets[bucketindex];

While(head!=null)
{
If(head.key.equals(key))
{
Head.value=value;
}
Head=head.next;
}
Return null;
}
}
142.how to remove a key from hash table-
 Public String remove(Integer key)
Int bucketIndex=getindex(key);
HashNode head=buckets[bucketindex];
HashNode previous=null;
While(head!=null)
{
If(head.key.equals(key))
{
Break;
}
Previous=head;
Head=head.next;
}
If(head==null)
{
Return null;
}
Size--;
If(previous!=null)
{
Previous.next=head.next;
}
Else
{
buckets[bucketindex]=head.next;
}
Return head.value;
}
143.contains duplicate
 Public Boolean contains duplicate(int[] nums)
{
Set<Integer>set=new HashSet<>();
For(int i=0;i<nums.length;i++)
{
If(set.contains(nums[i]))
{
Return true;
}
Set.add(nums[i]);
}
Return false;
}
144.introduction to overlapping intervals-
 An interval is a range represented by two numbers like(5,8).
 The two numbers are termed as -start and end.
 Interval representation-
Public class interval
{
Private int start;
Private int end;

Public interval(int start,int end)


{
This.start=start;
This.end=end;
}
}

142.merge the two intervals-


 First we sorting the intervals based on the start time.(a.start<=b.start)
 Then applying the overlapping conditions.
 List<Interval> merge(List<Interval>intervals)
{
If(intervals.size()<2)
{
Return intervals;
}
Intervals.sort(comparingInt(in->in.start));
{
List<Interval> result=new LinkedList<>();
Interval first=intervals.get(0);
Int start=first.start;
Int end=first.end;
For(int i=1;i<intervals.size();i++)
{
Interval current=intervals.get(i);
If(current.start<=end)
{
End=Math.max(current.end,end);
}
Else
{
Result.add(new Interval(start,end));
Start=current.start;
End=current.end;
}
}
Result.add(new Interval(start,end));
Return result;
}
143.introduction to trie-
 The main purpose of the trie data structure is to retrive stored information very fast.
 Aplictaions-Auto-complete words
1.Auto-complete feature is implemented by tries.
2.many websites uses the autocomplete features,which suggests users rest of the
word,while user is typing.
 Appliacation 2-search contacts in phone
Searching a person contact number in contact list is efficiently implemented by trie.As
soon as user enters letters the application auto suggests the name of the person.
 Application 3-spell cheking
Tries help to check and correct word spelling entered by user.

144.how to represent a TrieNode in java?


 TrieNode in a trie represents a single alphabet of the word.
 In below example,in order to insert word “dog” 3 TrieNode are used,one for each
alphabets.
145.how to implement tries data structure in java? See vs code
146.how to insert a word into tries?
 Public void insert(String word)
{
TrieNode current=root;
For(int i=0;i<word.length();i++)
{
Char c=word.charAt(i);
Int index=c-‘a’;
If(current.children[index]==null)
{
TrieNode node=new TrieNode();
current.children[index]==node;
current=node;
}
Else
{
Current=current.children[index];
}
}
Current.isword=true;
}
147.what is the dyanamic programming?
 Dp is a method used in computer science and mathematics to solve the complex
problems by breking them down into simpler subproblems.
 Solving the each sub-problems only once and storing the results,it avoids redudunt
computations.
148.How Does Dynamic programming Work?
 Firstly we dividing the main problem into smaller subproblems.
 We solving the each sub problem and storing the solution in a table or array.
 We using the stored solution to build up the solution to the main problem.
 By stroring solutions,DP ensures that each subproblem is solved only once.
149. Examples of Dynamic Programming (DP)
Example 1: Consider the problem of finding the Fibonacci sequence:
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

Fibonacci Series using Dynamic Programming


 Subproblems: F(0), F(1), F(2), F(3), …
 Store Solutions: Create a table to store the values of F(n) as they are
calculated.
 Build Up Solutions: For F(n), look up F(n-1) and F(n-2) in the table and add
them.
 Avoid Redundancy: The table ensures that each subproblem (e.g., F(2)) is
solved only once.
150. When to Use Dynamic Programming (DP)?
Dynamic programming is an optimization technique used when solving problems that
consists of the following characteristics:
1. Optimal Substructure:
Optimal substructure means that we combine the optimal results of subproblems to
achieve the optimal result of the bigger problem.
2. Overlapping Subproblems:
The same subproblems are solved repeatedly in different parts of the problem.

151.Approaches of dynamic programming?

 1.Top-Down Approach(memorization)
 2.bottom-up approach(Tabulation).

152.Top-Down Approach-
 Start with the final solution and recursively breks down into smaller subproblems.
 Stores the solution to subproblems in a table.

153.bottom-up Approach(Tabulation):

 Start with the smallest subproblem and gradually builds up the final solution.
 Solution to the subproblem is filled into table.

154.common algorithms that uses Dynamic programming?

 Shortest path algorithms.-finding the shortest path between two nodes in a graph.
 Matrix chain multiplication-
 Knapsack problem.-determine the maximum value of items that can be placed in knapsack with a given
capacity.
 Fibonacci sequence.

155.Applications of the Dynamic programming?

 Dynamic programming can be used in shortest path problems,knapsack problems.


 It can be used in distance editing,string matching.
 It can be used in resource allocation,inventory management.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy