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

deloitte Problem Statement

The document outlines five problem statements involving string segmentation, finding the least common multiple, constructing a balanced binary search tree from an inorder traversal, computing XOR for given queries, and a mention of a problem related to the Greatest Common Divisor. Each problem includes input and output formats, constraints, and sample solutions in C++, Python, and Java. The document provides a comprehensive overview of algorithmic challenges and their implementations in multiple programming languages.

Uploaded by

aasv218
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

deloitte Problem Statement

The document outlines five problem statements involving string segmentation, finding the least common multiple, constructing a balanced binary search tree from an inorder traversal, computing XOR for given queries, and a mention of a problem related to the Greatest Common Divisor. Each problem includes input and output formats, constraints, and sample solutions in C++, Python, and Java. The document provides a comprehensive overview of algorithmic challenges and their implementations in multiple programming languages.

Uploaded by

aasv218
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Problem Statement 1: John and Mocha are two friends.

Mocha made his dictionary of length n


with strings k1, k2 .. kn and called it Alien dictionary. John tries to test Mocha's Alien dictionary by
giving one string s to Mocha. Help Mocha check if John's string can be segmented into a sequence
of one or more words from Mocha's Alien dictionary.

Note: The words in the dictionary contain unique words of lowercase English letters and can be
found multiple times in the segmentation.

Input Format:

The first line contains a string s given by John.

The second line contains n, which is the length of the dictionary of strings of Mocha.

The following n lines are different strings that are present in the Mocha's Alien dictionary

Output Format:

Print "true" if the string given by John can be segmented into a sequence of one or more words of
Mocha's Alien dictionary.

Else, print "false".

Constraints:

1<= s.length() <= 3*10^2

1<= n <= 10^3

1<= ki.length() <= 20

Sample Input:

applepenapple

apple
pen

Sample Output:

true

Solution 1: C++

#include <bits/stdc++.h>
using namespace std;

bool wordBreak(string s, vector<string> &wordDict) {

if(wordDict.size() == 0) return false;


set<string> dict;

for(int i=0; i<wordDict.size(); i++) {

dict.insert(wordDict[i]);

vector<bool> dp(s.size() + 1, false);


dp[0] = true;

for(int i=1; i<=s.size(); i++) {


for(int j=i-1; j>=0; j--) {
if(dp[j]) {
string word = s.substr(j, i-j);
if(dict.find(word) != dict.end()) {

dp[i] = true;
break;

}
}
}
}
return dp[s.size()];
}

int main() {

string s;
cin>>s;
int n;
cin>>n;
vector<string> wordDict;
for(int i=0; i<n; i++) {
string str;
cin>>str;
wordDict.push_back(str);
}
wordBreak(s, wordDict) ? cout<<"true" : cout<<"false";
return 0;
}
Solution 2: Python

class AlienDictionary:
def __init__(self):
self.dictionary = set()

def add_word(self, word):


self.dictionary.add(word)

def can_segment(self, s):


n = len(s)
dp = [False] * (n + 1)
dp[0] = True

for i in range(1, n + 1):


for j in range(i):
if dp[j] and s[j:i] in self.dictionary:
dp[i] = True
break

return dp[n]

# Reading input
s = input().strip()
n = int(input().strip())

alien_dict = AlienDictionary()

for _ in range(n):
word = input().strip()
alien_dict.add_word(word)

# Checking if John's string can be segmented


result = alien_dict.can_segment(s)

# Printing the result


if result:
print("true")
else:
print("false")
Solution 3: Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to
STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
String s=sc.next();
boolean[]dp=new boolean[s.length()+1];
int n=sc.nextInt();
String[]dict=new String[n];

for(int i=0;i<n;i++){
dict[i]=sc.next();
// System.out.println(dict[i]);
}

dp[0]=true;
for(int i=0;i<s.length();i++){
for(int j=0;j<dict.length;j++){
if(s.charAt(i)==dict[j].charAt(dict[j].length()-1) &&
i+1>=dict[j].length())
{
if(s.substring(i-dict[j].length()+1,i+1).equals(dict[j]))
dp[i+1]=dp[i+1]||dp[i-dict[j].length()+1];
}

}
}
System.out.println(dp[s.length()]);

}
}
Problem Statement 2: Alice is given two integers, ( P ) and ( N ), where ( P ) is a prime number.
She needs to find the smallest number ( X ) that is a multiple of both ( P ) and ( N ).

Input Format

The input consists of two space-separated integers, ( P ) and ( N ).

Output Format

Return the smallest possible value of ( X ).

Constraints

1 <= P, N <= 10^9

Testcase Input
25

Testcase Output

10

Solution 1: Python

Python:
# Enter your code here. Read input from STDIN. Print output to STDOUT
import math

def lcm(a, b):


return a * b // math.gcd(a, b)

p, n = map(int, input().split())
print(lcm(p, n))

Solution code in C++

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
long long int a,b;
cin>>a>>b;
if(b%a==0)
{
cout<<b;
}
else
{
cout<<a*b;
}
}
Solution 2: Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Main {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to
STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
long a =sc.nextLong();
long b=sc.nextLong();
long great=gcd(a,b);
System.out.print((a*b)/great);

}
public static long gcd(long a,long b){
while(b!=0){
long temp=b;
b=a%b;
a=temp;
}
return a;

}
}
Problem Statement 3: You are given an array nums of integers of length n that represents the
inorder traversal of a balanced binary search tree (BST). Your task is to construct this BST from the
given array and return its level order serialization.

A balanced BST is a tree in which the depth difference between the two subtrees of any node is not
more than 1. If there are multiple possible balanced BSTs based on the given array, you should
construct the tree that has more nodes as a left child than as a right child.

Note: nums is sorted in a strictly increasing order and 'null' values of level order serialization are not
included in the final output.

Input Format

The first line of input contains N representing the number of nodes in the BST. The second line of
input contains N integers , separated by space, representing the inorder traversal of the required
balanced BST.

Output Format

Output a string representing the level order serialization of the constructed BST, where 'null' values
are not included.

Constraints
1 <= n <= 10^4

-10^4 <= nums[i] <= 10^4

Testcase Input

20

-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9

Testcase Output

-1 -6 4 -9 -4 1 7 -10 -8 -5 -3 0 2 5 8 -7 -2 3 6 9

Sloution 1: Python

from typing import List, Optional


from collections import deque

class TreeNode:
def __init__(self, x: int):
self.val = x
self.left = None
self.right = None

@staticmethod
def treeNodeToString(root: Optional['TreeNode']) -> str:
if root is None:
return ""

output = ""
queue = deque([root])
while queue:
node = queue.popleft()
if node is not None:
output += str(node.val) + " "
queue.append(node.left)
queue.append(node.right)
return output.strip()

class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def helper(left: int, right: int) -> Optional[TreeNode]:
if left > right:
return None
mid = (left + right) // 2
root = TreeNode(nums[mid])
root.left = helper(left, mid - 1)
root.right = helper(mid + 1, right)
return root

return helper(0, len(nums) - 1)

# Example usage
if __name__ == "__main__":
import sys
input = sys.stdin.read
data = list(map(int, input().split()))
nums = data[1:]
sol = Solution()
bst_root = sol.sortedArrayToBST(nums)
print(TreeNode.treeNodeToString(bst_root))
Solution 2: C++

#include <iostream>
#include <vector>
#include <queue>
#include <string>

using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

static string treeNodeToString(TreeNode* root) {


if (root == nullptr)
return "";

string output = "";


queue<TreeNode*> nodeQueue;
nodeQueue.push(root);

while (!nodeQueue.empty()) {
TreeNode* node = nodeQueue.front();
nodeQueue.pop();

if (node != nullptr) {
output += to_string(node->val) + " ";
nodeQueue.push(node->left);
nodeQueue.push(node->right);
}
}

return output;
}
};
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return helper(nums, 0, nums.size() - 1);
}

private:
TreeNode* helper(vector<int>& nums, int left, int right) {
if (left > right)
return nullptr;

int mid = (left + right) / 2;


TreeNode* root = new TreeNode(nums[mid]);
root->left = helper(nums, left, mid - 1);
root->right = helper(nums, mid + 1, right);
return root;
}
};

int main() {
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; ++i)
cin >> nums[i];

Solution sol;
TreeNode* bstRoot = sol.sortedArrayToBST(nums);
cout << TreeNode::treeNodeToString(bstRoot) << endl;

return 0;
}
Solution 3: Java

import java.util.*;
import java.io.*;

public class Main {


public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
Solution ob = new Solution();
int n = scn.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++)
nums[i] = scn.nextInt();

System.out.println(TreeNode.treeNodeToString(ob.sortedArrayToBST(nums)));
}
}

class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode() {
val = 0;
}

TreeNode(int x) {
val = x;
}

public static String treeNodeToString(TreeNode root) {


if (root == null) {
return "";
}

String output = "";


Queue<TreeNode> nodeQueue = new LinkedList<>();
nodeQueue.add(root);
while (!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.remove();

if (node == null) {
continue;
}

output += String.valueOf(node.val) + " ";


nodeQueue.add(node.left);
nodeQueue.add(node.right);
}
return output.trim();
}
}

class Solution {
int[] nums;

public TreeNode helper(int left, int right) {


if (left > right)
return null;

// always choose left middle node as a root


int p = (left + right) / 2;

// preorder traversal: node -> left -> right


TreeNode root = new TreeNode(nums[p]);
root.left = helper(left, p - 1);
root.right = helper(p + 1, right);
return root;
}

public TreeNode sortedArrayToBST(int[] nums) {


this.nums = nums;
return helper(0, nums.length - 1);
}
}
Problem Statement 4:

You are given an array ‘arr’ of positive integers. You are also given the array queries where
queries[i] = [lefti, righti]. For each query I compute the XOR of elements from left to right (that is,
arr[left] XOR arr[left + 1] XOR ... XOR arr[right] ). Display an array answer where answer[i] is the
answer to the ith query.

Input Format

The first line contains the number of elements in the array, n.

The second line contains n space-separated integers representing the array

The third line contains the number of queries, q

The fourth line contains the number of columns in the queries matrix which is always 2.

The next q lines contain the queries where there are two space-separated integers representing left
and right.

Output Format

Display a single line containing q space-separated integers representing the answer to each query.

Constraints

1 <= arr.length, queries.length<= 3 ^ 104

1 <= arr[i] <= 109

queries[i].length == 2

0 <= lefti<= righti <arr.length

Testcase Input

4
4 8 2 10

23

13

00

03

Testcase Output

Solution 1: C++

#include <bits/stdc++.h>
using namespace std;

int main() {
int n;
cin>>n;
vector<int>v(n);
for(auto &i:v) cin>>i;
vector<int>xoro(n);
xoro[0]=v[0];
for(int i=1;i<n;i++) xoro[i]=xoro[i-1]^v[i];
int q,c;
cin>>q>>c;
for(int i=0;i<q;i++)
{
int l,r;
cin>>l>>r;
if(l==0) cout<<xoro[r]<<endl;
else cout<<(xoro[r]^xoro[l-1])<<endl;
}
return 0;
}
Solution 2: Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Main {

public static int[] solveXORQueries(int[] arr, int[][] queries) {


int n = arr.length;

int[] prefixXOR = new int[n + 1];


for (int i = 1; i <= n; i++) {
prefixXOR[i] = prefixXOR[i-1] ^ arr[i-1];
}

int[] results = new int[queries.length];


for (int i = 0; i < queries.length; i++) {
int left = queries[i][0];
int right = queries[i][1];

results[i] = prefixXOR[right+1] ^ prefixXOR[left];


}

return results;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int q = scanner.nextInt();
scanner.nextInt();

int[][] queries = new int[q][2];


for (int i = 0; i < q; i++) {
queries[i][0] = scanner.nextInt();
queries[i][1] = scanner.nextInt();
}

int[] answer = solveXORQueries(arr, queries);


for (int value : answer) {
System.out.println(value);
}
}
}
Solution 3: Python

# Enter your code here. Read input from STDIN. Print output to STDOUT
n=int(input())
a=list(map(int,input().split()))
q=int(input())
c=int(input())
queries=[list(map(int,input().split())) for _ in range(q)]
#print(queries)
for i in queries:
start,end=i
res=a[start]
for i in range(start+1,end+1):
res^=a[i]
print(res)
Problem Statement 5: Leo is fascinated by the concepts of Greatest Common Divisor (GCD) and
Least Common Multiple (LCM). Alice gives him an array and challenges him to find how many pairs
(i, j) in the array satisfy a particular condition. Leo defines GL(i, j) as the difference between
LCM(A[i], A[j]) and GCD(A[i], A[j]), where i and j are indices of the array and 0<=i < j < N.

Your task is to help Leo count how many pairs (i, j) in the array satisfy GL(i, j) = 0. Return the total
number of such pairs

Input Format

The first line contains an integer N, representing the size of A.

The next line contains N space-separated integers, representing the original array A.

Output Format

Return the total number of pairs with GL(i,j) = 0.

Constraints

1 ≤ N ≤10^5
1 ≤ A[i] ≤100

Testcase Input

47

Testcase Output

Solution 1: Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

class Main {

// Function to count GLPairs


static int GLPairs(int n, int[] num) {
HashMap<Integer, Integer> mp = new HashMap<>(); // HashMap to
store occurrences of each element
int ans = 0; // Variable to store the count of GL(i,j)=0 pairs

// Iterating over the array to hash in the HashMap


for (int i = 0; i < n; i++) {
if (mp.containsKey(num[i])) {
mp.put(num[i], mp.get(num[i]) + 1);
} else {
mp.put(num[i], 1);
}
}

// Iterating over the HashMap to add the contribution of each


element in the GL(i,j) = 0 pairs
for (int count : mp.values()) {
ans += (count * (count - 1)) / 2;
}

return ans; // Returning the answer


}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
// Taking input
int n = scanner.nextInt();
int[] num = new int[n];
for (int i = 0; i < n; i++) {
num[i] = scanner.nextInt();
}

// Calling the function and printing the result


System.out.println(GLPairs(n, num));
}
}
Solution 2: C++

#include <bits/stdc++.h>
using namespace std;
int GLPairs(int n,vector<int>&num)
{
unordered_map<long long int, long long int>mp; // creating the map to
have the occurrence of each element.
long long int ans =0; // variable to store the count of GL(i,j)=0.
for(auto &i: num) //iterating over the array to hash in the map.
mp[i]++;
for(auto &i: mp) //iterating over the map to add the contribution of
each element in the GL(i,j) = 0 pairs.
{
ans += ((i.second*(i.second-1))/2); // incrementing answer by each
elements occurrence distribution.
}
return ans; //returning the answer.
}
int main() {
int n ;
cin>>n;
vector<int>vec(n);
for(auto &i:vec)
{
cin>>i;
}
cout<<GLPairs(n,vec)<<endl;
return 0;
}
Solution 3: Python

def GLPairs(n, num):


mp = {} # creating the dictionary to have the occurrence of each
element.
ans = 0 # variable to store the count of GL(i,j)=0.
for i in num: # iterating over the array to hash in the dictionary.
if i in mp:
mp[i] += 1
else:
mp[i] = 1
for i in mp.values(): # iterating over the dictionary to add the
contribution of each element in the GL(i,j) = 0 pairs.
ans += (i * (i - 1)) // 2 # incrementing answer by each
element's occurrence distribution.
return ans # returning the answer.

# Taking input and calling the function


n = int(input())
num = list(map(int, input().split()))
print(GLPairs(n, num))

You might also like