1.Array Subset of another array
Given two arrays: a1[0..n-1] of size n and a2[0..m-1] of size m. Task is to check whether a2[] is a subset of a1[] or not. Both the arrays can be sorted or unsorted. It may be assumed that elements in both array are distinct.
Example 1:
Input:
a1[] = {11, 1, 13, 21, 3, 7}
a2[] = {11, 3, 7, 1}
Output:
Yes
Explanation:
a2[] is a subset of a1[]\
Example 2:
Input:
a1[] = {1, 2, 3, 4, 5, 6}
a2[] = {1, 2, 4}
Output:
Yes
Explanation:
a2[] is a subset of a1[]
Example 3:
Input:
a1[] = {10, 5, 2, 23, 19}
a2[] = {19, 5, 3}
Output:
No
Explanation:
a2[] is not a subset of a1[]
class Compute {
public String isSubset( long a1[], long a2[], long n, long m) {
HashSet<Long> set = new HashSet<>();
for(long i : a1){
set.add(i);
}
int count =0;
for(int i = 0; i<m; i++){
if(set.contains(a2[i])) count++;
}
if(count == m) return "Yes";
else return "No";
}
}
2.Implement two stacks in an array
Your task is to implement 2 stacks in one array efficiently.
Example 1:
Input:
push1(2)
push1(3)
push2(4)
pop1()
pop2()
pop2()
Output:
3 4 -1
Explanation:
push1(2) the stack1 will be {2}
push1(3) the stack1 will be {2,3}
push2(4) the stack2 will be {4}
pop1() the poped element will be 3
from stack1 and stack1 will be {2}
pop2() the poped element will be 4
from stack2 and now stack2 is empty
pop2() the stack2 is now empty hence -1 .
void twoStacks :: push1(int x)
{
if(top1 == top2)
return;
arr[++top1] = x;
}
//Function to push an integer into the stack2.
void twoStacks ::push2(int x)
{
if(top1 == top2)
return;
arr[--top2] = x;
}
//Function to remove an element from top of the stack1.
int twoStacks ::pop1()
{
if(top1 == -1)
return -1;
return arr[top1--];
}
//Function to remove an element from top of the stack2.
int twoStacks :: pop2()
{
if(top2 == size)
return -1;
return arr[top2++];
}