Professional Documents
Culture Documents
DAA File
DAA File
implement it using a program to find whether given key element is present in the
array or not. Also, find total number of comparisons for each input case.
# Code
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
key = int(input().strip())
cmps = 0
# Code
while l <= r:
mid = (l + r) // 2
if arr[mid] == key:
comps += 1
return f"Present {comps}"
for _ in range(int(input().strip())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
key = int(input().strip())
# Code
if prev >= n:
return f"Not Present {cmps}"
for _ in range(int(input().strip())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
key = int(input().strip())
# Code
while l <= r:
mid = (l + r) // 2
if arr[mid] == key:
is_present = True
left_most = mid
r = mid - 1
l, r = 0, n-1
while l <= r:
mid = (l + r) // 2
if arr[mid] == key:
is_present = True
right_most = mid
l = mid + 1
if is_present:
return f"{key} - {(right_most - left_most) + 1}"
for _ in range(int(input().strip())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
key = int(input().strip())
# Code
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
found = False
for i in range(n):
target = arr[i]
l, r = 0, n-1
while l < r:
if arr[l] + arr[r] == target and i not in (l, r):
print(l, r, i)
found = True
break
if arr[l] + arr[r] < target:
l += 1
else:
r -= 1
if not found:
print("No sequence found")
Ques6: Given an array of non-negative integers, design an algorithm and a program
to count the number of pairs of integers such that their difference is equal to a given
key, K.
# Code
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
key = int(input().strip())
arr.sort()
l=r=0
cnt = 0
while r < n:
if arr[r] - arr[l] == key:
cnt += 1
l += 1
r += 1
elif arr[r] - arr[l] < key:
r += 1
else:
l += 1
print(cnt)
Ques7: Given an unsorted array of integers, design an algorithm and a program to
sort the array using insertion sort. Your program should be able to find number of
comparisons and shifts ( shifts - total number of times the array elements are
shifted from their place) required for sorting the array.
# Code
arr[j+1] = key
shifts += 1
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
# Code
for i in range(n-1):
min_ = i
for j in range(i+1, n):
if arr[j] < arr[min_]:
j = min_
cmps += 1
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
# Code
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
arr.sort()
# Code
cmps[0] += 1
mid = len(arr) // 2
left_part = arr[:mid]
right_part = arr[mid:]
return res
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
cmps = [0]
inversions = cnt_inversions(arr, n)
res = merge_sort(arr, cmps)
print(*res)
print(f"Comparisions: {cmps[0]}, Inversions: {inversions}”)
Ques11: Given an unsorted array of integers, design an algorithm and implement it
using a program to sort an array of elements by partitioning the array into two
subarrays based on a pivot element such that one of the sub array holds values
smaller than the pivot element while another sub array holds values greater than the
pivot element. Pivot element should be selected randomly from the array. Your
program should also find number of comparisons and swaps required for sorting
the array.
# Code
return end
return arr
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
# Code
p = pivot()
if p > k: return quick_select(arr, start, p-
1) if p < k: return quick_select(arr, p+1,
end) return arr[p]
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
k = int(input().strip()) - 1
# Code
for _ in range(int(input())):
n = int(input().strip())
arr = input().strip().split()
freq = {}
for c in arr:
freq[c] = freq.get(c, 0) + 1
if max_freq < 2:
print("No duplicates present")
else:
print(f"{res} - {max_freq}")
Ques14: Given an unsorted array of integers, design an algorithm and implement it
using a program to find whether two elements exist such that their sum is equal to
the given key element. (Time Complexity = O(n log n))
# Code
for _ in range(int(input())):
n = int(input().strip())
arr = list(map(int, input().strip().split()))
key = int(input().strip())
arr.sort()
l, r = 0, n-1
while l < r:
if arr[l] + arr[r] == key:
print(arr[l], arr[r])
break
else:
print("No such elements exists")
Ques15: You have been given two sorted integer arrays of size m and n. Design an
algorithm and implement it using a program to find list of elements which are
common to both. (Time Complexity = O(m+n))
# Code
m = int(input())
arr1 = list(map(int, input().split()))
n = int(input())
arr2 = list(map(int, input().split()))
common = set()
for ele in arr1:
common.add(ele)
for i in range(n):
if arr2[i] in common:
print(arr2[i], end=" ")
Ques16: Given a (directed/undirected) graph, design an algorithm and implement it
using a program to find if a path exists between two given vertices or not.
# Code
# Undirected Graph Assumed
while q:
curr = q.pop(0)
return "Yes Path Exists" if len(visited) == len(graph) else "No Path Exists"
for _ in range(int(input())):
graph = {}
node = 1
for _ in range(int(input())):
edges = list(map(int, input().strip().split()))
graph[node] = [i for i in range(1, len(edges)+1) if edges[i-1]]
node += 1
# Code
if graph[curr][curr-1]:
return "Not Bipartite”
for i in range(len(graph[curr])):
if graph[curr][i] and visited[i] == -1:
visited[i] = 1 - visited[curr]
q.append(i)
graph = {}
node = 1
for _ in range(int(input())):
edges = list(map(int, input().strip().split()))
graph[node] = edges
node += 1
res = bfs(graph, 1)
print(res)
Ques18: Given a directed graph, design an algorithm and implement it using a
program to find whether cycle exists in the graph or not.
# Code
while bfs_queue:
node = bfs_queue.pop(0)
cnt += 1
for i in range(len(graph[node])):
if graph[node][i]:
degree[i] -= 1
if not degree[i]:
bfs_queue.append(i+1)
graph = {}
node = 1
n = int(input())
for _ in range(n):
edges = list(map(int, input().strip().split()))
graph[node] = edges
node += 1
res = bfs(graph, n)
print(res)
Ques19: Design an algorithm and implement it using a program to solve problem
using Dijkstra’s shortest path algorithm.
# Code
import heapq
graph = {}
node = 1
n = int(input())
for _ in range(n):
edges = list(map(int, input().strip().split()))
graph[node] = [(i, edges[i-1]) for i in range(1, n+1) if edges[i-1]]
node += 1
src = int(input())
for i in range(1, n+1):
res = dijkstra_algo(graph, src, i)
print(res)
Ques20: Design an algorithm and implement it using a program to solve problem
using Bellman-Ford shortest path algorithm.
# Code
return distance
graph = {}
node = 1
n = int(input())
for _ in range(n):
edges = list(map(int, input().strip().split()))
graph[node] = [(i, edges[i-1]) for i in range(1, n+1) if edges[i-1]]
node += 1
src = int(input())
for i in range(1, n+1):
res = bellman_ford(graph, src, n)
print(f"{src} to {i} : {res[i-1]}")
Ques21: Given a directed graph with two vertices ( source and destination). Design
an algorithm and implement it using a program to find the weight of the shortest
path from source to destination with exactly k edges on the path.
# Code
res = float("inf")
for i in range(n):
if graph[src][i] != float("inf") and src != i+1 and dst != i:
rec_res = shortest_path(graph, i+1, dst, k - 1, n)
if rec_res != float("inf"):
res = min(res, graph[src][i] + rec_res)
return res
graph = {}
node = 1
n = int(input())
for _ in range(n):
edges = list(map(int, input().strip().split()))
graph[node] = edges
node += 1
# Code
for i in range(n):
if (mstset[i] == False and
keyval[i] < min_):
min_ = keyval[i]
mini_index = i
return mini_index
for i in range(n):
keyval[i] = float("inf")
mstset[i] = False
parent[0] = -1
keyval[0] = 0
for v in range(n):
if (city[u+1][v] and mstset[v] == False and
city[u+1][v] < keyval[v]):
keyval[v] = city[u+1][v]
parent[v] = u
cost = 0
for i in range(1, n):
cost += city[parent[i]+1][i]
return cost
graph = {}
node = 1
n = int(input())
for _ in range(n):
edges = list(map(int, input().strip().split()))
graph[node] = edges
node += 1
# Code
for i in range(n):
if (mstset[i] == False and
keyval[i] > max_):
max_ = keyval[i]
max_index = i
return max_index
for i in range(n):
keyval[i] = float("-inf")
mstset[i] = False
parent[0] = -1
keyval[0] = float("inf")
for v in range(n):
if (city[v+1][u] and mstset[v] == False and
city[v+1][u] > keyval[v]):
keyval[v] = city[v+1][u]
parent[v] = u
cost = 0
for i in range(1, n):
cost += city[parent[i]+1][i]
return cost
graph = {}
node = 1
n = int(input())
for _ in range(n):
edges = list(map(int, input().strip().split()))
graph[node] = edges
node += 1
# Code
n = int(input())
graph = [[None] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if i == j:
graph[i][j] = 0
else:
graph[i][j] = float("inf")
node = 0
for _ in range(n):
edges = list(map(int, input().strip().split()))
connections = [(node, i, edges[i]) for i in range(n)]
floyd_warshall(graph, n)
print("\nShortest Distance Matrix:")
print(*graph, sep="\n")
Ques25: Given a knapsack of maximum capacity w. N items are provided, each
having its own value and weight. You have to Design an algorithm and implement it
using a program to find the list of the selected items such that the final selected
content has weight w and has maximum value. You can take fractions of items,i.e.
the items can be broken into smaller pieces so that you have to carry
only a fraction xi of item i, where 0 ≤xi≤ 1.
# Code
max_value = 0
fractions = [0] * len(vals)
for i in index:
if weight[i] <= capacity:
fractions[i] = 1
max_value += vals[i]
capacity -= weight[i]
else:
fractions[i] = round(capacity / weight[i], 2)
max_value += vals[i] * capacity / weight[i]
break
for _ in range(int(input())):
weights = list(map(int, input().strip().split()))
vals = list(map(int, input().strip().split()))
capacity = int(input().strip())
# Code
import heapq
def get_min_merge_cost(arr):
heapq.heapify(arr)
cost = 0
while len(arr) > 1:
v1 = heapq.heappop(arr)
v2 = heapq.heappop(arr)
return cost
for _ in range(int(input())):
arr = list(map(int, input().split()))
min_cost = get_min_merge_cost(arr)
print(min_cost)
Ques27: Given a list of activities with their starting time and finishing time. Your
goal is to select maximum number of activities that can be performed by a single
person such that selected activities must be non-conflicting. Any activity is said to
be non-conflicting if starting time of an activity is greater than or equal to the
finishing time of the other activity. Assume that a person can only work on a single
activity at a time.
# Code
n = int(input())
start = list(map(int, input().strip().split()))
end = list(map(int, input().strip().split()))
res = [intervals[0]]
i=0
for j in range(1, n):
if intervals[j][0] >= intervals[i][1]:
res.append(intervals[j])
i=j
print(len(res))
print(*res)
Ques28: Given a long list of tasks. Each task takes specific time to accomplish it
and each task has a deadline associated with it. You have to design an algorithm
and implement it using a program to find maximum number of tasks that can be
completed without crossing their deadlines and also find list of selected tasks.
# Code
n = int(input())
time = list(map(int, input().strip().split()))
deadline = list(map(int, input().strip().split()))
res = []
for t, d in jobs:
if not slots[d-1]:
slots[d-1] = True
res.append(t)
else:
tmp = d - 1
while tmp >= 0 and slots[tmp]:
tmp -= 1
if tmp >= 0:
slots[tmp] = True
res.append(t)
# Code
n = int(input().strip())
arr = list(map(int, input().strip().split()))
arr.sort()
candidate = arr[n // 2]
cnt = 0
for ele in arr:
if ele == candidate:
cnt += 1