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

lab1

The document contains a series of programming tasks focused on array manipulation, searching algorithms, and sorting techniques, along with their respective implementations in Java. Each task includes questions about time complexity, loop execution counts, and efficiency of algorithms. The document also references external problems from LeetCode for additional practice and validation.

Uploaded by

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

lab1

The document contains a series of programming tasks focused on array manipulation, searching algorithms, and sorting techniques, along with their respective implementations in Java. Each task includes questions about time complexity, loop execution counts, and efficiency of algorithms. The document also references external problems from LeetCode for additional practice and validation.

Uploaded by

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

1. Write a program to find the smallest element of an unsorted array of size N.

Don’t
use any built-in functions/ methods like min() supported by certain programming
languages. a. How many times does your loop execute? b. As the elements in the
array changes (the size of the array remains same), will there be any change in the
number of times the loop executes? What is the minimum and maximum number of
times the loop executes? c. What is the time complexity of your program?

Ans:-
class Main {
public static void main(String[] args) {
int Array[]= {9,1,5,3,7,8,2};
int len=Array.length;
int smallest=Array[0];
for (int i=0;i<len-++i) {
if (Array[i]<=smallest) {
smallest=Array[i];
}
}
System.out.println("Smallest element is: "+smallest);
}
}

OUTPUT:-

Smallest element is: 1

a) There are 7 elements in my Array and the loop gets executed 7 times.
b) No, there won’t be any change in the number of times the loop is executed as
per this logic of mine.
Minimum :1
Maximum :n
c) The time complexity of this program is O(n).
2. Write a program to find the smallest and the largest element in a sorted array. a. Do
we need any loops in this program? b. What is the time complexity of your program?
Ans:-

class Main {
public static void main(String[] args) {
int Array[]= {1,2,3,4,5,6,7,8,9,10};
System.out.println("The smallest element of this sorted array is:
"+Array[0]);
System.out.println("The largest element of this sorted array is:
"+Array[Array.length-1]);
}

The smallest element of this sorted array is: 1


The largest element of this sorted array is: 10
a) No, we do not need any loops in this program.
b) Time complexity of this program is: O(1);
3. Write a program to search an element ‘k’ in an unsorted array of size N. a. As the
elements in the array changes (the size of the array remains same), will there be any
change in the number of times the loop executes? What is the minimum and
maximum number of times the loop executes? b. What is the time complexity of
your program?
Ans:-
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Array[]= {1,10,2,9,3,8,4,7,6,5};
System.out.println("Enter the target element: ");
int target = sc.nextInt();
int len=Array.length;
for (int i=0;i<len;++i){
if (Array[i]==target){
System.out.println("Target element found at
index: "+i);
break;
}
}
sc.close();
}
}

OUTPUT:-
Enter the target element:
10
Target element found at index: 1
a) No, As the number of elements changes the number of times the loop get
executed does not change.
Minimum: 1
Maximum: n
b) Time complexity of the given program is: O(n).
4. We need to search an element ‘k’ in a sorted array of size N. a. Will your program for
Qn. No 3 work for this case? b. Is the program for Qn. No 3 the most efficient one for
this? (Hint: There exists a Binary search algorithm) c. Write an iterative program to
implement Binary search. d. As the elements in the array changes (the size of the
array remains same), will there be any change in the number of times the loop
executes? What is the minimum and maximum number of times the loop executes?
e. What is the time complexity of your program?
Ans:-

A) Yes, the above program of Qn 3 will work here also.


B) No, the program for Qn 3 is not the most efficient way to solve this problem. We
can use the Binary Search Algorithm with lesser time complexity in this
scenario.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Array[]= {1,2,3,4,5,6,7,8,9,10};
System.out.println("Enter the target element: ");
int target = sc.nextInt();
int len=Array.length;
int low=0,high=len-1;
int mid=(low+high)/2;
while(low<=high){
if (Array[mid]==target){
System.out.println("The target element found
at index: "+mid);
break;
}else if (Array[mid]>target){
high=mid-1;
mid=(low+high)/2;
}else if (Array[mid]<target){
low=mid+1;
mid=(low+high)/2;
}
}
sc.close();
}
}

OUTPUT:-

Enter the target element:


10
The target element found at index: 9
C) If we change the elements in the sorted array of binary search, the number of
times the while loop executes depends on the target element to be searched. If
the changed array has the target element at mid position, it requires O(n) and in
other cases it could lead to a time complexity of O(log n).
D) The time complexity of a binary search program is: O(log n).
5. Write an efficient program to find an element in an array which neither the smallest
nor the largest. (Hint: you can do this without a loop.) a. What is the time complexity
of your program?
Ans:-
A)
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int Array[]= {1,5,6,7,2,8,3,9,4,10};
int len=Array.length;
Arrays.sort(Array);
int smallest=Array[0],largest=Array[len-1];
System.out.println("The element that is neither smallest nor
largest is: "+Array[1]);
sc.close();
}

}
The time complexity of this program is O(nlog(n))).
6. Write an efficient program to check if a given number is prime or not. a. What is the
time complexity of the algorithm? b. Show that the problem can be solved in root(n)
time.
Ans:-
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Natural number: ");
int target=sc.nextInt();
int factors=2;
for (int i=2;i<target;++i){
if (target%i==0){
++factors;
}
}
if (factors==2 && target>1){
System.out.println("Prime Number");
}else{
System.out.println("Not Prime");
}
sc.close();
}
}

OUTPUT:-

Enter a Natural number:


19
Prime Number

A) Time Complexity of this program is O(n).


B)
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Natural number: ");
int target=sc.nextInt();
int factors=2;
int root=(int)Math.pow(target,0.5);
for (int i=2;i<root;++i){
if (target%i==0){
++factors;
break;
}
}
if (factors==2 && target>1){
System.out.println("Prime Number");
}else{
System.out.println("Not Prime");
}
sc.close();
}
}

7. Write an efficient program to find the GCD (also called HCF) of two given numbers.
a. What is the time complexity of the algorithm? b. Find an input that requires
maximum number of iterations to solve.
Ans:-
import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num1,num2;
num1=sc.nextInt();
num2=sc.nextInt();
if (num1<=num2){
int temp=num2;
num2=num1;
num1=temp;
}
while(num2!=0){
int temp_1=num2;
num2=num1%num2;
num1=temp_1;
}
System.out.println("The hcf is: "+num1);
sc.close();
}
}

OUTPUT:-

3
7
The hcf is: 1
a) The time complexity of the given program is O(log n).
b) The worst case scenario occurs when the numbers are consecutive fibonacci
numbers. I.e let num1=13,num2=21 then (13,21) takes a lot of iterations.
8. You are given a sorted array A of size n. Write an iterative program to remove the
duplicates from the array. For example, if A[] = {2, 7, 7, 11, 24, 24, 24, 29, 36, 36},
your output should be B[] = {2, 7, 11, 24, 29, 36}. a. Count the operations to get the
closed-form equation of running time (worst case). b. Submit the program for the
problem https://leetcode.com/problems/remove- duplicates-from-sorted-array/
and submit the snapshot of acceptance as proof. c. What is the time complexity?
Ans:-
A)
B)
class Solution {
public int removeDuplicates(int[] nums) {
int len=nums.length;
if (len==0){
return(0);
}else{
int k=1;
for (int i=1;i<nums.length;++i){
if (nums[i]!=nums[i-1]){
nums[k]=nums[i];
++k;
}
}
return(k);
}
}
}
C)The time complexity of the given program is O(n).
9. Consider an array A of size n. Split A[] into the two arrays Low[] and High[] such that
Low[] contains all elements < A[0] and High[] contains all elements >= A[0]. a. Write
an iterative algorithm and implement it. b. What is the time complexity?
Ans:-
A)
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array A:");
int n=sc.nextInt();
int A[]= new int[n];
System.out.println("Enter the elements in array A:");
for (int i=0;i<n;++i){
A[i]=sc.nextInt();
}
int[] low=new int[n];
int[] high=new int[n];
int k=0,l=0;
for (int i=0;i<n;++i){
if (A[0]>A[i]){
low[k]=A[i];
++k;
}else if (A[0]<=A[i]){
high[l]=A[i];
++l;
}
}
for (int i=0;i<low.length;++i){
if (low[i]!=0){
System.out.print(low[i]+" ");
}
}
System.out.println("");
for (int i=0;i<high.length;++i){
if (high[i]!=0){
System.out.print(high[i]+" ");
}
}
sc.close();
}
}

B)The time complexity of the above program without checking the display syn for
Low and High array is: O(n).

10. Given two sorted lists A[1..n] and B[1..n], write an algorithm to merge them into a
single sorted list C[1..2n]. For example, if A[] = {1,3,6,7} and B[] = {2,4,5,8}, then C[] =
{1,2,3,4,5,6,7,8}. a. Find the complexity b. Submit the program for the problem
https://leetcode.com/problems/merge-two- sorted-lists/ and submit the snapshot
of acceptance as proof
Ans:-
a)The time complexity of this problem will be O(n).
b)
class Solution{
public ListNode mergeTwoLists(ListNode a,ListNode b){
ListNode temp=new ListNode(0);
ListNode current=temp;
while(a!=null&&b!=null){
if(a.val<=b.val){
current.next=a;
a=a.next;
}else{
current.next=b;
b=b.next;
}
current=current.next;
}
if(a!=null){
current.next=a;
}else{
current.next=b;
}
return temp.next;
}
}

11. You are given an array coordinates, cord[i] = [x, y], where [x, y] represents the
coordinate of a point. Check if these points make a straight line in the XY plane. a.
Find the time complexity of the algorithm. b. Submit the program for the problem
https://leetcode.com/problems/check-if-it-is-a- straight-line/ and submit the
snapshot of acceptance as proof.
Ans:-
class Solution {
public boolean checkStraightLine(int[][] coordinates) {
int len=coordinates.length;
int a=coordinates[len-1][1]-coordinates[0][1];
int b=(coordinates[len-1][0]-coordinates[0][0]);
double slope;
if (b==0){
slope=Double.POSITIVE_INFINITY;
}else{
slope=(double)a/b;
}
double c=coordinates[0][1]-slope*coordinates[0][0];
int x=1;
int r=coordinates[0][0];
int s=coordinates[0][1];
for (int i=0;i<len;++i){
if (a==0){
if (coordinates[i][1]!=s){
x=0;
}
}else if (b==0){
if (coordinates[i][0]!=r){
x=0;
};
}else if (coordinates[i][1]!=slope*coordinates[i][0]+c){
x=0;
}
}
if (x==1){
return(true);
}else{
return(false);
}
}
}

a) The time complexity of above program is O(n).


b)

12. There is a class with m students and n exams. You are given a 0-indexed m x n
integer matrix called score, where score[i][j] denotes the score the ith student got in
the jth exam. The matrix score contains distinct integers only. You are also given an
integer k. Sort the students (i.e., the rows of the matrix) by their scores in the kth (0 -
indexed) exam from the highest to the lowest. Return the matrix after sorting it. a.
Find the time complexity b. Submit the program for the problem
https://leetcode.com/problems/sort-the- students-by-their-kth-score/ and submit
the snapshot of acceptance as proof.
Ans:-

You might also like