Unit I
Unit I
Unit-1
Syllabus
The Sliding window is a problem-solving technique of data structure and algorithm for problems
that apply arrays or lists. These problems are painless to solve using a brute force approach
in O(n²) or O(n³). However, the Sliding window technique can reduce the time complexity
to O(n).
The basic idea behind the sliding window technique is to transform two nested loops into a single
loop.
➢ It will ask to find subrange in that array or string will have to give longest, shortest, or target
values.
➢ Its concept is mainly based on ideas like the longest sequence or shortest sequence of
something that satisfies a given condition perfectly.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
➢ Find the size of the window on which the algorithm has to be performed.
➢ Calculate the result of the first window, as we calculate in the naive approach.
➢ Then run a loop and keep sliding the window by one step at a time and also sliding that pointer
one at a time, and keep track of the results of every window.
OR
➢ Take hashmap or dictionary to count specific array input and uphold on increasing the window
towards right using an outer loop.
➢ Take one inside a loop to reduce the window side by sliding towards the right. This loop will
be very short.
➢ Store the current maximum or minimum window size or count based on the problem statement.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
[ 5, 7, 1, 4, 3, 6, 2, 9, 2 ]
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Example: Given an array as input, extract the pair of contiguous integers that have the
highest sum of all pairs. Return the pair as an array.
➢ Contiguous means sequential, which means the elements must be right next to each other to
count as a pair. This is a giant clue that a sliding window may work beautifully with this
question.
➢ In the context of this question, contiguous also means that one cannot simply sort the array
and return the last two integers in an array, since we want the pair of contiguous integers
which have the highest sum in the array as it is already ordered.
For this question, take the input [5, 2, 4, 6, 3, 1] as the input.
➢ The sliding window will not be explained thoroughly here but it will be in the next section.
This part serves as a visual introduction with light notes. The following picture is of the first
iteration of the sliding window for this problem.
➢ The window has a red border and a mint background. The current sum of the pair, [5,2] is
7. Continue iterating through the entire array to see if that’s still the highest sum. One
must slide the window up by 1 to reach the next iteration.
➢ This window’s pair is the highest so far. Keep track of that and compare it to the last two
iterations.
➢ This iteration’s pair definitely was not the highest. After all the iterations, the highest sum
pair was [4, 6].
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
➢ The number of iterations is worth noticing here: the number of iterations was 5, which ranks
the sliding window solution for this problem slightly faster than O(n). For small and large
inputs, linear time is an ideal goal.
➢ Now that the mental model is starting to form, one may be wondering how to recognize
problems that can use a sliding window successfully.
In general, any problem where the author is asking for any of the following return values can use a
sliding window:
➢ Minimum value
➢ Maximum value
➢ Longest value
➢ Shortest value
➢ K-sized value
In case the length of the ranges is fixed, we call this the fixed-size sliding window technique.
However, if the lengths of the ranges are changed, we call this the flexible window size technique.
We’ll provide examples of both of these options.
Applications:
1. Naive Approach.
2. Diet Plan Performance.
3. Distinct Numbers in Each Subarray.
4. Kth Smallest Subarray Sum.
5. Maximum of all subarrays of size k.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
1. Naive Approach
Fixed-Size Sliding Window
Let’s look at an example to better understand this idea.
i. The Problem:
Suppose the problem gives us an array of length ‘n’ and a number ‘k’. The problem asks us to
find the maximum sum of ‘k’ consecutive elements inside the array.
In other words, first, we need to calculate the sum of all ranges of length ‘k’ inside the array. After
that, we must return the maximum sum among all the calculated sums.
➢ First, we iterate over all the possible beginnings of the ranges. For each range, we iterate
over its elements from L to L+K-1 and calculate their sum. After each step, we update the
best answer so far. Finally, the answer becomes the maximum between the old answer and
the currently calculated sum.
➢ In the end, we return the best answer we managed to find among all ranges.
➢ The time complexity is O(n²) in the worst case, where ‘n’ is the length of the array.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Firstly, we calculate the sum for the first range which is [1,K]. Secondly, we store its sum as the
answer so far.
After that, we iterate over the possible ends of the ranges that are inside the range [k+1,n]. In each
step, we update the sum of the current range. Hence, we add the value of the element at index and
delete the value of the element at index ‘i -k’.
Every time, we update the best answer we found so far to become the maximum between the
original answer and the newly calculated sum. In the end, we return the best answer we found
among all the ranges we tested.
The time complexity of the described approach is O(n), where ‘n’ is the length of the array.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
i. Problem:
Suppose we have ‘n’ books aligned in a row. For each book, we know the number of minutes
needed to read it. However, we only have ‘k’ free minutes to read.
Also, we should read some consecutive books from the row. In other words, we can choose a range
from the books in the row and read them. Of course, the condition is that the sum of time needed
to read the books mustn’t exceed ‘k’.
Therefore, the problem asks us to find the maximum number of books we can read. Namely, we
need to find a range from the array whose sum is at most ‘k’ such that this range’s length is
the maximum possible.
ii. Naive Approach:
Take a look at the naive approach for solving the problem:
➢ First, we initialize the best answer so far with zero. Next, we iterate over all the possible
beginnings of the range. For each beginning, we iterate forward as long as we can read
more books. Once we can’t read any more books, we update the best answer so far as the
maximum between the old one and the length of the range we found.
➢ In the end, we return the best answer we managed to find.
➢ The complexity of this approach is O(n²) , where ‘n’ is the length of the array of books.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
We’ll try to improve the naive approach, in order to get a linear complexity.
First, let’s assume we managed to find the answer for the range that starts at the beginning of the
array. The next range starts from the second index inside the array. However, the end of the second
range is surely after the end of the first range.
The reason for this is that the second range doesn’t use the first element. Therefore, the second
range can further extend its end since it has more free time now to use.
Therefore, when moving from one range to the other, we first delete the old beginning from the
current answer. Also, we try to extend the end of the current range as far as we can.
Hence, by the end, we’ll iterate over all possible ranges and store the best answer we found.
The following algorithm corresponds to the explained idea:
Just as with the naive approach, we iterate over all the possible beginnings of the range. For each
beginning, we’ll first subtract the value of the index L-1 from the current sum.
After that, we’ll try to move ‘R’ as far as possible. Therefore, we continue to move ‘R’ as long as
the sum is still at most ‘K’. Finally, we update the best answer so far. Since the length of the current
range is R-L, we maximize the best answer with this value.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Although the algorithm may seem to have a O(n²) complexity, let’s examine the algorithm
carefully. The variable ‘R’ always keeps its value. Therefore, it only moves forward until it reaches
the value of ‘n’.
Therefore, the number of times we execute the while loop in total is at most ‘n’ times.
Hence, the complexity of the described approach is O(n), where ‘n’ is the length of the array.
Differences:
The main difference comes from the fact that in some problems we are asked to check a certain
property among all range of the same size. On the other hand, on some other problems, we are
asked to check a certain property among all ranges who satisfy a certain condition. In these cases,
this condition could make the ranges vary in their length.
In case these ranges had an already known size (like our consecutive elements problem), we’ll
certainly go with the fixed-size sliding window technique. However, if the sizes of the ranges were
different (like our book-length problem), we’ll certainly go with the flexible-size sliding window
technique.
Also, always keep in mind the following condition to use the sliding window technique that we
covered in the beginning: We must guarantee that moving the L pointer forward will certainly
make us either keep R in its place or move it forward as well.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Given an integer k, for every consecutive sequence of k days (calories[i], calories[i+1], ...,
calories[i+k-1] for all 0 <= i <= n-k), they look at T, the total calories consumed during that
sequence of k days (calories[i] + calories[i+1] + ... + calories[i+k-1]):
• If T < lower, they performed poorly on their diet and lose 1 point;
• If T > upper, they performed well on their diet and gain 1 point;
• Otherwise, they performed normally and there is no change in points.
Initially, the dieter has zero points. Return the total number of points the dieter has after
dieting for calories.length days.
Note that the total points can be negative.
Example 1:
Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3
Output: 0
Explanation: Since k = 1, we consider each element of the array separately and compare it to
lower and upper.
calories[0] and calories[1] are less than lower so 2 points are lost.
calories[3] and calories[4] are greater than upper so 2 points are gained.
Example 2:
Input: calories = [3,2], k = 2, lower = 0, upper = 1
Output: 1
Explanation: Since k = 2, we consider subarrays of length 2.
calories[0] + calories[1] > upper so 1 point is gained.
Example 3:
Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5
Output: 0
Explanation:
calories[0] + calories[1] > upper so 1 point is gained.
lower <= calories[1] + calories[2] <= upper so no change in points.
calories[2] + calories[3] < lower so 1 point is lost.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Constraints:
• 1 <= k <= calories.length <= 10^5
• 0 <= calories[i] <= 20000
• 0 <= lower <= upper
Solution
➢ Use the idea of sliding window. Initially, calculate the calories consumed during the first
consecutive k days, which is calories[0] + calories[1] + ... + calories[k - 1]. Let sum be the
calories consumed during the first consecutive k days.
➢ If sum < lower, then lose 1 point.
➢ If sum > upper, then gain 1 point.
➢ Each time, remove the first element from the window and add the next element into the
window and calculate the sum, and decide whether the point is increased, decreased or
unchanged.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
DietPlanPerformance.java
import java.util.*;
class DietPlanPerformance
{
public int dietPlanPerformance(int[] calories, int k, int lower, int upper)
{
int points = 0;
int sum = 0;
for (int i = 0; i < k; i++)
sum += calories[i];
if (sum > upper)
points++;
else if (sum < lower)
points--;
int length = calories.length;
for (int i = k; i < length; i++)
{
sum += calories[i];
sum -= calories[i - k];
if (sum > upper)
points++;
else if (sum < lower)
points--;
}
return points;
}
int n=sc.nextInt();
int calories[]=new int[n];
for(int i=0;i<n;i++)
{
calories[i]=sc.nextInt();
}
int k=sc.nextInt();
int l=sc.nextInt();
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
int u=sc.nextInt();
System.out.println(new
DietPlanPerformance().dietPlanPerformance(calories,k,l,u));
}
}
Test Case-1
input=6
654321
416
output=3
Test Case-1
input=10
9 18 27 36 45 54 63 72 81 90
5 72 81
output=6
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Example 1:
Input: nums = [1,2,3,2,2,1,3], k = 3
Output: [3,2,2,2,3]
Explanation: The number of distinct elements in each subarray goes as follows:
- nums[0:2] = [1,2,3] so ans[0] = 3
- nums[1:3] = [2,3,2] so ans[1] = 2
- nums[2:4] = [3,2,2] so ans[2] = 2
- nums[3:5] = [2,2,1] so ans[3] = 2
- nums[4:6] = [2,1,3] so ans[4] = 3
Example 2:
Input: nums = [1,1,1,1,2,3,4], k = 4
Output: [1,2,3,4]
Explanation: The number of distinct elements in each subarray goes as follows:
- nums[0:3] = [1,1,1,1] so ans[0] = 1
- nums[1:4] = [1,1,1,2] so ans[1] = 2
- nums[2:5] = [1,1,2,3] so ans[2] = 3
- nums[3:6] = [1,2,3,4] so ans[3] = 4
Constraints:
• 1 <= k <= nums.length <= 105
• 1 <= nums[i] <= 105
The time complexity to O(n) by using the sliding window technique
The idea is to store the frequency of elements in the current window in a map and keep track of
the distinct elements count in the current window (of size k ). The code can be optimized to
derive the count of elements in any window using the count of elements in the previous window
by inserting the new element to the previous window from its right and removing an element
from its left.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Java Program for Distinct Numbers in Each Subarray using Sliding Window Technique:
DistinctCount.java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class DistinctCount
{
// Function to find the count of distinct elements in every subarray/ of size `k` in the array
public static void findDistinctCount(int[] A, int k)
{
// map to store the frequency of elements in the current window of size `k`
Map<Integer, Integer> freq = new HashMap<>();
/* increment distinct count by 1 if element occurs for the first time in the
current window */
if (freq.get(A[i]) == 1)
{
distinct++;
}
if (i >= k - 1)
{
System.out.println(distinct);
}
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int array[]=new int[n];
int k=sc.nextInt();
for(int i=0;i<n;i++)
{
array[i]=sc.nextInt();
}
findDistinctCount(array, k);
}
}
Test Case-1:
Input: 7 3
2343324
Output : 3 2 2 2 3
Test Case-2:
Input =15 4
415323423133243
Output =4 4 3 3 3 3 4 3 2 3 3 3
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Constraints:
• n == nums.length
• 1 <= n <= 2 * 10^4
• 1 <= nums[i] <= 5 * 10^4
• 1 <= k <= n * (n + 1) / 2
Solution
Use binary search. The maximum subarray sum is the sum of all elements in nums and the
minimum subarray sum is the minimum element in nums. Initialize high and low as the maximum
subarray sum and the minimum subarray sum. Each time let mid be the mean of high and low and
count the number of subarrays that have sum less than or equal to mid, and
adjust high and low accordingly. Finally, the k-th smallest subarray sum can be obtained.
To count the number of subarrays that have sum less than or equal to mid, use sliding window
over nums and for each index, count the number of subarrays that end at the index with sum less
than or equal to mid.
Write a java Program for Kth Smallest Subarray Sum using Sliding Window Technique:
KthSmallestSubarraySum.java
import java.util.*;
class KthSmallestSubarraySum
{
public int kthSmallestSubarraySum(int[] nums, int k)
{
int min = Integer.MAX_VALUE, sum = 0;
for (int num : nums)
{
min = Math.min(min, num);
sum += num;
}
int low = min, high = sum;
while (low < high)
{
int mid = (low+high) / 2 ;
int count = countSubarrays(nums, mid);
if (count < k)
low = mid + 1;
else
high = mid;
}
return low;
}
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
int n=sc.nextInt();
int array[]=new int[n];
int k=sc.nextInt();
for(int i=0;i<n;i++)
array[i]=sc.nextInt();
System.out.println( new
KthSmallestSubarraySum().kthSmallestSubarraySum(array, k));
}
}
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Test Case1:
Input:
34
324
Output:
5
Explanation:
------------
The subarrays of 3 2 4 are:
1st subarray: 3 the sum is 3
2nd subarray: 2 the sum is 2
3rd subarray: 4 the sum is 4
4th subarray: 3,2 the sum is 5
5th subarray: 2,4 the sum is 6
6th subarray: 3,2,4 the sum is 9
Example-3
Input: a[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, k = 3
Output: 3 3 4 5 5 5 6
Explanation:
Maximum of subarray {1, 2, 3} is 3
Maximum of subarray {2, 3, 1} is 3
Maximum of subarray {3, 1, 4} is 4
Maximum of subarray {1, 4, 5} is 5
Maximum of subarray {4, 5, 2} is 5
Maximum of subarray {5, 2, 3} is 5
Maximum of subarray {2, 3, 6} is 6
Solution:
This problem is a variant of the problem First negative number in every window of size k.
If you closely observe the way we calculate the maximum in each k-sized subarray, you will notice
that we’re doing repetitive work in the inner loop. Let’s understand it with an example:
Input: a[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}, k = 3
For the above example, we first calculate the maximum in the subarray {1, 2, 3}, then we move
on to the next subarray {2, 3, 1} and calculate the maximum. Notice that, there is an overlap in
both the subarrays:
123
231
So, we’re calculating the maximum in the overlapping part (2, 3) twice. We can utilize the sliding
window technique to save us from re-calculating the maximum in the overlapping subarray and
improve the run-time complexity.
In the sliding window technique, we consider each k-sized subarray as a sliding window. To
calculate the maximum in a particular window (2, 3, 1), we utilize the calculation done for the
previous window (1, 2, 3).
Since we want to utilize the calculation from the previous window, we need a way to store the
calculation for the previous window. We’ll use a PriorityQueue to store the elements of the sliding
window in decreasing order (maximum first).
The remaining explanation is same as the previous problem we solved using the same
technique: First negative number in every window of size k.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Java Program for Maximum of all subarrays of size k using Sliding Window Technique:
MaxOfAllSubarraysOfSizeK.java
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
if(maxElement == a[windowStart])
{
/* Discard a[windowStart] since we are sliding the window
now. So, it is going out of the window.*/
q.remove();
}
Test Case-1
Input:9
123145236
3
Output:3 3 4 5 5 5 6
Test Case-2
input=8
1 5 7 2 8 18 12 10
2
output=5 7 7 8 18 18 12
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
➢ The two-pointer method is a helpful technique to keep in mind when working with strings
and arrays.
➢ It's a clever optimization that can help reduce time complexity with no added space
complexity (a win-win!) by utilizing extra pointers to avoid repetitive operations.
➢ Many questions involving data stored in arrays or linked lists ask us to find sets of data that
fit a certain condition or criterion.
➢ Enter two pointers: we could solve these problems by brute force using a single iterator,
but this often involves nesting loops, which increases the time complexity of a solution
exponentially.
➢ Instead, we can use two pointers, or iterator variables, to track the beginning and end of
subsets within the data, and then check for the condition or criterion.
Statement:
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order,
find two numbers such that they add up to a specific target number. Let these two numbers be
numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array
[index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element
twice.
Example 1:
Example 2:
Example 3:
Pseudocode
function(array, target)
{
set a left pointer to the first element of the array
set a right pointer to the last element of the array
loop through the array; check if left and right add to target
if sum is less than the target, increase left pointer
if sum is greater than the target, decrease right pointer
once their sum equals the target, return their indices
}
The pseudo code illustrates the most classic case of a two-pointer problem, where the pointers
start out as the ends of a sorted array. In this case, we are looking for two members of an array to
add to a specific target value.
Java code for Two Sum Problem with Sorted Input Array using Two pointer Approach:
class TwoSum
{
public static int[] twoSum(int[] numbers, int target)
{
int slow = 0, fast = numbers.length - 1;
while(slow < fast)
{
int sum = numbers[slow] + numbers[fast];
if(sum == target)
return new int[]{slow + 1, fast + 1};
else if(sum < target)
slow++;
else
fast--;
}
return new int[]{-1, -1};
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<n;i++)
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
arr[i]=sc.nextInt();
int k = sc.nextInt();
System.out.println(Arrays.toString(twoSum(arr, k)));
}
}
Given an array, rotate the array to the right by k steps, where k is non-negative. For example, if
our input array is [1, 2, 3, 4, 5, 6, 7] and k is 4, then the output should be [4, 5, 6, 7, 1, 2, 3].
We can solve this by having two loops again which will make the time complexity O(n^2) or by
using an extra, temporary array, but that will make the space complexity O(n).
Let's solve this using the two-pointer technique instead:
import java.util.*;
public class ArrayRotation
{
public static void rotateArray(int[] arr, int k)
{
if (arr == null || arr.length <= 1 || k % arr.length == 0)
return;
int n = arr.length;
k = k % n;
reverse(arr, 0, n - 1); // Reverse the whole array
reverse(arr, 0, k - 1); // Reverse the first k elements
reverse(arr, k, n - 1); // Reverse the remaining elements
}
public static void reverse(int[] arr, int start, int end)
{
while (start < end)
{
// Swap elements at start and end positions
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move the pointers towards the center
start++;
end--;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
int k = sc.nextInt();
rotateArray(arr, k);
System.out.println(Arrays.toString(arr));
}
}
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
test cases
case =1
input=12
1 2 3 4 5 6 7 8 9 10 11 12
2
output=[11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
case =2
input=9
987654321
0
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
import java.io.*;
class MiddleOftheLinkedList
{
Node head;
// Linked list node
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
// This function prints the contents of the linked list starting from the given node
public void printList()
{
Node tnode = head;
while (tnode != null) {
System.out.print(tnode.data + "->");
tnode = tnode.next;
}
System.out.println("NULL");
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String list[]=sc.nextLine().split(" ");
int val;
MiddleOftheLinkedList llist = new MiddleOftheLinkedList();
for (int i = 0; i < list.length; i++)
{
llist.push(Integer.parseInt(list[i]));
}
//llist.printList();
llist.printMiddle();
}
}
Test Cases:
case =1
input= 5 10 20 15 25 12 30 35 32
output=25
case =2
input=1 2 3 4 5 6 7 8 9
output= 5
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
APPLICATIONS:
1. Palindrome Linked List.
2. Find the Closest pair from two sorted arrays.
3. Valid Word Abbreviation.
Example 1:
Input:
head = [1,2,2,1]
Output:
true
Example 2:
Input:
head = [1,2]
Output:
false
PalindromeLinkedList.java
import java.util.*;
class Node
{
int data;
Node next;
class Solution
{
//Function to check whether the list is palindrome.
Node getmid (Node head)
{
Node slow = head ;
Node fast = head.next ;
while(curr != null)
{
next = curr.next ;
curr.next = prev ;
prev = curr ;
curr = next ;
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
}
return prev ;
}
while(head2 != null)
{
if(head1.data != head2.data)
{
return false;
}
head1 = head1.next;
head2 = head2.next;
}
temp = middle.next;
middle.next = reverse(temp);
return true ;
}
}
}
else
{
tail.next = newNode;
tail = newNode;
}
}
case =2
input =1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1
output =True
case =3
input =1 2 3 4 5 6 7 8 9 8 9 7 6 5 4 3 2 1
output =false
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Example-1:
Example-2:
1. Merge given two arrays into an auxiliary array of size m+n using merge process of merge
sort. While merging keeps another boolean array of size m+n to indicate whether the current
element in merged array is from ar1[] or ar2[].
2. Consider the merged array and use the linear time algorithm to find the pair with sum closest
to x. One extra thing we need to consider only those pairs which have one element from ar1[]
and other from ar2[], we use the boolean array for this purpose.
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
The idea is to start from left side of one array and right side of another array, and use the
algorithm same as step 2 of above approach. Following is detailed algorithm.
1) Initialize a variable diff as infinite (Diff is used to store the difference between pair and x).
We need to find the minimum diff.
2) Initialize two index variables l and r in the given sorted array.
(a) Initialize first to the leftmost index in ar1: l = 0
(b) Initialize second the rightmost index in ar2: r = n-1
3) Loop while l< length.ar1 and r>=0
(a) If abs(ar1[l] + ar2[r] - sum) < diff then
update diff and result
(b) If (ar1[l] + ar2[r] < sum ) then l++
(c) Else r--
4) Print the result.
Java program to find closest pair in an array using Two pointer approach:
ClosestPair.java
import java.util.*;
class ClosestPair
{
/* arr1[0..m-1] and arr2[0..n-1] are two given sorted arrays/ and x is given number. This
function prints the pair from both arrays such that the sum of the pair is closest to x.*/
void printClosest(int ar1[], int ar2[], int m, int n, int x)
{
// Initialize the diff between pair sum and x.
int diff = Integer.MAX_VALUE;
// res_l and res_r are result indexes from ar1[] and ar2[] respectively
int res_l = 0, res_r = 0;
// Start from left side of ar1[] and right side of ar2[]
int l = 0, r = n-1;
while (l<m && r>=0)
{
/* If this pair is closer to x than the previously found closest, then update
res_l, res_r and diff*/
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
Input:
enter size of array_1
4
enter the values of array_1
1 8 10 12
enter size of array_2
4
enter the values of array_2
2 4 9 15
enter closest number
11
Output:
The closest pair is [1, 9]
COMPETITIVE PROGRAMMING UNIT-I III –II SEM(KR21)
["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2",
"2r1", "3d", "w3", "4"]
Notice that only the above abbreviations are valid abbreviations of the string "word". Any other
string is not a valid abbreviation of "word".
Note: Assume s contains only lowercase letters and abbr contains only lowercase letters and
digits.
Example 1:
Return true.
Example 2:
Return false.
Java program for Valid Word Abbreviation using Two Pointer approach:
ValidWordAbbreviation.java
import java.util.*;
class ValidWordAbbreviation
{
public boolean validWordAbbreviation(String word, String abbr)
{
int i = 0, j = 0;
while (i < word.length() && j < abbr.length())
{
if (word.charAt(i) == abbr.charAt(j))
{
++i;
++j;
continue;
}
if (abbr.charAt(j) <= '0' || abbr.charAt(j) > '9')
{
return false;
}
int start = j;
while (j < abbr.length() && abbr.charAt(j) >= '0'&&abbr.charAt(j) <= '9')
{
++j;
}
int num = Integer.valueOf(abbr.substring(start, j));
i += num;
}
return i == word.length() && j == abbr.length();
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter word");
System.out.println(new
ValidWordAbbreviation().validWordAbbreviation(word,abbrv));
}
}
Case-1:
input=
Enter word
kmit
Enter Abbreviation
4
output=true
Case=2
input=
Enter word
Diary
Enter Abbreviation
d2ary
output=false