CH 6 [Arrays]
CH 6 [Arrays]
Arrays
• The array is a simplest data structure.
• Given an array A, A[i] denotes the (i+l)th object stored in the array.
• Insertion into a full array can be handled by resizing, i.e., allocating a new array with
additional memory and copying over the entries from the original array.
• Deleting an element from an array entails moving all successive elements one over to the
left to fill the vacated space.
o The time complexity to delete the element at index i from an array of length n is
O(n- i).
Write a program to define an array, which take the array input from the user.
Then reorder its entries so that the even entries appear first.
Approach:
• For this problem, partition the array into three subarrays: Even, Unclassified, and Odd,
appearing in that order.
• Initially Even and Odd are empty, and Unclassified is the entire array.
• We iterate through Unclassified, moving its elements to the boundaries of the Even and
Odd subarrays via swaps, thereby expanding Even and Odd, and shrinking Unclassified.
Programme:
import java.util.Scanner;
int size;
A[i] = s.nextInt();
}
System.out.println();
evenOdd(A);
if (A[nextEven] % 2 == 0) {
nextEven++;
}
else {
A[nextEven] = A[nextOdd];
A[nextOdd--] = temp;
}
} //end of while
} //end of evenOdd()
} //end of EvenOddProg1
Output:
Time Complexity:
Space Complexity:
• It uses O(n) space, where n is the length of the array. The additional space complexity is
clearly O(1) - a couple of variables that hold indices, and a temporary variable for
performing the swap.
• The Dutch national flag (DNF) problem is one of the most popular programming
problems proposed by Edsger Dijkstra. The flag of the Netherlands consists of three
colors: white, red, and blue.
• The Dutch national flag (DNF) is closely related to the partition operation of quick sort.
• In the Dutch national flag (DNF) problem, write a program that takes an array A and an
index i into A, and rearranges the elements such that all elements less than A[i] (the
"pivot") appear first, followed by elements equal to the pivot, followed by elements
greater than the pivot.
Programme 1:
import java.util.*;
//Creating a List
List<Color> A = new ArrayList<Color>();
for(Color C : A)
System.out.print( C + " ");
dutchFlagPartition(pivotlndex , A);
System.out.println(" ");
Collections.swap(A , i, j);
break ;
}
}
}
Collections.swap(A , i, j);
break ;
}
}
}
}
}
Output:
• The additional space complexity is now O(1), but the time complexity is O(n2)
Programme 2:
import java.util.*;
//Creating a List
List<Color> A = new ArrayList<Color>();
// A.add(WHITE);
dutchFlagPartition(pivotlndex , A);
System.out.println(" ");
System.out.println(" ");
}
}
Output:
Programme 3:
import java.util.*;
//Creating a List
List<Color> A = new ArrayList<Color>();
dutchFlagPartition(pivotlndex , A);
System.out.println(" ");
++equal ;
Output:
• The time spent within each iteration is O(1),implying the time complexity is O(n). The
space complexity is clearly O(1).
Example: if the input is (1,2,9) then you should update the array to (1,3,0).
Approach :
• check If the last element (i.e., Least Significant Digit) is 9, then make it 0 and carry = 1
otherwise make element value + 1.
• For the next digits in the given integer traverse from last digit, check If the element is 9,
then make it 0 and carry = 1 otherwise make element value + 1.
• If the MSD is 10, set current MSD as 0 and need additional digit as the MSD (i.e.,
increase the List size) append 1 in the beginning.
Programme :
import java.util.*;
//Creating a List
List<Integer> A = new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
plusOne(A);
//Traverse from last digit find carry and add to other digit.
for (int i = n; i > 0 && A.get(i) == 10; --i) {
// if the MSD is 10, set current MSD as 0 and need additional digit as
// the MSD (i.e., increase the List size) append 1 in the beginning.
if (A.get (0) == 10) {
return A;
}
}
Output:
Write a program that takes two arrays representing integers, and returns an integer
representing their product.
• Use arrays to represent integers, e.g., with one digit per array entry
• if the inputs are (1,9,3, 7,0,7, 7, 2,1} and (-7,6,1,8,3,8, 2,5,7, 2,8, 7), your function
should return (-1,4, 7,5,7,3, 9,5, 2,5,8, 9,6, 7,6, 4,1, 2, 9, 2,7).
Approach:
• From a space perspective, it is better to incrementally add the terms rather than compute
all of them individually and then add them up.
• The number of digits required for the product is at most n + m for n and m digit operands,
• Example: when multiplying 123 with 987, (All numbers shown are represented using
arrays of digits.)
Programme :
import java.util.*;
//Creating a List
List<Integer> num1 = new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
//Creating a List
List<Integer> num2 = new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
System.out.print(num);
}
}
public static List <Integer> multiply(List <Integer> num1 , List <Integer > num2) {
//if the num1 and num2 are -ve, then make its to +ve,
//by using abs() of element at index 0
num1.set (0 , Math . abs (num1 .get(0)));
num2.set (0 , Math . abs (num2 .get(0)));
//Create result array with size3 and initialize the each cell with zero
int size3 = size1 + size2;
List<Integer> result = new ArrayList <> (Collections.nCopies(size3, 0));
int k = i + j;
++first_not_zero ;
}
result = result. subList (first_not_zero, result . size()) ;
Output:
• we perform O(1) operations on each digit in each partial product. O(m * n),
where m and n are length of two number that need to be multiplied.
Given a sorted array that has some unique as well as some duplicate elements. Write a program
which remove all duplicate elements from the given array and return the array that is not having
any duplicate elements in it.
This problem is concerned with deleting repeated elements from a sorted array.
Since the array is sorted, repeated elements must appear one-after-another, so we do not need an
auxiliary data structure to check if an element has appeared already. We move just one element,
rather than an entire subarray, and ensure that we move it just once.
Example:
• then after deletion of duplicate element, i.e., 5, the array A = [2, 3, 5, 7, 11, 11].
o There are no requirements as to the values stored beyond the last valid element.
Approach:
• We need to modify the array in-place and the size of the final array would potentially be
smaller than the size of the input array. So, we ought to use a two-pointer approach here.
One, that would keep track of the current element in the original array and another one
for just the unique elements.
o Use a separate index in same array for pointing the unique elements.
• Essentially, once an element is encountered, simply need to bypass its duplicates and
move on to the next unique element.
o shift the elements in the array by comparing two adjacent elements, if they are not
equal then consider one as unique and put it at the index pointer’s location and we
will again check the other element with its adjacent one.
• This shifting will help in only having unique elements in the array.
For the given example, (2,3,5,5,7,11), when processing the A[3], since we already have a 5
(which we know by comparing A[3] with A[2]), we advance to A[4], Since this is a new value,
we move it to the first vacant entry, namely A[3]. Now the array is (2,3,5,7,7,11,11,11,13), and
the first vacant entry is A[4]. We continue from A[5],
Programme :
import java.util.*;
//Creating a List
List<Integer> A = new ArrayList<Integer>();
System.out.println(" ");
System.out.println(" ");
if (A.isEmpty()) {
return 0;
}
int writelndex = 1;
for (int i = 1; i < A.size(); ++i) {
A.set(writelndex++, A.get(i));
}
}
return writelndex;
}
}
Output:
• The time complexity is O(n),and the space complexity is O(1), since all that is needed is
the two additional variables.
• In a particular board game, a player has to try to advance through a sequence of positions.
• Each position has a nonnegative integer associated with it, representing the maximum
you can advance from that position in one move.
• You begin at the first position, and win by getting to the last position.
Example:
• Let A = < 3, 3, 1,0, 2, 0, 1 > represent the board game, i.e., the ith entry in A is the
maximum we can advance from i.
• Then the game can be won by the following sequence of advances through A:
o take 1 step from A[0] to A[1],
o then 3 steps from A[l] to A[4],
o then 2 steps from A[4] to A[6], which is the last position.
Example:
• Let A = < 3, 2, 0,0, 2, 0,1> represent the board game, i.e., the ith entry in A is the
maximum we can advance from i.
• Then the game can take the following sequence of advances through A:
o take 3 step from A[0] to A[3],
o The A[3], which contains 0, hence it would not possible to advance past position
3, so the game cannot be won.
• Alternatively:
o take 1 step from A[0] to A[1],
o The A[1], which contains 2, which leads to index 3,
o The A[3], which contains 0, hence it would not possible to advance past position
3, so the game cannot be won.
• Alternatively:
o take 1 step from A[0] to A[1], which contains 2.
o Then take 1 step from A[1], which contains 0, hence it would not possible to
advance past position 3, so the game cannot be won.
Example, let C = < 2,4,1,1,0, 2,3> represent the board game, i.e., the ith entry in C is the
maximum we can advance from i.
• Alternative:
Write a program which takes an array of n integers, where A[i] denotes the maximum you
can advance from index i, and returns whether it is possible to advance to the last index
starting from the beginning of the array.
Approach:
• As iterate through the array, track the furthest index which can advance to.
• The furthest can advance from index i is i + A[i], where i is index processed.
• If, for some i before the end of the array, i is the furthest index that we can advance to,
we cannot reach the last index. Otherwise, we reach the end.
Programme:
import java.util.ArrayList;
import java.util.List;
System.out.println("CASE - 1: ");
//Creating a List
List<Integer> A = new ArrayList<Integer>();
A.add(1);
System.out.println(" ");
if (reach1)
else
System.out.println(" ");
System.out.println(" ");
System.out.println("CASE - 2: ");
//Creating a List
List<Integer> B = new ArrayList<Integer>();
System.out.println(" ");
if (reach2)
else
int furthestReachSoFar = 0;
int lastlndex = maxAdvanceSteps.size() - 1;
furthestReachSoFar = Math.max(furthestReachSoFar,
i + maxAdvanceSteps.get(i));
}
return true;
else
return false;
}
}
Output:
CASE - 1:
The Array of Integer Numbers : 3 3 1 0 2 0 1
possible to reach the last index
CASE - 2:
The Array of Integer Numbers : 3 2 0 0 2 0 1
not possible to reach the last index
• The time complexity is O(n), and the additional space complexity (beyond what is used
for A) is three integer variables, i.e., O(1).
Explanation:
• Suppose an array of integers, i.e., prices = [310, 315, 275, 295, 260, 270, 290, 230,
255, 250]
o The items (array elements), i.e., prices[i] correspond to stock prices of a given
stock on the i+1th day.
• You want to maximize your profit by choosing a single day to buy one stock and
choosing a different day in the future to sell that stock.
o calculates the maximum profit from this transaction (by buying once and selling
once).
• You can only sell a stock on a day after you bought it.
Example:
• In array, prices = [310, 315, 275, 295, 260, 270, 290, 230, 255, 250]
• The maximum profit that can be made with one buy and one sell is 30
• Note:
o 260 is not the lowest price, nor 290 the highest price.
o buying on day 5 (at price 260) and selling on day 2 (at price 315) is not allowed
because you must buy before you sell.
Approach:
• This approach assumes that each item (array elements) present in the given array, i.e.,
prices[i], is the potential selling price for the stock.
• Iterate through array element, keeping track of the minimum element m seen thus far.
• If the difference of the current element and m is greater than the maximum profit
recorded so far, update the maximum profit.
Programme:
import java.util.ArrayList;
import java.util.List;
//Creating a List
List<Double> Prices = new ArrayList<Double>();
System.out.println(" ");
return maxProfit;
}
}
Output:
The Stock Prices : 310.0 315.0 275.0 295.0 260.0 270.0 290.0 230.0 255.0 250.0
Profit : 30.0
• This algorithm performs a constant amount of work per array element, leading to an 0(n)
time complexity. It uses two float-valued variables (the minimum element and the
maximum profit recorded so far) and an iterator, i.e., 0(1) additional space.
Write a program that takes an array denoting the daily stock price, then computes the
maximum profit that can be made by buying and selling a share at most twice. The second
buy must be made on another date after the first sale.
Example:
• In array, prices = [30, 30, 50, 10, 10, 30, 11, 40]
Programme:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
System.out.println(" ");
firstBuySellProfits.add(maxTotalProfit);
}
// Backward phase. For each day, find the maximum profit if we make
// the second buy on that day.
double maxPriceSoFar = Double.MIN_VALUE ;
return maxTotalProfit;
}
}
Output:
Enter the size of the array list : 9
Enter the 9Integers
12
11
13
9
12
8
14
13
15
The Stock Prices : 12.0 11.0 13.0 9.0 12.0 8.0 14.0 13.0 15.0
Profit : 10.0
• The time complexity is 0(n), and the additional space complexity is O(n), which is the
space used to store the best solutions for the subarrays.
Write a program that takes an integer argument and returns all the primes between1 and
that integer.
Example:
• If the input is 10
In brute force approach, we will simply run a loop from 2 to N and for each number in this
range(let say X), we will check whether it is prime or not which will take √X steps for each X in
range(2,N). The complexity of the algorithm comes out to be O(N*√N).
2. Sieve of Eratosthenes
• This approach filter out the composite numbers leaving the prime numbers.
o Take p=2, i.e., if A[p] = true and make all the multiples of 2 in array (indices
which are multiples of 2) as false.
o Increment p and if A[p] = true, then mark all multiples of p in array as false.
o The elements left unmarked (i.e., true) after the above steps in the array are the
prime numbers.
Example: Let say n = 10, it means to find out all the primes less than 10.
o Where T is true and F is false. Entries 0 and 1 are false, since 0 and 1 are not
primes.
• We begin with index 2. Since the corresponding entry is True, we add 2 to the list of
primes, and sieve out its multiples.
• The next nonzero entry is 3, so we add it to the list of primes, and sieve out its multiples.
• The next nonzero entry are 5 and 7, and neither of them can be used to sieve out more
entries.
Programme:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
isPrime.set(j, false);
}
}
}
return Primes;
}
}
Output:
• The time complexity is O(n*log(log(n))) and The space complexity is dominated by the
storage for P, i.e., 0(n).
• Here n! is the factorial, which is the product of all positive integers smaller or equal to n.
Example:
Example:
• Let given array is A = [a, b, c, d] and the permutation can be specified by an array P =
[2, 0, 1, 3]
o Now all elements have been moved according to the permutation, and the result is
[b, c, a, d]
Programme:
import java.util.*;
System.out.println(" ");
System.out.println(" ");
applyPermutation(P, A);
Collections.swap(A , i, P.get(next));
Output:
• The program above will apply the permutation in 0(n) time. The space complexity is
0(1),assumingwecan temporarily modify the sign bit from entries in the permutation
array.
• There exist exactly n\ permutations of n elements. These can be totally ordered using the
dictionary ordering.
Write a program that takes as input a permutation, and returns the next permutation
under dictionary ordering. If the permutation is the last permutation, return the empty
array.
o Find k such that p[k] < p[k + 1] and entries after index k appear in decreasing
order.
o Find the smallest p[l] such that p[l] > p[k] (such an / must exist since p[k]
<p[k+l]).
o Swap p[l] and p[k] (note that the sequence after position k remains in decreasing
order).
Programme:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
System.out.println(" ");
nextPermutation(perm);
int k = perm.size() - 2;
--k;
}
if (k == -1) {
// Swap the smallest entry after index k that is greater than perm[k] . We
// exploit the fact that perm .subList (k + 1, perm.sizeO) is decreasing so
// if we search in reverse order, the first entry that is greater than
// perm[k ] is the smallest such entry.
for (int i = perm.size() - 1; i > k; --i) {
Collections.swap(perm, k, i);
break ;
}
}
Output:
• Each step is an iteration through an array, so the time complexity is O(n). All that we use
are a few local variables, so the additional space complexity is O(1).
• The size of a sample is always less than the size of the whole data set from which it is
taken.
Implement an algorithm that takes as input an array of distinct elements and a size, and
returns a subset of the given size of the array elements. All subsets should be equally likely.
Return the result in input array itself.
Approach:
• In first iteration, generate one random number between 0 to A.length; let the random
number is r, then swap A[0] with A[r], The entry A[0] now partn of the result.
• In second iteration, generate one random number between 1 to A.length; let the random
number is s. then swap A[1] with A[s], The entry A[1] now part of the result.
• Repeat the above procedure k times. Eventually, the random subset occupies the slots
A[0 : k - 1] and the remaining elements are in the last n-k slots.
• Return the result (i.e, A[0 : k - 1]) in the same input array .
Example:
• let the input is A = [3, 7,5,11] and the size be 3 (the sample size is 3).
• The random subset consists of the first three entries, i.e., [5,11,3].
Programme:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
System.out.println(" ");
randomsampling(k, A);
Output:
• The algorithm clearly runs in additional 0(1) space. The time complexity is 0(k) to select
the elements.
• Here, randomly choosing k samples from a list of n items, where n is either a very large
or unknown number.
• Typically n is large enough that the list doesn’t fit into main memory.
Design a program that takes as input a size k,and reads packets, continuously maintaining
a uniform random subset of size k of the read packets.
Algorithm:
• Now one by one consider all items from (k+1)th item to nth item.
Programme:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
System.out.println(" ");
Iterator B = A.iterator();
runningSample.add(sequence.next());
}
while (sequence.hasNext()){
Integer x = sequence.next();
++numSeenSoFar ;
if (idxToReplace < k) {
runningSample.set(idxToReplace, x);
}
}
return runningSample;
}
Output:
• The time complexity is proportional to the number of elements in the stream, since we
spend 0(1) time per element, hence the Time complexity is O(n). The space complexity is
0(k).
• The use of random permutations is often fundamental to fields that use randomized
algorithms such as coding theory, cryptography, and simulation.
Example:
o Suppose it is1.
o We update the array by swapping A[0] with A[1]. Hence the Updated array is
A[1,0, 2,3].
Programme:
package ComputeRandomPermutaion;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
}
}
public static List<Integer> computeRandomPermutation(int n) {
permutation . add(i) ;
}
return permutation;
}
}
package ComputeRandomPermutaion;
import java.util.Collections;
import java.util.List;
import java.util.Random;
//
for (int i = 0; i < k; ++i) {
Output:
• The time complexity is 0(n), and, as an added bonus, no storage outside of that needed
for the permutation array itself is needed.
Example:
• Create a HashMap H, which is empty. In HasMap H whose keys and values are from
(0,1, …, n-1).
Let n be the total number of elements in array and k is the subset size. Here k < = n.
Here, n =5 and k = 3.
• To selct one subset randomly from the k subset, we need to perform k iteration.
• The random subset is the 3 elements corresponding to indices 0,1, 2, i.e., [4, 0, 3].
Programme:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
changedElements.put(randldx , i);
changedElements.put(i, randldx);
changedElements.put(randldx , ptr2);
changedElements.put(i, randldx);
changedElements.put(i , ptrl);
changedElements.put(randldx , i);
} else {
changedElements.put(i , ptrl);
changedElements.put(randldx , ptr2);
}
result.add(changedElements.get(i));
}
return result ;
}
}
Output:
• The time complexity is O(k), since we perform a bounded number of operations per
iteration. The space complexity is also O(k), since H and the result array never contain
more than k entries.
You are given n numbers as well as probabilities po, p1, … pn , which sum up to 1. Given a
random number generator that produces values in [0,1] uniformly, how would you
generate one of the n numbers according to the specified probabilities?
Approach:
• You are given n numbers as well as probabilities po, p1, … pn , which sum up to 1.
• For the case where the probabilities are not same, the problem can be solved by
partitioning the interval [0, 1] into n disjoint segments.
• To create these intervals is to use p0, p0+p1, p0+p1+p2, … , p0+p1+p2+ … +Pn-1 as the
endpoints.
o Here the interval array < p0, p0+p1, p0+p1+p2, … , p0+p1+p2+ … +Pn-1 > is
sorted.
• Find the index of the interval that randomly generated number falls in.
o use the searching technique, i.e., the interval array is sorted, hence use Binary
search.
• Return the number corresponding to the interval the randomly generated number falls in.
Example:
• Let n numbers as well as probabilities po, p1, … pn are given, the sum of the probabilities
is up to 1.
• If numbers are 3, 5, 7, 11, and the probabilities are 9/18, 6/18, 2/18, 1/18
• To create these intervals is to use p0, p0+p1, p0+p1+p2, … , p0+p1+p2+ … +Pn-1 as the
endpoints. Here the interval array < p0, p0+p1, p0+p1+p2, … , p0+p1+p2+ … +Pn-1 > is
sorted.
o the four intervals are [0.0, 5.0], [0.5, 0.0.8333), [0.833, 0.944), [0.944,
1.0].
• Use the searching technique, i.e., binary search to find the index of the interval that
randomly generated number falls in.
o science o.873 lies in [0.833, 0.944), which is the 3rd interval (i.e., index 2) in
intervalarray = [0.0, 0.5, 0.833, 0.944, 0.999]
• Return the number corresponding to the interval the randomly generated number falls in.
o return the third number (i.e., elemet at index 2) in values = [3, 5, 7, 11], which is
7.
Programme:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
prefixSumofprobabilities.add(
prefixSumofprobabilities.get(prefixSumofprobabilities.size() - 1) + p);
if(it < 0) {
} else {
return values.get(it) ;
}
}
}
Output:
• The time complexity to compute a single value is O(n),which is the time to create the
array of intervals. This array also implies an O(n) space complexity. Once the array is
constructed, computing each additional result entails one call to the uniform random
number generator, followed by a binary search, i.e., O(log n).
ROTATE A 2D ARRAY
Write a function that takes as input an n X n 2D array, and rotates the array by 90 degrees
clockwise.
Brute-force approach
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
• writing rows of the original matrix into the columns of the new matrix B.
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
Alternate Approach:
o Example:
▪ In Layer 1:
• send 1 to 4's location
• send 4 to 16's location
• send 16 to 13's location
• send 13 to 1's location
▪ In Layer 2:
• send 2 to 8's location,
• send 8 to 15's location
• send 15 to 9's location
Programme:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*Declaring 2D ArrayList<E>*/
ArrayList<ArrayList<Integer>> squareMatrix =
new ArrayList<ArrayList<Integer>>();
System.out.println();
}
rotateMatrix(squareMatrix);
System.out.println();
}
}
squareMatrix.get(i).set(j, temp1);
squareMatrix.get(j).set(matrixSize - i, temp4);
}
}
}
}
Output:
• The time complexity is O(n2) and the additional space complexity is O(1).
1. Put a 1 at the top of the triangle. Each row will have one entry more than the previous
row.
3. In each spot of a row enter the sum of the two entries immediately above to the left and to
the right in the previous row.
4. Because each row is built from the previous row by step 3, the rows are symmetric (i.e.
reversing the row produces the same numbers).
Write a program which takes as input a nonnegative integer n and returns the first n rows
of Pascal's triangle.
Approach:
o Otherwise, it is the sum of the (j- l)th and jth entries in the (i- l)th row.
Example:
• The fourth row R3 is < l, R2[0] + R2[l] =3, R2[1] + R2[2] = 3,1 >.
• The fifth row R4 is < l, R3[0] + R3[l] = 4, R3[1] + R3[2] = 6, R3[2] + R3[3] = 4, 1 >.
Programme
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*Declaring 2D ArrayList<>*/
List<List<Integer>> PascalTriangle = new ArrayList<List<Integer>>();
PascalTriangle = generatePascalTriangle(numRows);
System.out.println();
}
}
/*Declaring 2D ArrayList<>*/
List<List<Integer>> pascalTriangle = new ArrayList<>();
currRow.add(pascalTriangle.get(i - 1).get(j - 1)
+ pascalTriangle.get(i - 1).get(j));
else
currRow.add(1);
}
pascalTriangle.add(currRow);
}
return pascalTriangle ;
}
}
Output:
121
1331
14641
• Since each element takes O(1) time to compute, the time complexity is O(1+ 2+ …+ n) =
O(n(n + l)/2) = O(n2). Similarly, the space complexity is 0(n2).
What is Sudoku?
• Sudoku is a number-placement puzzle where the objective is to fill a square grid of size
’n’ with numbers between 1 to ’n’.
• The numbers must be placed so that each column, each row, and each of the sub-grids (if
any) contains all of the numbers from 1 to ‘n’.
• The most common Sudoku puzzles use a 9x9 grid. The grids are partially filled (with
hints) to ensure a solution can be reached.
Problem Description: You are given a Sudoku puzzle and you need to fill the empty cells
without violating any rules. A sudoku solution must satisfy all of the following rules:
• Each of the digits 1-9 must occur exactly once in each row.
• Each of the digits 1-9 must occur exactly once in each column.
• Each of the digits 1-9 must occur exactly once in each of the 3x3 sub-boxes of the grid.
Problem Note:
Algorithm
• Check if the rows and columns contain values 1-9, without repetition.
• If any row or column violates this condition, the Sudoku board is invalid.
• Check to see if each of the 9 sub-squares contains values 1-9, without repetition. If they
do, the Sudoku board is valid; otherwise, it is invalid.
Programme:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
System.out.println();
}
if(result){
else{
if (hasDuplicate(partialAssignment , i, i + 1, 0, partialAssignment.size())){
return false;
}
}
return false;
}
}
if (hasDuplicate(partialAssignment , regionSize * I,
regionSize * (I + 1), regionSize * J, regionSize * (J + 1))) {
return false;
}
}
}
return true ;
}
//This function takes one set at a time and checks if there is a duplicate in it.
// First it creates a boolean array of size 9 and then starts iterating through
//all the records for every digit it checks if that digit is already set to true
//in the array if yes then that means there is a duplicate if not, it sets that
//digit to true
private static boolean hasDuplicate (List <List<Integer>> partialAssignment, int
startRow, int endRow, int startCol, int endCol ) {
if (partialAssignment.get(i).get(j) != 0 &&
isPresent.get(partialAssignment.get(i).get (j))) {
return true ;
}
isPresent.set(partialAssignment.get(i).get(j), true);
}
}
return false;
}
}
Output:
The time complexity of this algorithm for an nXn Sudoku grid with n X n subgrids is O(n2) +
O(n2) + O(n2/(√n)2X(√n)2) = 0(n2); the terms correspond to the complexity to check n row
constraints, the n column constraints, and the n subgrid constraints, respectively. The memory
usage is dominated by the bit array used to check the constraints, so the space complexity is 0(n).
• row-by-row
• column-by-column
• spiral order.
Example:
Write a program which takes an nxn 2D array and returns the spiral ordering of the array.
Programme:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*Declaring 2D ArrayList<E>*/
List<List<Integer>> squareMatrix = new ArrayList<List<Integer>>();
System.out.println();
}
spiralOrdering = matrixInSpiralOrder(squareMatrix);
return spiralOrdering ;
}
return ;
}
spiralOrdering.add(squareMatrix.get(offset).get(j));
}
spiralOrdering.add(squareMatrix.get(i).get(offset));
}
}
}
Output: