Data Structure and Algorithms
Data Structure and 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.
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?
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.
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
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.
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.
16.what is an array?
18.remove even integers from an array see the =vs code array 3
22.moving all the zeroes at the end of the array-vs code array-8
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.
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
ListNode current=head;
While(current!=null)
{
System.out.println(current.data+””);
Current=current.next;
}
System.out.println(“null”);
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
30.how to insert the node at the end of a singly Linked List in java? See vs code
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;
}
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;
}
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.
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.
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();
}
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;
}
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);
}
}
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);
}
}
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++;
}
}
}
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;
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
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;
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.
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.