Convegenius Coding Questions and Answers
Convegenius Coding Questions with Solutions
This page will help you to find Sample Convegenius Coding Questions and Answers included Online Assessment and Technical Interview of the company which will help you to prepare for Convegenius Hiring Drive. Go through this page to get all the Sample Questions to prepare for Convegenius Hiring for freshers.
By the end of Convegenius Coding Questions and Answers page you’ll get FAQ’s related to Convegenius Hiring Process that will help you to get clear understanding of the recruitment drive.
Convegenius Coding Questions with Solutions
Question 1: Detecting loop in a linked list
Problem Statement –
You are given a singly linked list, where each node contains a value and a pointer to the next node in the list. Your task is to determine if the linked list contains a cycle or not.
A cycle in a linked list occurs when there is a node in the list whose next pointer points to a previously visited node, creating a loop.
You need to implement an efficient solution with a time complexity of O(n) and a space complexity of O(1), where n is the number of nodes in the linked list.
Function Description:
Complete the hasLoop function that takes the head of the linked list as input.
Returns true if a cycle exists, and false otherwise.
Constraints:
- The number of the nodes in the list is in the range [1, 99].
- -105 <= Node.val <= 105
Sample Cases:
Sample Input :
list = [1, 2, 3, 4]
loop at 4 -> 1
Sample Output :
After giving sample input the desired output will be as follows:
Loop Detected
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
#include<bits/stdc++.h> using namespace std; class ListNode { public: int value; ListNode* next; }; void insertAtBeginning(ListNode** head, int newValue) { ListNode* newNode = new ListNode(); newNode->value = newValue; newNode->next = (*head); (*head) = newNode; } int detectLoop(ListNode* list) { ListNode* slowPtr = list; ListNode* fastPtr = list; while (slowPtr && fastPtr && fastPtr->next) { slowPtr = slowPtr->next; fastPtr = fastPtr->next->next; if (slowPtr == fastPtr) { return 1; } } return 0; } int main() { ListNode* head = NULL; insertAtBeginning(&head, 1); insertAtBeginning(&head, 2); insertAtBeginning(&head, 3); insertAtBeginning(&head, 4); insertAtBeginning(&head, 5); head->next->next->next->next->next = head; if (detectLoop(head)) cout << "Loop Found"; else cout << "No Loop"; return 0; }
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while temp: print(temp.data) temp = temp.next def detectLoop(self): slow_ptr = self.head fast_ptr = self.head while slow_ptr and fast_ptr and fast_ptr.next: slow_ptr = slow_ptr.next fast_ptr = fast_ptr.next.next if slow_ptr == fast_ptr: return 1 return 0 linklist = LinkedList() linklist.push(1) linklist.push(2) linklist.push(3) linklist.push(4) linklist.head.next.next.next.next = linklist.head if linklist.detectLoop(): print("Loop Found") else: print("No Loop")
public class Main { Node head; class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } void insert(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; } else { Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } } boolean hasCycle() { if (head == null || head.next == null) { return false; } Node slowPtr = head; Node fastPtr = head.next; while (fastPtr != null && fastPtr.next != null) { if (slowPtr == fastPtr) { return true; } slowPtr = slowPtr.next; fastPtr = fastPtr.next.next; } return false; } public static void main(String[] args) { Main linkedList = new Main(); linkedList.insert(1); linkedList.insert(2); linkedList.insert(3); linkedList.insert(4); linkedList.insert(5); linkedList.head.next.next.next.next.next = linkedList.head; if (linkedList.hasCycle()) { System.out.println("Cycle Detected"); } else { System.out.println("No Cycle Detected"); } } }
Question 2 : Weird Terminal
Problem Statement :
Here is a weird problem in Susan’s terminal. He can not write more than two words each line, if she writes more than two, it takes only 2 words and the rest are not taken. So she needs to use enter and put the rest in a new line. For a given paragraph, how many lines are needed to be written in Susan’s terminal?
Input Format:
A string as the text to input in the terminal
Output Format:
Number of lines written.
Constraints:
Number of words <=10^7
Sample Input:
How long do you have to sit dear ?
Sample Output:
4
Explanation:
The writing will be:
How long
Do you
Have to
Sit dear ?
#include<bits/stdc++.h> using namespace std; int main() { string s; getline(cin, s); int ans = 0; istringstream ss(s); while (ss) { string word; int flag = 0; ss >> word; if (word == "") break; for (int i = 0; i < word.length(); i++) if (!isalpha(word[i])) { if (i != 0) { if (i == word.length() - 1) { if (word[i] == ',' || word[i] == '.' || word[i] == ';' || word[i] == ':' || word[i] == '?' || word[i] == '!') continue; } else if (word[i] == '.' && word[i + 1] != '.') { flag++; break; } else if (word[i] == '-' && isalpha(word[i + 1])) continue; else { flag++; break; } } else { flag++; break; } } if (flag == 0) { ans++; //cout <<word<<" "<<word.length()<<endl; } } cout << floor((ans - 1) / 2) + 1; }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int ans = 0; String[] words = s.split(" "); for (String word : words) { int flag = 0; if (word.equals("")) break; for (int i = 0; i < word.length(); i++) { if (!Character.isLetter(word.charAt(i))) { if (i != 0) { if (i == word.length() - 1) { if (word.charAt(i) == ',' || word.charAt(i) == '.' || word.charAt(i) == ';' || word.charAt(i) == ':' || word.charAt(i) == '?' || word.charAt(i) == '!') continue; } else if (word.charAt(i) == '.' && word.charAt(i + 1) != '.') { flag++; break; } else if (word.charAt(i) == '-' && Character.isLetter(word.charAt(i + 1))) continue; else { flag++; break; } } else { flag++; break; } } } if (flag == 0) { ans++; // System.out.println(word + " " + word.length()); } } System.out.println(Math.floorDiv((ans - 1), 2) + 1); } }
s=input() n=len(s) s1='' for i in range(n): if s[i]=='-': s1+='' continue if s[i]=='.' or s[i]=='!' or s[i]==',' or s[i]=='?': s1+=' ' continue else: s1+=s[i] a=list(s1.split()) c=0 for i in a: i1=0 for j in i: if not ((ord(j)>=65 and ord(j)<=90) or (ord(j)>=97 and ord(j)<=122)): i1=1 break if i1==0: c+=1 print((c-1)//2 +1)
Question 3 : Device Name System
Problem statement: Rocky is a software engineer and he is creating his own operating system called “myFirst os”. myFirst os is a GUI (Graphical user interface) based operating system where everything is stored in files and folders. He is facing issues on creating unique folder names for the operating system . Help rocky to create the unique folder name for it’s os.If folder name already exists in the system and integer number is added at the name to make it unique. The integer added starts with 1 and is incremented by 1 for each new request of an existing folder name. Given a list of folder names , process all requests and return an array of corresponding folder names.
Example
- n=5
- foldername= [‘home’ , ‘myfirst’ ,’downloads’, ‘myfirst’, ‘myfirst’]
- Foldername[0] = ‘home’ is unique.
- Foldername[1] = ‘myfirst’ is unique.
- foldername [2] =’downloads’ is unique.
- Foldername[3] =’myfirst’ already exists in our system. So Add1 at the end of the folder name i.e foldername[3] =”myfirst1″
- Foldername[4 ]=’myfirst’ also already exists in our system.So add 2 at the end of the folder name i.e. foldername[4]=”myfirst2″.
Function description
- Complete the function folderNameSystem In the editor below
- folderNameSystem has the following parameters
- string foldername[n]: an array of folder name string in the order requested
Returns:
- String[n]: an array of strings usernames in the order assigned
Constraints
- 1<=n<=10^4
- 1<=length of foldername[i]<20
- foldername[i] contains only lowercase english letter in the range ascii[a-z]
Input Format:
- The first line contains an integer n , denoting the size of the array usernames Each line i of the n subsequent lines (where i<=0<=n) contains a string usernames[i] representing a username request in the order received.
Sample case 0
- 4
- home
- download
- first
- first
Sample Output 0
- home
- download
- first
- first1
Explanation 0
- foldername[0] = ‘home’ is unique
- foldername[1]=’download’ is unique
- foldername[2]= ‘first’ is unique
- foldername[3]=’first’ is already existing . so add 1 to it and it become first1
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; vector v(n); for(int i=0;i<n;i++) cin>>v[i]; map<string,int> m; for(auto i:v){ if(m[i]) cout<<i<<m[i]<<endl; else cout<<i<<endl; m[i]++; } }
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); LinkedHashMap<String, Integer> map=new LinkedHashMap<>(); for(int i=0;i<n;i++){ String str=sc.next(); if(map.containsKey(str)){ int count=map.get(str); count = count+1; map.put(str,count); } else map.put(str,1); } Set s = map.entrySet(); Iterator itr = s.iterator(); while(itr.hasNext()){ Map.Entry m=(Map.Entry)itr.next(); int value=(Integer)m.getValue(); System.out.println(m.getKey()); value--; for(int i=1;i<=value;i++){ System.out.println(m.getKey()+""+i); value--; } } } }
n=int(input()) arr = [] ans = "" for i in range(n): arr.append(input()) print() for i in range(n): if arr[:i+1].count(arr[i])>1: ans = arr[i]+str(arr[:i+1].count(arr[i])-1) else: ans = arr[i] print(ans)
Question 4 : Airport Authority
Problem Statement -:
In an airport, the Airport authority decides to charge a minimum amount to the passengers who are carrying luggage with them. They set a threshold weight value, say, T, if the luggage exceeds the weight threshold you should pay double the base amount. If it is less than or equal to threshold then you have to pay $1.
Function Description:
Complete the weightMachine function in the editor below. It has the following parameter(s):
Parameters:
Name | Type | Description |
N | Integer | number of luggage |
T | Integer | weight of each luggage |
weights[ ] | Integer array | threshold weight |
Returns: The function must return an INTEGER denoting the required amount to be paid.
Constraints:
- 1 <= N <= 10^5
- 1 <= weights[i] <= 10^5
- 1 <= T <= 10^5
Input Format for Custom Testing:
- The first line contains an integer, N, denoting the number of luggage.
- Each line i of the N subsequent lines (where 0 <= i <n) contains an integer describing the weight of ith luggage.
- The next line contains an integer, T, denoting the threshold weight of the boundary wall.
Sample Cases:
- Sample Input 1
4
1
2
3
4
3 - Sample Output 1
5 - Explanation:
Here all weights are less than threshold weight except the luggage with weight 4 (at index 3) so all pays base fare and it pays double fare.
#include<stdio.h> #include<string.h> long int weightMachine(long int N,long int weights[],long int T) { long int amount=0,i; for(i=0;i<N;i++) { amount++; if(weights[i]>T) { amount++; } } return amount; } int main() { long int N,i,T; scanf("%ld",&N); long int weights[N]; for(i=0;i<N;i++) { scanf("%ld",&weights[i]); } scanf("%ld",&T); printf("%ld",weightMachine(N,weights,T)); return 0; }
#include <bits/stdc++.h> using namespace std; long int weightMachine(long int N,long int weights[],long int T) { long int amount=0,i; for(i=0;i<N;i++) { amount++; if(weights[i]>T) { amount++; } } return amount; } int main() { long int N,i,T; cin>>N; long int weights[N]; for(i=0;i<N;i++) { cin>>weights[i]; } cin>>T; cout<<weightMachine(N,weights,T); return 0; }
import java.util.*; class Main { static int weightMachine (int N, int weights[],int T) { int amount = 0, i; for (i = 0; i < N; i++) { amount++; if (weights[i] > T) { amount++; } } return amount; } public static void main (String[]args) { Scanner sc = new Scanner (System.in); int n = sc.nextInt (); int weights[]= new int[n]; for(int i=0; i<n; i++) weights[i] = sc.nextInt(); int t = sc.nextInt (); System.out.println (weightMachine(n, weights, t)); } }
def weightMachine(N,weights,T): amount=0 for i in weights: amount+=1 if(i>T): amount+=1 return amount N=int(input()) weights=[] for i in range(N): weights.append(int(input())) T=int(input()) print(weightMachine(N,weights,T))
Question 5: Candies
Problem Description
Question:- Krishna loves candies a lot, so whenever he gets them, he stores them so that he can eat them later whenever he wants to.
He has recently received N boxes of candies each containing Ci candies where Ci represents the total number of candies in the ith box. Krishna wants to store them in a single box. The only constraint is that he can choose any two boxes and store their joint contents in an empty box only. Assume that there are an infinite number of empty boxes available.
At a time he can pick up any two boxes for transferring and if both the boxes contain X and Y number of candies respectively, then it takes him exactly X+Y seconds of time. As he is too eager to collect all of them he has approached you to tell him the minimum time in which all the candies can be collected.
Input Format:
- The first line of input is the number of test case T
- Each test case is comprised of two inputs
- The first input of a test case is the number of boxes N
- The second input is N integers delimited by whitespace denoting the number of candies in each box
Output Format: Print minimum time required, in seconds, for each of the test cases. Print each output on a new line.
Constraints:
- 1 < T < 10
- 1 < N< 10000
- 1 < [Candies in each box] < 100009
S. No. | Input | Output |
---|---|---|
1 | 1 4 1 2 3 4 | 19 |
2 | 1 5 1 2 3 4 5 | 34 |
Explanation for sample input-output 1:
4 boxes, each containing 1, 2, 3 and 4 candies respectively.Adding 1 + 2 in a new box takes 3 seconds.Adding 3 + 3 in a new box takes 6 seconds.Adding 4 + 6 in a new box takes 10 seconds.Hence total time taken is 19 seconds. There could be other combinations also, but overall time does not go below 19 seconds.
Explanation for sample input-output 2:
5 boxes, each containing 1, 2, 3, 4 and 5 candies respectively.Adding 1 + 2 in a new box takes 3 seconds.Adding 3 + 3 in a new box takes 6 seconds.Adding 4 + 6 in a new box takes 10 seconds.Adding 5 + 10 in a new box takes 15 seconds.Hence total time taken is 34 seconds. There could be other combinations also, but overall time does not go below 33 seconds.
#include<stdio.h> int main() { int i,j; int num_box=0,k=0,sum=0,times=0,tst_case,temp=0; long c[10000],s[10000]; printf("Enter the number of test case:"); scanf("%d",&tst_case); printf("Enter the number of boxes:"); for(int l=0;l<tst_case;l++) { scanf("%d",&num_box); } printf("Enter the number of candies in each box:"); for(i=0;i<num_box;i++) { scanf("%ld",&c[i]); } for(i=0;i<num_box;i++) { for(j=i+1;j<num_box;j++) { if(c[i]>c[j]) { temp=c[i]; c[i]=c[j]; c[j]=temp; } } } sum=0; k=0; for(i=0;i<num_box;i++) { sum=sum+c[i]; s[k]=sum; k++; } times=0; printf("Minimum time requried:"); for(i=1;i<k;i++) times=times+s[i]; printf("%d\n",times); return 0; }
Output 1 4 1 2 3 4 19
#include<bits/stdc++.h> using namespace std; int main() { int i,j; int num_box=0,k=0,sum=0,times=0,tst_case,temp=0; long c[10000],s[10000]; cout<<("Enter the number of test case:"); cin>>tst_case; cout<<("Enter the number of boxes:"); for(int l=0;l<tst_case;l++) { cin>>num_box; } cout<<("Enter the number of candies in each box:"); for(i=0;i<num_box;i++) { cin>>c[i]; } for(i=0;i<num_box;i++) { for(j=i+1;j<num_box;j++) { if(c[i]>c[j]) { temp=c[i]; c[i]=c[j]; c[j]=temp; } } } sum=0; k=0; for(i=0;i<num_box;i++) { sum=sum+c[i]; s[k]=sum; k++; } times=0; cout<<("Minimum time requried:"); for(i=1;i<k;i++) times=times+s[i]; cout<<times; return 0; }
Output 1 4 1 2 3 4 19
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n, i, k = 0, sum = 0, s1 = 0, t, temp = 0, j; long c[] = new long[1000009]; long s[] = new long[100009]; t = sc.nextInt(); for (int l = 0; l < t; l++) { n = sc.nextInt(); for (i = 0; i < n; i++) c[i] = sc.nextLong(); for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (c[i] > c[j]) { temp = (int) c[i]; c[i] = c[j]; c[j] = temp; } } } sum = 0; k = 0; for (i = 0; i < n; i++) { sum = (int) (sum + c[i]); s[k] = sum; k++; } s1 = 0; for (i = 1; i < k; i++) s1 = (int) (s1 + s[i]); System.out.println(s1); } } }
Output 1 4 1 2 3 4 19
T = int(input()) arr1 = [] for _ in range(T): N = int(input()) arr = list(map(int, input().split())) arr.sort() count = arr[0] for i in range(1, len(arr)): count += arr[i] arr1.append(count) print(sum(arr1))
Output 1 4 1 2 3 4 19
Question 6: Remove all characters in a given string that are not lowercase or numerical
The task is to remove all characters in a given string that are not lowercase letters or numerical digits. The purpose is to clean the string and only keep the lowercase letters (a-z) and numerical digits (0-9), discarding any other characters such as whitespace, punctuation marks, or uppercase letters.
- For example
- Input: “Hello!123$”
- Output: “ello123”
- Explanation: The input string contains uppercase letters, an exclamation mark, and a dollar sign. After removing all characters that are not lowercase or numerical, only the lowercase letters “e”, “l”, “l”, “o”, and the numerical digits “1”, “2”, “3” remain.
Write the code to remove all characters in a given string that are not lowercase or numerical.
Input Format: First line contains two numbers N,M
Output Format: Print all the stepping numbers present in the range.
Constraints: 0 <= N < M <= 1,000,000,000
#include<bits/stdc++.h> removeNonAlphanumeric(const std::string& str) { std::string cleanedString; for (char c : str) { if (std::islower(c) || std::isdigit(c)) { cleanedString += c; } } return cleanedString; } int main() { std::string inputString = "Hello!123$"; std::string cleanedString = removeNonAlphanumeric(inputString); std::cout << "Original string: " << inputString << std::endl; std::cout << "Cleaned string: " << cleanedString << std::endl; return 0; }
public class Main { public static String removeNonAlphanumeric(String string) { // Use regular expression to remove non-alphanumeric characters String cleanedString = string.replaceAll("[^a-z0-9]", ""); return cleanedString; } public static void main(String[] args) { String inputString = "Hello!123$"; String cleanedString = removeNonAlphanumeric(inputString); System.out.println("Original string: " + inputString); System.out.println("Cleaned string: " + cleanedString); } }
import re def removeNonAlphanumeric(string): # Use regular expression to remove non-alphanumeric characters cleaned_string = re.sub(r'[^a-z0-9]', '', string) return cleaned_string # Test the function input_string = "Hello!123$" cleaned_string = removeNonAlphanumeric(input_string) print("Original string:", input_string) print("Cleaned string:", cleaned_string)
Question 7 : Elements of Matrix
Problem Statement
You are required to input the size of the matrix then the elements of matrix, then you have to divide the main matrix in two sub matrices (even and odd) in such a way that element at 0 index will be considered as even and element at 1st index will be considered as odd and so on. then you have sort the even and odd matrices in ascending order then print the sum of second largest number from both the matrices
Example
- enter the size of array : 5
- enter element at 0 index : 3
- enter element at 1 index : 4
- enter element at 2 index : 1
- enter element at 3 index : 7
- enter element at 4 index : 9
Sorted even array : 1 3 9
Sorted odd array : 4 7
7
#include<bits/stdc++.h> using namespace std; int main () { int arr[100]; int length, i, j, oddlen, evenlen, temp, c, d; int odd[50], even[50]; cout << "enter the length of array : "; cin >> length; for (i = 0; i < length; i++) { cout << "Enter element at " << i << " index : "; cin >> arr[i]; } if (length % 2 == 0) { oddlen = length / 2; evenlen = length / 2; } else { oddlen = length / 2; evenlen = (length / 2) + 1; } for (i = 0; i < length; i++) // seperation of even and odd array { if (i % 2 == 0) { even[i / 2] = arr[i]; } else { odd[i / 2] = arr[i]; } } for (i = 0; i < evenlen - 1; i++) // sorting of even array { for (j = i + 1; j < evenlen; j++) { temp = 0; if (even[i] > even[j]) { temp = even[i]; even[i] = even[j]; even[j] = temp; } } } for (i = 0; i < oddlen - 1; i++) // sorting of odd array { for (j = i + 1; j < oddlen; j++) { temp = 0; if (odd[i] > odd[j]) { temp = odd[i]; odd[i] = odd[j]; odd[j] = temp; } } } cout << "\nSorted even array : "; // printing even array for (i = 0; i < evenlen; i++) { cout << even[i] << " "; } cout << "\n"; cout << "Sorted odd array : "; // printing odd array for (i = 0; i < oddlen; i++) { cout << odd[i] << " "; } cout << endl; cout << even[evenlen - 2] + odd[oddlen - 2]; // printing final result }
import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main (String[]args) { Scanner sc = new Scanner (System.in); System.out.print ("Enter size of array : "); int arrsize = sc.nextInt (); int[] main = new int[arrsize]; ArrayList < Integer > even = new < Integer > ArrayList (); ArrayList < Integer > odd = new < Integer > ArrayList (); System.out.println ("Enter " + arrsize + " Elements"); for (int i = 0; i < arrsize; i++) main[i] = sc.nextInt (); for (int i = 0; i < arrsize; i++) { if (i % 2 == 0) even.add (main[i]); else odd.add (main[i]); } Collections.sort (even); Collections.sort (odd); System.out.println ("Sorted even array "); for (int e:even) System.out.print (e + " "); System.out.println (); System.out.println ("sorted odd array "); for (int e:odd) System.out.print (e + " "); System.out.println (); int evensec = even.get (even.size () - 2); int oddsec = odd.get (odd.size () - 2); System.out.println ("Second Largest Element in Even List is:" + evensec); System.out.println ("Second Largest Element in Odd List is:" + oddsec); System. out.println ("Sum Of Second Largest Element Of Odd and Even List:" + (evensec + oddsec)); } }
array = [] evenArr = [] oddArr = [] n = int(input("Enter the size of the array:")) for i in range(0,n): number = int(input("Enter Element at {} index:".format(i))) array.append(number) if i % 2 == 0: evenArr.append(array[i]) else: oddArr.append(array[i]) evenArr = sorted(evenArr) print("Sorted Even Array:", evenArr[0:len(evenArr)]) oddArr = sorted(oddArr) print("Sorted Odd Array:", oddArr[0:len(oddArr)]) print(evenArr[1] + oddArr[1]) evenArr = sorted(evenArr) print("Sorted Even Array:", evenArr[0:len(evenArr)]) oddArr = sorted(oddArr) print("Sorted Odd Array:", oddArr[0:len(oddArr)]) print(evenArr[-2] + oddArr[-2])
Question 8: Queries for Count
The task is to determine the number of elements within a specified range in an unsorted array. Given an array of size n, the goal is to count the elements that fall between two given values, i and j, inclusively.
Examples:
Input:
Array: [1, 3, 3, 9, 10, 4]
Range 1: i = 1, j = 4
Range 2: i = 9, j = 12
Output:
For Range 1: 4
For Range 2: 2
Explanation:
In the first query, the numbers within the range 1 to 4 are 1, 3, 3, and 4.
In the second query, the numbers within the range 9 to 12 are 9 and 10.
#include<bits/stdc++.h> using namespace std; int findLowerIndex(int arr[], int n, int x) { int low = 0, high = n - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] >= x) high = mid - 1; else low = mid + 1; } return low; } int findUpperIndex(int arr[], int n, int y) { int low = 0, high = n - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] <= y) low = mid + 1; else high = mid - 1; } return high; } int countElementsInRange(int arr[], int n, int x, int y) { int count = 0; count = findUpperIndex(arr, n, y) - findLowerIndex(arr, n, x) + 1; return count; } int main() { int arr[] = {1, 4, 4, 9, 10, 3}; int n = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + n); int lowerRange = 1, upperRange = 4; cout << countElementsInRange(arr, n, lowerRange, upperRange) << endl; lowerRange = 9; upperRange = 12; cout << countElementsInRange(arr, n, lowerRange, upperRange) << endl; return 0; }
def find_lower_index(arr, x): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] >= x: high = mid - 1 else: low = mid + 1 return low def find_upper_index(arr, y): low, high = 0, len(arr) - 1 while low <= high: mid = (low + high) // 2 if arr[mid] <= y: low = mid + 1 else: high = mid - 1 return high def count_elements_in_range(arr, x, y): arr.sort() lower_index = find_lower_index(arr, x) upper_index = find_upper_index(arr, y) count = upper_index - lower_index + 1 return count arr = [1, 4, 4, 9, 10, 3] lower_range = 1 upper_range = 4 print(count_elements_in_range(arr, lower_range, upper_range)) lower_range = 9 upper_range = 12 print(count_elements_in_range(arr, lower_range, upper_range))
import java.util.Arrays; class Main { static int findLowerIndex(int[] arr, int n, int x) { int low = 0, high = n - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] >= x) high = mid - 1; else low = mid + 1; } return low; } static int findUpperIndex(int[] arr, int n, int y) { int low = 0, high = n - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] <= y) low = mid + 1; else high = mid - 1; } return high; } static int countElementsInRange(int[] arr, int n, int x, int y) { int count = 0; count = findUpperIndex(arr, n, y) - findLowerIndex(arr, n, x) + 1; return count; } public static void main(String[] args) { int[] arr = {1, 4, 4, 9, 10, 3}; int n = arr.length; Arrays.sort(arr); int lowerRange = 1, upperRange = 4; System.out.println(countElementsInRange(arr, n, lowerRange, upperRange)); lowerRange = 9; upperRange = 12; System.out.println(countElementsInRange(arr, n, lowerRange, upperRange)); } }
Question 9: Fountains Installation
Fountains are installed at every position along a one-dimensional garden of length n. Array locations[] represents the coverage limit of these fountains. The ith fountain (where 1sisn) has a coverage limit of locations[i] that can range from the position max((i – locations[i]), 1) to min((i + locations[i]), n ). In other words, the h fountains do not reach outside the boundaries of the garden. In the beginning,all the fountains are switched off. Determine the minimum number of fountains that need to be activated to cover the n length garden by water.
Example
- n = 3
- locations[] = {0, 2, 13, then
- For position 1: locations[1] = 0, max((1 – 0),
- 1) to mini (1+0), 3) gives range = 1 to 1
- For position 2: locations[2] = 2, max((2-2),
- 1) to min( (2+2), 3) gives range = 1 to 3
- For position 3: locations[3] = 1, max( (3-1),
- 1) to min( (3+1), 3) gives range = 2 to 3
- For position 1: locations[1] = 0, max((1 – 0),
For the entire length of this garden to be covered, only the fountain at position 2 needs to be activated.
Function Description
Complete the function fountainActivation in the editor below.
fountainActivation has the following Parameter:
- int locations[n]: the fountain locations
Returns
- int: the minimum number of fountains that must be activated
Constraints
- 1<_n<_ 10^5
- O<_locations[i] <_ mini (n,100) (where 1 <_1<_10^5)
► Input Format For Custom Testing
Sample Case 0
Sample Input For Custom Testing
- 3 ->locations[] size n = 3
- 1 ->locations[] [1, 1, 1
- 1 ->Sample Output
Sample Output
- 1
Explanation
Here, locations = {1, 1, 13
- For position 1: locations[1] = 1, maxi (1 -1), 1) to min((1+1), 3) gives range = 1 to 2
- For position 2: locations[2] = 1, max( (2 -1), 1) to min( (2+1), 3) gives range = 1 to 3
- For position 3: locations[3] = 1, max((3 -1), 1) to min((3+1), 3) gyes range = 2 to 3
If the 2nd fountain is active, the range from position 7 to 3 will be covered. The total number of fountains needed is 1.
#include<bits/stdc++.h> #define ll long long using namespace std; bool compare(pair < int, int > A, pair < int, int > B) { if (A.first = B.first) return A.second < B.second; return A.first < B.first; } int solve(int location[], int n) { pair < int, int > range[n]; for (int i = 0; i < n; i++) { int id = i + 1; range[i].first = max(1, id - location[i]); range[i].second = min(n, id + location[i]); } sort(range, range + n, compare); int i = 0; int ans = 0; while (i < n) { pair < int, int > p = range[i]; ans++; while (i + 1 < n && range[i].first == range[i + 1].first) { p.second = max(p.second, range[i + 1].second); i++; } //cout<<p.second<<" "<<i<<endl; while (i < n && range[i].second <= p.second) i++; //cout<<p.second<<" "<<i<<endl; } return ans; } int main() { int n; cin >> n; int location[n]; for (int i = 0; i < n; i++) cin >> location[i]; cout << solve(location, n) << endl; return 0; }
import java.util.*; class Main { static int minCntFoun(int a[], int N) { int[] dp = new int[N + 1]; Arrays.fill(dp, -1); // Mark the reachable indices for each fountain for (int i = 0; i < N; i++) { int left = Math.max(i - a[i], 0); int right = Math.min(i + a[i]+1, N); dp[left] = Math.max(dp[left], right); } int cntfount = 1; int idxRight = dp[0]; int idxNext = 0; // Traverse the reachable indices and activate fountains for (int i = 0; i < N; i++) { idxNext=Math.max(idxNext,dp[i]); if(i==idxRight){ cntfount++; idxRight = idxNext; } } return cntfount; } // Driver Code public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n = scan.nextInt(); int[] location=new int[n]; for(int i=0;i < n;i++){ location[i]=scan.nextInt(); } System.out.print(minCntFoun(location, n)); } }
Question 10 : Death Note
Problem Statement :
Ryuk, the Shinigami (God of death) had allowed Light Yagami, a school student, to kill as many people as he can by using a death note. But writing the names barely will allow other people to watch them. So he encrypts the names using digits, where a means 1, b means 2 and so on upto z is 26. Now if he gives numbers, there is a communication error because a number string can be decrypted by the death note in various ways and eventually killing them all. If everyone in the world has a unique name, for a given number, how many people can die?
NOTE THAT: There is every possible name in the world with the 26 letters, and capital or small letters is not a problem.
Input format:
A number stream denoting the first name’s encrypted version
Output Format:
Number of people dying by this.
Constraints:
1<=stream length<=10^8
Sample Input: 1267
Sample Output: 3
Output Specification:Two people of the name azg and lfg die.
#include <bits/stdc++.h> using namespace std; string s; int ans; void func(int i, int n) { if (i == n - 1 || i == n) { ans++; return; } if (s[i] == '1') func(i + 2, n); else if (s[i] == '2' && s[i + 1] < '7') func(i + 2, n); func(i + 1, n); } int main() { ans = 0; cin >> s; func(0, s.length()); cout << ans; }
import java.util.*; class Main { static String s; static int ans; public static void func(int i, int n) { if (i == n - 1 || i == n) { ans++; return; } if (s.charAt(i) == '1') func(i + 2, n); else if (s.charAt(i) == '2' && s.charAt(i + 1) < '7') func(i + 2, n); func(i + 1, n); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); s = sc.next(); func(0, s.length()); System.out.println(ans); } }
def solve(s, n): if n == 0 or n == 1: return 1 ans = 0 if s[n - 1] > "0": ans = solve(s, n - 1) if s[n - 2] == "1" or (s[n - 2] == "2" and s[n - 1] < "7"): ans += solve(s, n - 2) return ans s = input() print(solve(s, len(s)))
FAQ's related ConvenGenius Hiring Process
Question 1: What kind of company is ConveGenius ?
ConveGenius is an EdTech Company that provides Affordable Educational Solutions for children of Rural areas of our country. They have Personalized and Adaptive Learning Platform that enables a specific, contextual approach that focuses on what learners need and guides teachers to teach better.
Question 2: What is the eligibility criteria for Convegenius hiring process?
Convegenius has following eligibility criteria for SDE intern role such as:
- Minimum 6 C.G.P.A or Equivalent % throughout academic.
- B.Tech – CSE or IT.
- No current backlog allowed.
Question 3: What is the Selection process of Convegenius?
Convegenius selection process includes following steps:
- Online Assessment
- HR Interview
- 2 Rounds of Technical Interviews
Question 4: What are the skills required for Convegenius Hiring process ?
For Convegenius SDE role you must have good command in following skills:
- Data Structures and Algorithms
- Java
- JavaScript
- ReactJS / Node JS
- SQL
- DBMS
- Operating Systems
Question 5: What is the salary in Convegenius?
For SDE Role:
- During Internship : ₹ 3 LPA
- Post Internship Completion: For Full Time Role = ₹ 15 LPA.
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others