Sunday, January 30, 2022

Sum Of Two Arrays

package jan20;

import java.util.Scanner;

public class SumOf2Arrays {
public static void main(String[] args) {
// Create a Scanner object for input
// TC: O(1), SC: O(1)
Scanner sc = new Scanner(System.in);

int size1 = sc.nextInt();
// TC: O(1), SC: O(1)

int[] arr1 = new int[size1];
// TC: O(1), SC: O(size1)

for (int i = 0; i < size1; i++) {
arr1[i] = sc.nextInt();
// TC: O(size1), SC: O(1) per element (already allocated)
}

int size2 = sc.nextInt();
// TC: O(1), SC: O(1)

int[] arr2 = new int[size2];
// TC: O(1), SC: O(size2)

for (int i = 0; i < size2; i++) {
arr2[i] = sc.nextInt();
// TC: O(size2), SC: O(1) per element (already allocated)
}

sum(arr1, size1, arr2, size2);
// TC: O(max(size1, size2)), SC: O(max(size1, size2))
}

private static void sum(int[] arr1, int size1, int[] arr2, int size2) {
int p1 = size1 - 1, p2 = size2 - 1, p3, carry = 0;
// TC: O(1), SC: O(1)

int[] ansArr = new int[size1 > size2 ? size1 + 1 : size2 + 1];
// TC: O(1), SC: O(max(size1, size2) + 1)

p3 = ansArr.length - 1;
// TC: O(1), SC: O(1)

while (p3 > 0) {
// Loop runs O(max(size1, size2)) times

int sum = (p1 >= 0 ? arr1[p1] : 0) + (p2 >= 0 ? arr2[p2] : 0) + carry;
// TC: O(1), SC: O(1)

ansArr[p3] = sum % 10;
// TC: O(1), SC: O(1)

carry = sum / 10;
// TC: O(1), SC: O(1)

p1--;
p2--;
p3--;
// TC: O(1) each
}

if (carry > 0) ansArr[p3] = carry;
// TC: O(1), SC: O(1)

for (int i : ansArr){
System.out.print(i + "");
// TC: O(max(size1, size2)), SC: O(1) per element print
}
}
}
CaseTime ComplexitySpace Complexity1-line Explanation
Best CaseO(max(size1, size2))O(max(size1, size2))Always need to add all digits even if one array has mostly zeros.
Average CaseO(max(size1, size2))O(max(size1, size2))Typically process all digits with some carries happening.
Worst CaseO(max(size1, size2))O(max(size1, size2))Maximum possible carries (like 999 + 1) but still proportional to number of digits.

Summary in simple words:

  • Time always depends on the larger array size, because addition needs to touch every digit once.

  • Space always depends on the size of the bigger array +1 (for possible carry at the most significant digit).


No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...