0% found this document useful (0 votes)
3 views

AAPS_LAB FileFormat

The document is a lab file for a course on Advanced Algorithmic & Problem Solving at Galgotias University, detailing various programming problems and their solutions. Each problem includes an aim, description, source code, and output, covering topics such as finding missing numbers, detecting duplicates, and sorting algorithms. The lab file serves as a practical guide for students in the Bachelor of Engineering & Technology program.
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)
3 views

AAPS_LAB FileFormat

The document is a lab file for a course on Advanced Algorithmic & Problem Solving at Galgotias University, detailing various programming problems and their solutions. Each problem includes an aim, description, source code, and output, covering topics such as finding missing numbers, detecting duplicates, and sorting algorithms. The lab file serves as a practical guide for students in the Bachelor of Engineering & Technology program.
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/ 32

Advance Algorithmic & Problem Solving

Course Code: R1UC601B

Lab File
For
BACHELOR OF

ENGINEERING & TECHNOLOGY

SCHOOL OF COMPUTER SCIENCE AND ENGINEERING

GALGOTIAS UNIVERSITY, GREATER NOIDA

UTTAR PRADESH

Student Name: MRITUNJAY KUMAR

Admission No: 21SCSE1010595

Semester : VI

1|P a g e
PROBLEM NO. : 1

AIM : Missing number in array, Rotate Bits

PROGRAM :
DESCRIPTION:

Find the sum of the numbers in the range [1, N] using the formula N * (N+1)/2. Now find
the sum of all the elements in the array and subtract it from the sum of the first N natural
numbers. This will give the value of the missing element.

SOURCE CODE:
import java.util.Arrays;

class prb_solv {

public static int getMissingNo(int[] nums, int n) {


int expectedSum = (n + 1) * (n + 2) / 2;
int actualSum = Arrays.stream(nums).sum();
return expectedSum - actualSum;
}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 5};
int N = arr.length;
System.out.println("The missing number is: " + getMissingNo(arr,
N));
}
}

OUTPUT:

2|P a g e
PROBLEM NO. : 2

AIM : Power of 2, Bit-Difference

PROGRAM :
DESCRIPTION:

A simple method for this is to simply take the log of the number on base 2 and if you get
an integer then the number is the power of 2

SOURCE CODE:
class prb_solv {

public static int nextPowerOf2(int n) {


if (n <= 0) return 1;
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n + 1;
}
public static int bitDifference(int a, int b) {
int xor = a ^ b;
int count = 0;
while (xor != 0) {
count += xor & 1;
xor >>= 1;
}
return count;
}

// Driver code
public static void main(String[] args) {
int num = 19;
int nextPower = nextPowerOf2(num);
System.out.println("Next power of 2 greater than or equal to " +
num + " is: " + nextPower);

int a = 5;
int b = 14;
int diff = bitDifference(a, b);
System.out.println("Number of differing bits between " + a + "
and " + b + " is: " + diff);

3|P a g e
}
}

OUTPUT:

4|P a g e
PROBLEM NO. : 3

AIM : Detecting Duplicates in Array, Longest Consecutive 1's (Hamming Weight)

PROGRAM :
DESCRIPTION:

This experiment explores two fundamental computer science problems: detecting


duplicates in an array and finding the longest sequence of consecutive 1's in the binary
representation of a number.

SOURCE CODE:
import java.util.HashSet;
import java.util.Set;

class prb_solv {
public static boolean hasDuplicates(int[] nums) {
Set<Integer> seen = new HashSet<>();
for (int num : nums) {
if (!seen.add(num)) {
return true;
}
}
return false;
}

public static int longestConsecutiveOnes(int n) {


int maxCount = 0;
int currentCount = 0;

while (n > 0) {
if ((n & 1) == 1) {
currentCount++;
maxCount = Math.max(maxCount, currentCount);
} else {
currentCount = 0;
}
n >>= 1;
}

return maxCount;
}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1};

5|P a g e
System.out.println("Array has duplicates: " +
hasDuplicates(arr));
int num = 29;
System.out.println("Longest consecutive 1's in " + num + ": " +
longestConsecutiveOnes(num));
}
}

OUTPUT:

6|P a g e
PROBLEM NO. : 4

AIM : Detecting Duplicates in Array, Longest Consecutive 1's (Hamming Weight)

PROGRAM :

SOURCE CODE:
import java.util.HashSet;
import java.util.Set;

class prb_solv {

public static int findUnique(int[] nums) {


int unique = 0;
for (int num : nums) {
unique ^= num;
}
return unique;
}
public static int findMaximumXOR(int[] nums) {
int maxXOR = 0;
int prefixXOR = 0;
Set<Integer> prefixSet = new HashSet<>();

prefixSet.add(0);

for (int num : nums) {


prefixXOR ^= num;
maxXOR = Math.max(maxXOR, prefixXOR);
for (int prefix : prefixSet) {
maxXOR = Math.max(maxXOR, prefixXOR ^ prefix);
}
prefixSet.add(prefixXOR);
}

return maxXOR;
}
public static void main(String[] args) {
int[] uniqueArray = {2, 3, 5, 4, 5, 3, 4};
System.out.println("Unique element in the array: " +
findUnique(uniqueArray));

int[] xorArray = {8, 1, 2, 12, 7, 6};


System.out.println("Maximum XOR of any subarray: " +
findMaximumXOR(xorArray));

7|P a g e
}
}

OUTPUT:

8|P a g e
PROBLEM NO. : 5

AIM : Find the Kth largest elements in an array, Rearrange an array in maximum
minimum form using Two Pointer Technique

PROGRAM :

SOURCE CODE:
import java.util.PriorityQueue;
import java.util.Arrays;

class prb_solv {
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int num : nums) {
minHeap.add(num);
if (minHeap.size() > k) {
minHeap.poll();
}
}
return minHeap.peek();
}
public static void rearrangeMaxMin(int[] nums) {
int n = nums.length;
int[] result = new int[n];
int left = 0;
int right = n - 1;
boolean placeMax = true;

for (int i = 0; i < n; i++) {


if (placeMax) {
result[i] = nums[right--];
} else {
result[i] = nums[left++];
}
placeMax = !placeMax;
}
System.arraycopy(result, 0, nums, 0, n);
}
public static void main(String[] args) {
int[] arr1 = {3, 2, 1, 5, 6, 4};
int k = 2;
System.out.println("The " + k + "th largest element is: " +
findKthLargest(arr1, k));
int[] arr2 = {1, 2, 3, 4, 5, 6, 7};

9|P a g e
System.out.println("Original array: " + Arrays.toString(arr2));
rearrangeMaxMin(arr2);
System.out.println("Rearranged array: " + Arrays.toString(arr2));
}
}

OUTPUT:

10 | P a g e
PROBLEM NO. : 6

AIM : Move all zeroes to end of array, Rearrange array such that even positioned are
greater than odd

PROGRAM :

SOURCE CODE:
import java.util.Arrays;

class prb_solv {
public static void moveZeroesToEnd(int[] nums) {
int n = nums.length;
int index = 0;

for (int i = 0; i < n; i++) {


if (nums[i] != 0) {
nums[index++] = nums[i];
}
}
while (index < n) {
nums[index++] = 0;
}
}
public static void rearrangeEvenOddPositions(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int[] result = new int[n];

int left = 0;
int right = (n % 2 == 0) ? n / 2 : n / 2 + 1;

for (int i = 0; i < n; i++) {


if (i % 2 == 0) {
result[i] = nums[right++];
} else {
result[i] = nums[left++];
}
}
System.arraycopy(result, 0, nums, 0, n);
}
public static void main(String[] args) {
int[] arr1 = {0, 1, 0, 3, 12};
System.out.println("Original array: " + Arrays.toString(arr1));
moveZeroesToEnd(arr1);

11 | P a g e
System.out.println("Array after moving zeroes to end: " +
Arrays.toString(arr1));

int[] arr2 = {1, 3, 2, 2, 5, 6};


System.out.println("Original array: " + Arrays.toString(arr2));
rearrangeEvenOddPositions(arr2);
System.out.println("Rearranged array (even positions > odd
positions): " + Arrays.toString(arr2));
}
}

OUTPUT:

12 | P a g e
PROBLEM NO. : 7

AIM : Find sub-array with given sum, Find the smallest missing number

PROGRAM :

SOURCE CODE:
import java.util.HashSet;

class ArrayManipulation {
public static int[] findSubArrayWithGivenSum(int[] nums, int
targetSum) {
int left = 0;
int currentSum = 0;

for (int right = 0; right < nums.length; right++) {


currentSum += nums[right];

while (currentSum > targetSum && left <= right) {


currentSum -= nums[left];
left++;
}

if (currentSum == targetSum) {
int[] subArray = new int[right - left + 1];
System.arraycopy(nums, left, subArray, 0, right - left +
1);
return subArray;
}
}
return new int[0];
}
public static int findSmallestMissingNumber(int[] nums) {
HashSet<Integer> set = new HashSet<>();

for (int num : nums) {


if (num > 0) {
set.add(num);
}
}

int smallestMissing = 1;
while (set.contains(smallestMissing)) {
smallestMissing++;
}

13 | P a g e
return smallestMissing;
}
public static void main(String[] args) {
int[] arr1 = {1, 4, 20, 3, 10, 5};
int sum = 33;
int[] subArray = findSubArrayWithGivenSum(arr1, sum);
if (subArray.length > 0) {
System.out.println("Sub-array with sum " + sum + ": " +
java.util.Arrays.toString(subArray));
} else {
System.out.println("No sub-array found with sum " + sum);
}
int[] arr2 = {1, 3, 6, 4, 1, 2};
int missingNumber = findSmallestMissingNumber(arr2);
System.out.println("Smallest missing positive number: " +
missingNumber);
}
}

OUTPUT:

14 | P a g e
PROBLEM NO. : 8

AIM : Merge two sorted arrays with O(1) extra space, Search an element in a sorted and
rotated array

PROGRAM :

SOURCE CODE:
class ArrayManipulation {

public static void mergeSortedArrays(int[] nums1, int m, int[] nums2,


int n) {
int i = m - 1;
int j = n - 1;
int k = m + n - 1;

while (i >= 0 && j >= 0) {


if (nums1[i] > nums2[j]) {
nums1[k--] = nums1[i--];
} else {
nums1[k--] = nums2[j--];
}
}
while (j >= 0) {
nums1[k--] = nums2[j--];
}
}
public static int searchRotatedSortedArray(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (nums[mid] == target) {
return mid;
}
if (nums[left] <= nums[mid]) {
if (target >= nums[left] && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (target > nums[mid] && target <= nums[right]) {
left = mid + 1;

15 | P a g e
} else {
right = mid - 1;
}
}
}
return -1;
}
public static void main(String[] args) {
int[] nums1 = {1, 3, 5, 0, 0, 0};
int m = 3;
int[] nums2 = {2, 4, 6};
int n = 3;
mergeSortedArrays(nums1, m, nums2, n);
System.out.println("Merged sorted array: " +
java.util.Arrays.toString(nums1));
int[] rotatedArray = {4, 5, 6, 7, 0, 1, 2};
int target = 0;
int index = searchRotatedSortedArray(rotatedArray, target);
System.out.println("Index of target " + target + " in rotated
array: " + index);
}
}

OUTPUT:

16 | P a g e
PROBLEM NO. : 9

AIM : Sort elements by frequency, How to sort an array of dates in C/C++?

PROGRAM :
Sorting an Array of Dates in C/C++
To sort an array of dates in C/C++, you can define a custom comparison function for the
date data type and use it with a sorting algorithm like std::sort

SOURCE CODE:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Date {
int day, month, year;
bool operator<(const Date& other) const {
if (year != other.year) return year < other.year;
if (month != other.month) return month < other.month;
return day < other.day;
}
};

int main() {
vector<Date> dates = {{1, 12, 2021}, {31, 10, 2020}, {15, 7, 2022},
{1, 1, 2021}};
sort(dates.begin(), dates.end());
for (const auto& date : dates) {
cout << date.day << "/" << date.month << "/" << date.year <<
endl;
}

return 0;
}

17 | P a g e
OUTPUT:

18 | P a g e
PROBLEM NO. : 10

AIM : Bucket Sort To Sort an Array with Negative Numbers, K-Way Merge Sort

PROGRAM :
SOURCE CODE:
import java.util.*;

public class prb_solv {

public static void bucketSort(int[] nums) {


int minValue = Arrays.stream(nums).min().getAsInt();
int maxValue = Arrays.stream(nums).max().getAsInt();
int bucketRange = maxValue - minValue + 1;
List<List<Integer>> buckets = new ArrayList<>(bucketRange);

for (int i = 0; i < bucketRange; i++) {


buckets.add(new ArrayList<>());
}

for (int num : nums) {


buckets.get(num - minValue).add(num);
}

int index = 0;
for (List<Integer> bucket : buckets) {
Collections.sort(bucket);
for (int num : bucket) {
nums[index++] = num;
}
}
}

static class Element {


int value;
int arrayIndex;

public Element(int value, int arrayIndex) {


this.value = value;
this.arrayIndex = arrayIndex;
}
}

public static int[] kWayMergeSort(int[][] arrays) {


int k = arrays.length;

19 | P a g e
PriorityQueue<Element> minHeap = new
PriorityQueue<>(Comparator.comparingInt(a -> a.value));

for (int i = 0; i < k; i++) {


if (arrays[i].length > 0) {
minHeap.offer(new Element(arrays[i][0], i));
arrays[i] = Arrays.copyOfRange(arrays[i], 1,
arrays[i].length);
}
}

List<Integer> sortedArray = new ArrayList<>();


while (!minHeap.isEmpty()) {
Element minElement = minHeap.poll();
sortedArray.add(minElement.value);

if (arrays[minElement.arrayIndex].length > 0) {
minHeap.offer(new Element(arrays[minElement.arrayIndex]
[0], minElement.arrayIndex));
arrays[minElement.arrayIndex] =
Arrays.copyOfRange(arrays[minElement.arrayIndex], 1,
arrays[minElement.arrayIndex].length);
}
}

return
sortedArray.stream().mapToInt(Integer::intValue).toArray();
}

public static void main(String[] args) {


// Bucket Sort
int[] nums = {4, -5, 6, -2, 1, -8, 3};
bucketSort(nums);
System.out.println("Bucket Sorted Array: " +
Arrays.toString(nums));

// K-Way Merge Sort


int[][] arrays = {{3, 6, 9}, {1, 4, 7}, {2, 5, 8}};
int[] sortedArray = kWayMergeSort(arrays);
System.out.println("K-Way Merge Sorted Array: " +
Arrays.toString(sortedArray));
}
}

OUTPUT:

20 | P a g e
PROBLEM NO. : 11

AIM : Sum of natural numbers using recursion, Decimal to binary number using
recursion

PROGRAM :
SOURCE CODE:
public class prob_solv {
public static int sumOfNaturalNumbers(int n) {
if (n == 0) {
return 0;
} else {
return n + sumOfNaturalNumbers(n - 1);
}
}

public static String decimalToBinary(int n) {


if (n == 0) {
return "0";
} else if (n == 1) {
return "1";
} else {
return decimalToBinary(n / 2) + (n % 2);
}
}

public static void main(String[] args) {


int n = 5;
int sum = sumOfNaturalNumbers(n);
System.out.println("Sum of first " + n + " natural numbers: "
+ sum);
int decimalNumber = 10;
String binaryNumber = decimalToBinary(decimalNumber);
System.out.println("Binary representation of " +
decimalNumber + ": " + binaryNumber);
}
}

OUTPUT:

21 | P a g e
PROBLEM NO. : 12

AIM : Print reverse of a string using recursion, Program for length of a string using
recursion

PROGRAM :
SOURCE CODE:
public class prob_solv {
public static String reverseString(String str) {
if (str.isEmpty()) {
return str;
} else {
return reverseString(str.substring(1)) + str.charAt(0);
}
}

public static int lengthOfString(String str) {


if (str.isEmpty()) {
return 0;
} else {
return 1 + lengthOfString(str.substring(1));
}
}

public static void main(String[] args) {


String inputString = "hello";
String reversedString = reverseString(inputString);
System.out.println("Reverse of \"" + inputString + "\": " +
reversedString);
String str = "world";
int length = lengthOfString(str);
System.out.println("Length of \"" + str + "\": " + length);
}
}

OUTPUT:

22 | P a g e
PROBLEM NO. : 13

AIM : Sort the Queue using Recursion, Reversing a queue using recursion

PROGRAM :
SOURCE CODE:
Sorting a Queue using Recursion
import java.util.LinkedList;
import java.util.Queue;

public class prob_solv {

public static void sortQueue(Queue<Integer> queue) {


if (queue.isEmpty()) {
return;
}

int front = queue.poll();


sortQueue(queue);
insertInSortedOrder(queue, front);
}

private static void insertInSortedOrder(Queue<Integer> queue, int


element) {
if (queue.isEmpty() || element < queue.peek()) {
queue.add(element);
} else {
int front = queue.poll();
insertInSortedOrder(queue, element);
queue.add(front);
}
}

public static void main(String[] args) {


Queue<Integer> queue = new LinkedList<>();
queue.add(3);
queue.add(1);
queue.add(4);

23 | P a g e
queue.add(1);
queue.add(5);
queue.add(9);

System.out.println("Original Queue: " + queue);


sortQueue(queue);
System.out.println("Sorted Queue: " + queue);
}
}

OUTPUT:

Reversing a Queue using Recursion


import java.util.LinkedList;
import java.util.Queue;

public class prob_solv {

public static void reverseQueue(Queue<Integer> queue) {


if (queue.isEmpty()) {
return;
}

int front = queue.poll();


reverseQueue(queue);
queue.add(front);
}

public static void main(String[] args) {


Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);

24 | P a g e
queue.add(5);

System.out.println("Original Queue: " + queue);


reverseQueue(queue);
System.out.println("Reversed Queue: " + queue);
}
}

OUTPUT:

25 | P a g e
PROBLEM NO. : 14

AIM : Length of longest palindromic sub-string : Recursion, Convert a String to an


Integer using Recursion

PROGRAM :
SOURCE CODE:
Length of Longest Palindromic Substring using Recursion
public class PalindromeAndStringToInt {

public static int longestPalindromicSubstring(String str) {


return longestPalindromicSubstringHelper(str, 0, str.length() -
1);
}

private static int longestPalindromicSubstringHelper(String str, int


left, int right) {
if (left > right) {
return 0;
}
if (left == right) {
return 1;
}
if (str.charAt(left) == str.charAt(right)) {
int remainingLength = right - left - 1;
if (remainingLength == longestPalindromicSubstringHelper(str,
left + 1, right - 1)) {
return remainingLength + 2;
}
}
return Math.max(longestPalindromicSubstringHelper(str, left + 1,
right),
longestPalindromicSubstringHelper(str, left,
right - 1));
}

public static void main(String[] args) {


String str = "babad";
int length = longestPalindromicSubstring(str);
System.out.println("Length of longest palindromic substring: " +
length);
}
}

26 | P a g e
OUTPUT:

27 | P a g e
Convert a String to an Integer using Recursion
CODE:
public class PalindromeAndStringToInt {

public static int stringToInt(String str) {


return stringToIntHelper(str, str.length() - 1, 0);
}

private static int stringToIntHelper(String str, int index, int


multiplier) {
if (index < 0) {
return 0;
}
int digit = str.charAt(index) - '0';
return digit * (int) Math.pow(10, multiplier) +
stringToIntHelper(str, index - 1, multiplier + 1);
}

public static int longestPalindromicSubstring(String str) {


return longestPalindromicSubstringHelper(str, 0, str.length() -
1);
}

private static int longestPalindromicSubstringHelper(String str, int


left, int right) {
if (left > right) {
return 0;
}
if (left == right) {
return 1;
}
if (str.charAt(left) == str.charAt(right)) {
int remainingLength = right - left - 1;
if (remainingLength == longestPalindromicSubstringHelper(str,
left + 1, right - 1)) {
return remainingLength + 2;
}
}
return Math.max(longestPalindromicSubstringHelper(str, left + 1,
right),
longestPalindromicSubstringHelper(str, left,
right - 1));
}

public static void main(String[] args) {


// Length of longest palindromic substring
String palindromeStr = "babad";

28 | P a g e
int length = longestPalindromicSubstring(palindromeStr);
System.out.println("Length of longest palindromic substring: " +
length);

// Convert string to integer using recursion


String numStr = "12345";
int num = stringToInt(numStr);
System.out.println("String to integer: " + num);
}
}

OUTPUT:

29 | P a g e
PROBLEM NO. : 15

AIM : DFS traversal of a Tree, How to Sort a Stack using Recursion

PROGRAM :
SOURCE CODE:
DFS Traversal of a Tree
class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode(int val) {
this.val = val;
left = null;
right = null;
}
}

public class TreeTraversal {

public static void dfs(TreeNode root) {


if (root == null) {
return;
}
System.out.print(root.val + " ");
dfs(root.left);
dfs(root.right);
}

public static void main(String[] args) {


TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);

System.out.print("DFS Traversal: ");


dfs(root);
}
}

30 | P a g e
OUTPUT:

Sorting a Stack using Recursion


import java.util.Stack;

public class StackSort {

public static void sortStack(Stack<Integer> stack) {


if (stack.isEmpty()) {
return;
}
int top = stack.pop();
sortStack(stack);
insertInSortedOrder(stack, top);
}

private static void insertInSortedOrder(Stack<Integer> stack, int


element) {
if (stack.isEmpty() || element > stack.peek()) {
stack.push(element);
} else {
int top = stack.pop();
insertInSortedOrder(stack, element);
stack.push(top);
}
}

public static void main(String[] args) {


Stack<Integer> stack = new Stack<>();
stack.push(3);
stack.push(1);
stack.push(4);
stack.push(2);
stack.push(5);

System.out.println("Original Stack: " + stack);


sortStack(stack);
System.out.println("Sorted Stack: " + stack);

31 | P a g e
}
}

OUTPUT:

32 | P a g e

You might also like