SAP
100+ Magic Edtech Interview Questions and Answers
Q1. Duplicate Integer in Array
Given an array ARR
of size N
, containing each number between 1 and N-1
at least once, identify the single integer that appears twice.
Input:
The first line contains an integer, 'T', r...read more
Identify the duplicate integer in an array containing numbers between 1 and N-1.
Iterate through the array and keep track of the frequency of each element using a hashmap.
Return the element with a frequency greater than 1 as the duplicate integer.
Time complexity can be optimized to O(N) using Floyd's Tortoise and Hare algorithm.
Example: For input [1, 2, 3, 4, 4], the output should be 4.
Q2. Given a 10 digit number, sort the individual digits of the number.
Sort the individual digits of a 10 digit number.
Convert the number to a string to access individual digits
Use a sorting algorithm to sort the digits
Convert the sorted digits back to a number
Q3. Multilevel Inheritance Implementation
Create a series of classes to demonstrate multilevel inheritance.
Explanation:
Create three classes to illustrate multilevel inheritance.
GrandFather
: This class should ha...read more
Demonstrate multilevel inheritance with classes GrandFather, Father, and Son with specific attributes and methods.
Create a class GrandFather with a parameterized constructor and attribute grandFatherName.
Create a class Father inheriting from GrandFather with an additional attribute fatherName.
Create a class Son inheriting from Father with an additional attribute sonName and a method printName to display all names in a specific format.
Ensure constructors initialize attributes ...read more
Q4. Reverse Linked List Problem Statement
Given a singly linked list of integers, return the head of the reversed linked list.
Example:
Initial linked list: 1 -> 2 -> 3 -> 4 -> NULL
Reversed linked list: 4 -> 3 -> 2...read more
Reverse a singly linked list of integers and return the head of the reversed linked list.
Iterate through the linked list and reverse the pointers to point to the previous node.
Keep track of the current, previous, and next nodes while reversing the linked list.
Update the head of the reversed linked list as the last node encountered during reversal.
Q5. Overlapping Intervals Problem Statement
You are given the start and end times of 'N' intervals. Write a function to determine if any two intervals overlap.
Note:
If an interval ends at time T and another interv...read more
Given start and end times of intervals, determine if any two intervals overlap.
Iterate through intervals and check if any two intervals overlap by comparing their start and end times
Sort intervals based on start times for efficient comparison
Consider edge cases where intervals end and start at the same time
Q6. BFS Traversal in a Graph
Given an undirected and disconnected graph G(V, E) where V vertices are numbered from 0 to V-1, and E represents edges, your task is to output the BFS traversal starting from the 0th ve...read more
BFS traversal in a disconnected graph starting from vertex 0.
Implement BFS algorithm to traverse the graph starting from vertex 0.
Explore neighbor nodes first before moving to the next level neighbors.
Consider the bidirectional nature of edges in an undirected graph.
Output the BFS traversal sequence for each test case in a separate line.
Q7. Find All Anagrams Problem Statement
Given a string STR and a non-empty string PTR, identify all the starting indices of anagrams of PTR within STR.
Explanation:
An anagram of a string is another string that can...read more
Given a string STR and a non-empty string PTR, find all starting indices of anagrams of PTR within STR.
Create a frequency map of characters in PTR.
Use sliding window technique to check anagrams in STR.
Return the starting indices of anagrams found.
Q8. LCA of Binary Tree Problem Statement
You are given a binary tree consisting of distinct integers and two nodes, X
and Y
. Your task is to find and return the Lowest Common Ancestor (LCA) of these two nodes.
The ...read more
Find the Lowest Common Ancestor (LCA) of two nodes in a binary tree.
Traverse the binary tree to find the paths from the root to nodes X and Y.
Compare the paths to find the last common node, which is the LCA.
Handle cases where one node is an ancestor of the other.
Consider edge cases like when X or Y is the root node.
Implement a recursive or iterative solution to find the LCA efficiently.
Q9. Next Permutation Problem Statement
You are given a permutation of 'N' integers. A sequence of 'N' integers is considered a permutation if it includes all integers from 1 to 'N' exactly once. Your task is to rea...read more
The task is to rearrange a given permutation of 'N' integers to form the lexicographically next greater permutation.
Iterate from right to left to find the first element that is smaller than the element to its right.
Swap this element with the smallest element to its right that is greater than it.
Reverse the elements to the right of the swapped element to get the lexicographically next greater permutation.
Q10. Maximum of All Subarrays of Size k
Given an array of 'N' non-negative integers and an integer 'K', your task is to find the maximum elements for each subarray of size 'K'.
Input:
The first line contains an inte...read more
Find the maximum elements for each subarray of size 'K' in an array of non-negative integers.
Iterate through the array and maintain a deque to store the indices of elements in decreasing order.
Pop elements from the deque if they are out of the current window of size 'K'.
The front of the deque will always have the index of the maximum element in the current window.
Q11. Reverse the String Problem Statement
You are given a string STR
which contains alphabets, numbers, and special characters. Your task is to reverse the string.
Example:
Input:
STR = "abcde"
Output:
"edcba"
Input...read more
Reverse a given string containing alphabets, numbers, and special characters.
Iterate through the string from the end to the beginning and append each character to a new string.
Use built-in functions like reverse() or StringBuilder in languages like Python or Java for efficient reversal.
Handle special characters and numbers while reversing the string.
Ensure to consider the constraints provided in the problem statement.
Test your solution with different test cases to validate th...read more
Q12. How do you tackle something that you can't find a solution to?
When faced with an unsolvable problem, I break it down, research, seek help, experiment, and iterate until a solution is found.
Break down the problem into smaller, manageable parts
Research and gather information related to the problem
Seek help from colleagues, online communities, or experts
Experiment with different approaches or solutions
Iterate and refine the solution based on feedback and results
Q13. Covid Vaccination Distribution Problem
As the Government ramps up vaccination drives to combat the second wave of Covid-19, you are tasked with helping plan an effective vaccination schedule. Your goal is to ma...read more
Maximize the number of vaccines administered on a specific day while adhering to certain rules.
Given n days, maxVaccines available, and a specific dayNumber, distribute vaccines to maximize on dayNumber
Administer positive number of vaccines each day with a difference of 1 between consecutive days
Ensure sum of vaccines distributed does not exceed maxVaccines
Output the maximum number of vaccines administered on dayNumber for each test case
Q14. Right View of Binary Tree
Given a binary tree of integers, your task is to output the right view of the tree.
The right view of a binary tree includes the nodes that are visible when the tree is observed from t...read more
The task is to output the right view of a binary tree, which includes the nodes visible when observed from the right.
Traverse the tree level by level and keep track of the rightmost node at each level.
Use a queue for level order traversal and a map to store the rightmost nodes.
Print the values of the rightmost nodes stored in the map as the right view of the tree.
Q15. Level Order Traversal Problem Statement
Given a binary tree of integers, return the level order traversal of the binary tree.
Input:
The first line contains an integer 'T', representing the number of test cases...read more
The task is to implement a function that returns the level order traversal of a binary tree given in level order.
Create a queue to store nodes for level order traversal
Start with the root node and enqueue it
While the queue is not empty, dequeue a node, print its value, and enqueue its children
Repeat until all nodes are traversed
Q16. Subset Sum Problem Statement
Given an array of integers, find the sum of all subsets in non-decreasing order of the given array.
Example:
Input:
N = 3, array = [1, 2]
Output:
[0, 1, 2, 3]
Explanation:
The subse...read more
Find sum of all subsets in non-decreasing order of given array.
Use recursion to generate all subsets of the array
Calculate sum of each subset and store in a list
Sort the list in non-decreasing order to get the final result
Q17. Longest Increasing Subsequence Problem Statement
Given 'N' students standing in a row with specific heights, your task is to find the length of the longest strictly increasing subsequence of their heights, ensu...read more
Find the length of the longest strictly increasing subsequence of heights of students in a row.
Iterate through the heights array and for each element, find the length of the longest increasing subsequence ending at that element.
Use dynamic programming to keep track of the longest increasing subsequence length for each element.
Return the maximum length found as the result.
Q18. Merge Sort Problem Statement
You are given a sequence of numbers, ARR
. Your task is to return a sorted sequence of ARR
in non-descending order using the Merge Sort algorithm.
Explanation:
The Merge Sort algorit...read more
Implement Merge Sort algorithm to sort a sequence of numbers in non-descending order.
Divide the input array into two halves recursively until each array has only one element.
Merge the sorted halves to produce a completely sorted array.
Time complexity of Merge Sort is O(n log n).
Example: Input: [3, 1, 4, 1, 5], Output: [1, 1, 3, 4, 5]
Q19. Boundary Traversal of Binary Tree Problem Statement
Given a binary tree consisting of integers, your task is to provide the boundary nodes of this tree in an anti-clockwise direction, starting with the root nod...read more
Boundary traversal of a binary tree to find left boundary, right boundary, and leaf nodes in an anti-clockwise direction.
Perform a pre-order traversal to get the left boundary nodes
Perform an in-order traversal to get the leaf nodes
Perform a post-order traversal to get the right boundary nodes
Combine the results to get the boundary nodes in anti-clockwise direction
Q20. Find the Middle of a Linked List
This problem requires you to return a pointer that references the middle node of a singly linked list.
Explanation:
If the number of elements in the linked list is odd, return t...read more
Return the middle node of a singly linked list, considering odd and even number of elements.
Traverse the linked list with two pointers, one moving twice as fast as the other
When the fast pointer reaches the end, the slow pointer will be at the middle
Return the node pointed to by the slow pointer as the middle node
Q21. Zig-Zag String Problem Statement
Given a string STR
of size N
and an integer M
representing the number of rows in the zig-zag pattern, return the string formed by concatenating all rows when the string STR
is w...read more
Arrange a string in zig-zag pattern with given number of rows and concatenate the rows.
Iterate through the string and distribute characters to rows based on zig-zag pattern
Concatenate the characters in each row to get the final result
Handle edge cases like when number of rows is 1 or equal to the length of the string
Q22. Discuss a DBMS consisting of college faculty, professors, courses and students.
A DBMS for managing college faculty, professors, courses, and students.
The DBMS should have tables for faculty, professors, courses, and students.
Each table should have appropriate attributes to store relevant information.
Relationships can be established between tables using foreign keys.
Queries can be used to retrieve information about faculty, professors, courses, and students.
The DBMS can be used to track enrollment, grades, and other relevant data.
Q23. Longest Substring Without Repeating Characters Problem Statement
Given a string S
of length L
, determine the length of the longest substring that contains no repeating characters.
Example:
Input:
"abacb"
Output...read more
Find the length of the longest substring without repeating characters in a given string.
Use a sliding window approach to keep track of the longest substring without repeating characters.
Use a hashmap to store the index of each character as it appears in the string.
Update the start index of the window when a repeating character is found.
Calculate the maximum length of the substring as the window slides through the string.
Q24. Floyd Warshall Algorithm Problem
You are given a directed weighted graph with 'N' vertices, labeled from 1 to 'N', and 'M' edges. Each edge connects two nodes 'u' and 'v' with a weight 'w', representing the dis...read more
The Floyd Warshall algorithm is used to find the shortest paths between all pairs of vertices in a graph, including graphs with negative edge weights.
The algorithm works by considering all pairs of vertices and all intermediate vertices to find the shortest path.
It can handle graphs with negative edge weights, but not negative weight cycles.
The time complexity of the algorithm is O(N^3), where N is the number of vertices.
Example: Given a graph with 4 vertices and 5 edges, fin...read more
Q25. Longest Unique Substring Problem Statement
Given a string input of length 'n', your task is to determine the length of the longest substring that contains no repeating characters.
Explanation:
A substring is a ...read more
Find the length of the longest substring with unique characters in a given string.
Use a sliding window approach to keep track of the longest substring without repeating characters.
Use a hashmap to store the index of each character in the string.
Update the start index of the window when a repeating character is encountered.
Calculate the maximum length of the window as you iterate through the string.
Q26. Binary Pattern Problem Statement
Given an input integer N
, your task is to print a binary pattern as follows:
Example:
Input:
N = 4
Output:
1111
000
11
0
Explanation:
The first line contains 'N' 1s. The next line ...read more
Print a binary pattern based on input integer N in a specific format.
Iterate from 1 to N and print N - i + 1 numbers alternatively as 1 or 0 in each line
Follow the pattern of increasing 1s and decreasing 0s in each line
Handle the number of test cases and constraints as specified
Q27. Nth Fibonacci Number Problem Statement
Calculate the Nth term in the Fibonacci sequence, where the sequence is defined as follows: F(n) = F(n-1) + F(n-2)
, with initial conditions F(1) = F(2) = 1
.
Input:
The inp...read more
Calculate the Nth Fibonacci number efficiently using recursion or dynamic programming.
Implement a recursive function to calculate the Nth Fibonacci number.
Use memoization to store previously calculated Fibonacci numbers for efficiency.
Consider using dynamic programming to optimize the solution.
Handle edge cases such as N = 1 or N = 2 separately.
Ensure the solution works efficiently for large values of N (up to 10000).
Q28. Prime Numbers Identification
Given a positive integer N
, your task is to identify all prime numbers less than or equal to N
.
Explanation:
A prime number is a natural number greater than 1 that has no positive d...read more
Identify all prime numbers less than or equal to a given positive integer N.
Iterate from 2 to N and check if each number is prime
Use the Sieve of Eratosthenes algorithm for efficient prime number identification
Optimize by only checking up to the square root of N for divisors
Two people with torch cross, one returns, two faster people cross, one with torch returns, two slower people cross.
Two slower people cross first (A and B), A returns with torch (1 minute)
Two faster people cross (C and D), B returns with torch (2 minutes)
Two slower people cross last (A and B) (10 minutes)
Q30. Print Permutations - String Problem Statement
Given an input string 'S', you are tasked with finding and returning all possible permutations of the input string.
Input:
The first and only line of input contains...read more
Return all possible permutations of a given input string.
Use recursion to generate all possible permutations of the input string.
Swap characters at different positions to generate permutations.
Handle duplicate characters in the input string by using a set to store unique permutations.
Q31. Factorial of a Number Problem Statement
You are provided with an integer 'N'. Your task is to calculate and print the factorial of 'N'. The factorial of a number 'N', denoted as N!, is the product of all positi...read more
Calculate and print the factorial of a given integer 'N'.
Iterate from 1 to N and multiply each number to calculate factorial
Handle edge cases like N=0 or N=1 separately
Use recursion to calculate factorial efficiently
Q32. Write code for LCA in Binary Search Tree.
The code for finding the Lowest Common Ancestor (LCA) in a Binary Search Tree (BST).
Start from the root node and compare it with the given two nodes.
If both nodes are smaller than the current node, move to the left subtree.
If both nodes are greater than the current node, move to the right subtree.
If one node is smaller and the other is greater, then the current node is the LCA.
Continue this process until the LCA is found.
Turn on one switch for a while, then turn it off and turn on another switch. One bulb will be on, one will be off, and one will be warm.
Turn on switch 1 for a few minutes, then turn it off.
Turn on switch 2 and enter the room with bulbs.
The bulb that is on corresponds to switch 2, the warm bulb corresponds to switch 1, and the off bulb corresponds to switch 3.
Q34. Bubble Sort Problem Statement
Sort the given unsorted array consisting of N non-negative integers in non-decreasing order using the Bubble Sort algorithm.
Input:
The first line contains an integer 'T' represent...read more
Bubble Sort algorithm is used to sort an array of non-negative integers in non-decreasing order.
Iterate through the array and compare adjacent elements, swapping them if they are in the wrong order.
Repeat this process until the array is sorted.
Time complexity of Bubble Sort is O(n^2) in worst case.
Space complexity of Bubble Sort is O(1) as it is an in-place sorting algorithm.
Q35. Design a parking lot? Design should include -Logic Flow Diagram -E-R diagram (very important) -DB tables with relations between them, preferably normalized -Commands for transaction with tables
Design a parking lot with Logic Flow Diagram, E-R diagram, DB tables with relations, and commands for transactions.
Identify the types of vehicles that will use the parking lot
Determine the number of parking spaces needed for each vehicle type
Create a flow diagram to show the process of entering and exiting the parking lot
Design an E-R diagram to show the relationships between entities such as vehicles, parking spaces, and transactions
Normalize the DB tables to reduce redundan...read more
Q36. Given an array, sort the zeroes from non zeros for example Input: 1 2 0 0 7 4 42 0 0 0 6 Output: 1 2 7 4 42 6 0 0 0 0 0
Sort an array by moving all zeroes to the end.
Iterate through the array and move all non-zero elements to the front.
Count the number of zeroes encountered and append them at the end of the array.
Use two pointers to swap elements and maintain the order.
The minimum number of attempts needed is 14.
Start dropping the first egg from the 14th floor, then move up by one floor for each attempt until the first egg breaks.
Once the first egg breaks, use the second egg to test each floor starting from the last unbroken floor.
The worst-case scenario is dropping the first egg 14 times and the second egg 13 times, totaling 14 attempts.
Q38. Remove Consecutive Duplicates Problem Statement
Given a string S, your task is to recursively remove all consecutive duplicate characters from the string.
Input:
String S
Output:
Output string
Constraints:
- 1 <...read more
Recursively remove consecutive duplicate characters from a string.
Use recursion to check if the current character is the same as the next character, if so skip the next character
Base case: if the string is empty or has only one character, return the string
Example: Input: 'aaabcc', Output: 'abc'
Q39. Given a tree, WAP such that a matrix is generated so that: Tree: 1 / 2 3 | / 4 5 6 Matrix: 0 1 2 3 4 5 6 1 0 1 1 1 1 1 2 0 0 0 1 0 0 3 0 0 0 0 1 1 4 0 0 0 0 0 0 5 0 0 0 0 0 0 6 0 0 0 0 0 0
WAP to generate a matrix from a given tree.
Create a 2D array to store the matrix
Traverse the tree and fill the matrix accordingly
Use BFS or DFS to traverse the tree
The matrix will be symmetric along the diagonal
Q40. Write a function to know if the check-box is checked in javascript.
Function to check if a checkbox is checked in JavaScript
Use the 'checked' property of the checkbox element
Access the checkbox element using its ID or class name
Return true if checked, false if not checked
ACID properties are a set of properties that guarantee the reliability of transactions in database management systems.
Atomicity ensures that either all operations in a transaction are completed successfully or none of them are. For example, transferring money from one account to another should either be completed in full or not at all.
Consistency ensures that the database remains in a consistent state before and after the transaction. For example, if a transaction violates a ...read more
Make one horizontal cut through the middle of the cake, then make two vertical cuts perpendicular to each other.
Make a horizontal cut through the middle of the cake to create two equal halves.
Make one vertical cut through the center of one of the halves.
Make another vertical cut through the center of the other half, perpendicular to the first cut.
You will end up with 8 equal pieces of cake.
Yes, I can design an ER diagram for an online shopping portal.
Entities: User, Product, Order, Payment, Cart
Relationships: User places Order, Order contains Product, Payment for Order, User has Cart
Attributes: User (id, name, email), Product (id, name, price), Order (id, date), Payment (id, amount)
malloc() is used to dynamically allocate memory in C, while free() is used to release allocated memory.
malloc() allocates a block of memory of specified size and returns a pointer to the beginning of the block.
free() deallocates the memory previously allocated by malloc() or calloc().
Example: int *ptr = (int*)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
Example: free(ptr); // Deallocates the memory allocated for the integers
Primary key uniquely identifies each record in a table, while unique key ensures that all values in a column are distinct.
Primary key does not allow NULL values, while unique key allows one NULL value.
A table can have only one primary key, but multiple unique keys.
Primary key is automatically indexed, while unique key may or may not be indexed.
Example: In a table of students, student ID can be a primary key as it uniquely identifies each student, while email address can be a ...read more
Q46. what is the difference between Java and C++?
Java is platform-independent and uses automatic memory management, while C++ is faster and allows for more control over memory.
Java is compiled to bytecode and runs on a virtual machine, while C++ is compiled to machine code.
Java has automatic memory management through garbage collection, while C++ requires manual memory management.
Java has a simpler syntax and is easier to learn, while C++ has more complex syntax and is more difficult to master.
Java is used for web developme...read more
Q47. When to use List and Vector of Standard Template Library ?
List is preferred when frequent insertion and deletion is required. Vector is preferred when random access is required.
List is implemented as a doubly-linked list, allowing for efficient insertion and deletion at any position.
Vector is implemented as a dynamic array, allowing for efficient random access.
Use List when the number of elements is expected to change frequently and the order of elements matters less.
Use Vector when the number of elements is fixed or changes infrequ...read more
Q48. Different versions of polymorphism, how to solve the problem of multiple inheritance
Polymorphism can be achieved through method overloading, method overriding, and interfaces. Multiple inheritance can be solved using interfaces.
Method overloading allows multiple methods with the same name but different parameters
Method overriding allows a subclass to provide its own implementation of a method already defined in its superclass
Interfaces provide a way to achieve multiple inheritance by allowing a class to implement multiple interfaces
Diamond problem in multipl...read more
Q49. What is polymorphism? Explain using a real life example
Polymorphism is the ability of an object to take on many forms. It allows objects of different classes to be treated as the same type.
Polymorphism allows a single interface to be used for different types of objects.
It enables code reusability and flexibility in object-oriented programming.
For example, a parent class 'Animal' can have multiple child classes like 'Dog', 'Cat', and 'Bird'. They can all be treated as 'Animal' objects.
Each child class can have its own implementati...read more
Q50. Write a query to find name of a player with maximum number of runs in a match on given date and given venue
Query to find player with maximum runs in a match on given date and venue
Use MAX() function to find maximum runs
Join tables for player name, match details and runs scored
Filter by given date and venue
Order by runs scored and limit to 1 result
Q51. Different types of polymorphism, the diamond problem, and how can it be avoided?
Polymorphism refers to the ability of an object to take on many forms. The diamond problem occurs in multiple inheritance.
Polymorphism can be achieved through method overloading and method overriding.
Method overloading allows multiple methods with the same name but different parameters.
Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass.
The diamond problem arises in languages that support multiple inheritan...read more
Operator overloading in OOP allows custom behavior for operators like +, -, *, etc.
Operator overloading is a feature in OOP that allows defining custom behavior for operators
Example: Overloading the + operator to concatenate strings or add two numbers
Example: Overloading the * operator to perform matrix multiplication
BCNF is a normal form in database management systems that ensures all determinants are candidate keys.
BCNF stands for Boyce-Codd Normal Form.
It is a stricter version of 3NF (Third Normal Form).
In BCNF, every determinant must be a candidate key.
It helps in reducing redundancy and anomalies in the database.
Example: If a table has columns A, B, and C, and A determines B and B determines C, then it is not in BCNF unless A is a candidate key.
Use two identical wires to measure 45 minutes by burning them at different ends.
Burn one end of the first wire and both ends of the second wire simultaneously.
When the first wire burns out completely (30 minutes), light the other end of the second wire.
When the second wire burns out completely (15 minutes), 45 minutes have passed.
By burning one candle at both ends, you can calculate 45 minutes using only 2 candles.
Light one end of the first candle and both ends of the second candle simultaneously.
When the second candle burns out completely, 30 minutes have passed.
Light the other end of the first candle and let it burn. When it meets the first end, 15 minutes have passed.
Q56. What is foreign key? can foreign key be Null?
Foreign key is a column in a table that refers to the primary key of another table.
It establishes a relationship between two tables.
It ensures referential integrity.
It can be null, but only if it is defined as nullable.
It helps in joining tables.
Example: Customer table has a foreign key to the Order table's primary key.
Example: Order table's foreign key can be null if the order has not been placed by any customer yet.
Q57. What is normalization? why should we do normalization?
Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity.
Normalization involves breaking down a database into smaller, more manageable tables.
It helps to eliminate data redundancy and inconsistencies.
Normalization ensures that each table has a primary key and that data is stored in a logical and consistent manner.
It improves data integrity and reduces the likelihood of errors and inconsistencies.
Normalization is important f...read more
The database design for an ATM system should include tables for users, accounts, transactions, and ATM machines.
Create a table for users with fields like user_id, name, pin, etc.
Create a table for accounts with fields like account_id, user_id, balance, etc.
Create a table for transactions with fields like transaction_id, account_id, amount, date, etc.
Create a table for ATM machines with fields like atm_id, location, status, etc.
AES is a more secure and efficient cipher compared to DES.
AES has a block size of 128 bits, while DES has a block size of 64 bits.
AES supports key sizes of 128, 192, or 256 bits, while DES supports only 56-bit keys.
AES is considered more secure and efficient than DES due to its stronger encryption algorithm and larger key sizes.
Q60. Normalized form is better or storing in a single table/ 2 tables is better?
Normalized form is better for data consistency and scalability.
Normalized form reduces data redundancy and ensures data consistency.
Normalized form allows for easier scalability and maintenance.
Single table/2 tables may be appropriate for small, simple datasets.
Normalized form may require more complex queries to retrieve data.
Normalized form may require more storage space due to additional tables.
Example: Normalized form for a customer database would have separate tables for ...read more
Normalization is the process of organizing data in a database to reduce redundancy and improve data integrity.
Normalization involves breaking down a database into smaller, more manageable tables.
It helps in reducing data redundancy by storing data in a structured way.
There are different normal forms such as 1NF, 2NF, 3NF, BCNF, etc., each with specific rules to follow.
Normalization ensures data integrity and reduces the chances of anomalies like insertion, update, and deletio...read more
Public cloud is shared infrastructure available to anyone, while private cloud is dedicated infrastructure for a single organization.
Public cloud is accessible to multiple organizations or users, while private cloud is exclusive to a single organization.
Public cloud services are provided over the internet, while private cloud services can be hosted on-premises or in a dedicated data center.
Public cloud offers cost-effective scalability and flexibility, while private cloud off...read more
Q63. Which data structures the candidate is confident in development and why?
I am confident in developing arrays, linked lists, and hash tables.
Arrays are simple and efficient for storing and accessing data.
Linked lists are useful for dynamic data structures and efficient insertion/deletion.
Hash tables provide fast access to data with key-value pairs.
Q64. Find Minimum and Maximum of an array in only one traversal
Find the minimum and maximum values in an array in a single traversal.
Initialize min and max variables with the first element of the array
Iterate through the array and update min and max if a smaller or larger value is found
Return the min and max values
Q65. Why String" class is immutable in Java environment?
String class is immutable in Java to ensure security, thread-safety, and performance.
Immutable objects are thread-safe as they cannot be modified by multiple threads simultaneously.
Immutable objects are also secure as they cannot be modified by malicious code.
String pool is possible because of immutability, which improves performance by reducing memory usage.
StringBuffer and StringBuilder classes are used for mutable string operations.
Q66. What is C++? Difference between deep and shallow copy?
C++ is a programming language. Deep copy creates a new object and copies all values, while shallow copy creates a reference to the original object.
C++ is a general-purpose programming language
Deep copy creates a new object with its own copy of the data
Shallow copy creates a reference to the original object
Deep copy is safer but can be slower and consume more memory
Shallow copy is faster but can lead to unexpected behavior if the original object is modified
C is a procedural programming language while C++ is a multi-paradigm programming language with object-oriented features.
C is a procedural programming language while C++ supports both procedural and object-oriented programming.
C does not support classes and objects while C++ does.
C does not have built-in support for exception handling while C++ does.
C does not have namespaces while C++ does.
C does not have function overloading while C++ does.
C is a procedural programming language while C++ is an object-oriented programming language with features like classes and inheritance.
C is a procedural programming language, while C++ is a multi-paradigm language with support for object-oriented programming.
C does not support classes and objects, while C++ does.
C uses structures for data organization, while C++ uses classes.
C does not have features like inheritance and polymorphism, which are present in C++.
C++ allows functi...read more
Q69. Use of 'finally' block in Java? When finally" block is not called in which cases?
The 'finally' block in Java is used to execute code after try-catch blocks, even if an exception is thrown.
The 'finally' block is always executed, regardless of whether an exception is thrown or caught.
It is used to release resources like database connections, network connections, etc.
If the JVM exits while the try or catch code is being executed, then the 'finally' block may not execute.
If the thread executing the try or catch code is interrupted or killed, the 'finally' blo...read more
Q70. Given a chessboard find maximum number of squares present
Given a chessboard, find the maximum number of squares present.
Start with the smallest square and count all possible squares
Use the formula n*(n+1)*(2n+1)/6 to find the total number of squares in an n x n chessboard
Add up the squares of all sizes from 1 to n to get the maximum number of squares
For example, an 8 x 8 chessboard has 204 squares
Various SQL queries related to data manipulation and retrieval were asked during the interview.
Basic SELECT queries to retrieve data from a single table
JOIN queries to retrieve data from multiple tables based on a common column
Aggregate functions like COUNT, SUM, AVG, etc. to perform calculations on data
Subqueries to retrieve data based on the result of another query
UPDATE queries to modify existing data in a table
DELETE queries to remove specific records from a table
Q72. Write a program for an operator(=) such that it behaves differently for integer and character
The program should differentiate between integers and characters when using the assignment operator (=).
Check the data type of the variable before assigning a value.
Use conditional statements to perform different actions based on the data type.
For integers, assign the value directly. For characters, convert the character to its ASCII value and assign it.
Q73. Can unique key be a primary key?
Yes, a unique key can be a primary key.
A primary key is a unique identifier for a record in a table.
A unique key is a constraint that ensures the values in a column are unique.
A unique key can be used as a primary key if it meets the requirements.
A primary key cannot have NULL values, while a unique key can have one NULL value.
Q74. How to implement queue using stack?
Implementing a queue using stack involves using two stacks to simulate the behavior of a queue.
Create two stacks, one for enqueue and one for dequeue operations.
For enqueue operation, push the element onto the enqueue stack.
For dequeue operation, if the dequeue stack is empty, pop all elements from the enqueue stack and push onto the dequeue stack.
Pop the top element from the dequeue stack for dequeue operation.
Write-ahead logging is a technique used in DBMS to ensure that changes are recorded in the log before they are applied to the database.
Write-ahead logging ensures that changes are first written to the log file before being applied to the database to maintain data integrity.
It helps in recovering the database in case of a system crash or failure by replaying the log entries to bring the database back to a consistent state.
This technique is commonly used in databases like Postg...read more
Q76. If you have 1 million requests how will you manage that
I would use load balancing, caching, and scaling techniques to manage the 1 million requests.
Implement load balancing to distribute requests evenly across multiple servers.
Utilize caching to store frequently accessed data and reduce response times.
Scale horizontally by adding more servers to handle the increased load.
Optimize code and database queries to improve performance.
Monitor system performance and make adjustments as needed.
Query to find the nth highest salary in a database
Use the ORDER BY clause to sort salaries in descending order
Use the LIMIT clause to specify the nth highest salary
Consider handling cases where there may be ties for the nth highest salary
Q78. Given a chessboard find the maximum number of squares present?
The maximum number of squares on a chessboard is 64.
The chessboard has 64 squares in total.
The number of squares on a chessboard can be calculated using the formula n^2, where n is the number of rows or columns.
In this case, n = 8 (8 rows and 8 columns), so the maximum number of squares is 8^2 = 64.
Q79. Find Min and Max of an array in only one traversal
To find min and max of an array in one traversal, initialize min and max to first element and compare with rest.
Initialize min and max to first element of array
Traverse the array and compare each element with min and max
Update min and max accordingly
Return min and max
RDBMS is a type of DBMS that manages data in a structured format using tables with relationships.
RDBMS enforces referential integrity through foreign keys, while DBMS does not.
RDBMS supports ACID properties (Atomicity, Consistency, Isolation, Durability), while DBMS may not.
RDBMS allows for normalization of data to reduce redundancy, while DBMS does not have this feature.
Examples of RDBMS include MySQL, Oracle, SQL Server. Examples of DBMS include Microsoft Access, FoxPro.
Q81. Find the repeated number in a list of contagious numbers.
Find the repeated number in a list of contagious numbers.
Iterate through the list and keep track of the numbers seen so far
If a number is already seen, it is the repeated number
Use a hash set or dictionary to efficiently check for duplicates
If the list is sorted, use two pointers to find the repeated number
Deadlock avoidance schemes are strategies used to prevent deadlocks in a system.
Banker's algorithm: Ensures that the system will never enter an unsafe state by keeping track of available resources and only granting a request if it does not lead to a deadlock.
Wait-die and Wound-wait: Two deadlock prevention schemes used in transaction processing systems to avoid deadlocks by allowing transactions to wait or abort based on their timestamps.
Resource allocation graph: A graph-bas...read more
A virtual function in C++ is a function that is declared within a base class and is redefined by a derived class.
Virtual functions allow a function to be overridden in a derived class.
They are used in polymorphism to achieve runtime binding.
The base class function must be declared as virtual for dynamic binding to occur.
Example: virtual void display() = 0; // pure virtual function
Q84. Given a string “I LOVE CODING”, print “CODING LOVE I”
The given string needs to be reversed and the words need to be rearranged.
Split the string into an array of words
Reverse the array
Join the array elements with a space in between
Q85. Difference between deep and shallow copy?
Deep copy creates a new object with a new memory address, while shallow copy creates a new reference to the same memory address.
Deep copy duplicates the object and all its nested objects, while shallow copy only duplicates the top-level object.
Deep copy is slower and more memory-intensive than shallow copy.
Shallow copy can lead to unexpected behavior if the original object is modified.
In Python, deep copy can be achieved using the deepcopy() function from the copy module, whi...read more
Q86. What is primary key? unique key?
Primary key is a column or set of columns that uniquely identifies each row in a table. Unique key is a constraint that ensures uniqueness of values in a column or set of columns.
Primary key is used to enforce data integrity and ensure that each row in a table can be uniquely identified.
Unique key is used to ensure that no two rows in a table have the same values in a column or set of columns.
Primary key can be a single column or a combination of columns, while unique key can...read more
Q87. What do you think SAP does?
SAP is a multinational software corporation that provides enterprise software solutions.
SAP develops and sells software for managing business operations and customer relations.
Their software helps organizations streamline processes, improve efficiency, and make data-driven decisions.
SAP offers a wide range of products, including ERP (Enterprise Resource Planning), CRM (Customer Relationship Management), and SCM (Supply Chain Management) solutions.
Their software is used by com...read more
Design an e-commerce website similar to Flipkart or Amazon.
Implement user-friendly interface for easy navigation
Include search functionality with filters for products
Incorporate secure payment gateway for transactions
Provide personalized recommendations based on user behavior
Include customer reviews and ratings for products
Implement order tracking and delivery status updates
Offer various payment options like credit/debit cards, net banking, and COD
Q89. Reverse a linked list with and without using Recursion
Reverse a linked list with and without using Recursion
Iterative approach: Use three pointers to reverse the links between nodes
Recursive approach: Recursively reverse the rest of the list and then fix the links
Q90. class hierarchy, List the number of VTables created
The number of VTables created in a class hierarchy depends on the number of virtual functions and the number of derived classes.
VTables are used in object-oriented programming languages to implement dynamic dispatch.
Each class with at least one virtual function has its own VTable.
Derived classes inherit the VTable of their base class and add their own entries for any additional virtual functions.
The total number of VTables created in a class hierarchy is equal to the number o...read more
Q91. Difference between ArrayList and LinkedList? Their other implementations? pros and cons?
ArrayList and LinkedList are both implementations of List interface in Java. ArrayList is backed by an array while LinkedList is backed by a doubly linked list.
ArrayList provides constant time access to elements while LinkedList provides constant time insertion and deletion at any position.
ArrayList is better for random access and LinkedList is better for sequential access.
Other implementations of List interface include Vector, Stack, CopyOnWriteArrayList.
Vector is similar to...read more
Q92. Difference between StringBuilder and StringBuffer classes in Java?
StringBuilder is not thread-safe while StringBuffer is thread-safe.
StringBuilder is faster than StringBuffer in single-threaded environments.
StringBuffer is synchronized, making it safe to use in multi-threaded environments.
Both classes are used to manipulate strings, but StringBuilder is preferred for single-threaded environments.
Example: StringBuilder sb = new StringBuilder("Hello");
Example: StringBuffer sb = new StringBuffer("World");
Q93. Whats “preinitialization” View Answer
Preinitialization is the process of initializing data or objects before they are actually needed.
Preinitialization can improve performance by reducing the time needed to initialize data or objects when they are actually needed.
It can also help to avoid delays or interruptions during runtime.
Examples of preinitialization include preloading data into memory, initializing objects in advance, and caching frequently used data.
Q94. Detect a loop in a linked list.
Detect a loop in a linked list.
Use two pointers, one moving at a slower pace than the other.
If there is a loop, the faster pointer will eventually catch up with the slower one.
If the faster pointer reaches the slower pointer, there is a loop in the linked list.
Function overloading is when multiple functions have the same name but different parameters or return types.
Allows multiple functions with the same name but different parameters or return types
Helps improve code readability and maintainability
Example: int add(int a, int b) and float add(float a, float b)
Q96. Difference between REST and SOAP services?
REST is lightweight and uses HTTP for communication, while SOAP is XML-based and has a more complex messaging format.
REST is simpler and easier to use than SOAP.
SOAP is more secure and reliable than REST.
REST uses HTTP methods like GET, POST, PUT, DELETE, while SOAP uses XML messaging format.
REST is better suited for web applications, while SOAP is better suited for enterprise-level applications.
Examples of RESTful services include Twitter, Google Maps, and Amazon S3, while e...read more
A clustered index is a type of index that sorts and stores the data rows in the table based on their key values.
Defines the order in which data is physically stored in a table
Only one clustered index per table
Helps in improving the performance of queries that involve range searches or sorting
Example: Clustered index on a table's primary key
Structure padding is the concept of adding empty bytes to a structure to align its data members on memory boundaries.
Structure padding is done to optimize memory access and improve performance.
Padding is necessary because most processors require data to be aligned on specific memory boundaries for efficient access.
For example, if a structure contains a char followed by an int, padding may be added after the char to align the int on a 4-byte boundary.
Q99. What is pre initialization ?
Pre initialization refers to the process of initializing variables or objects before they are used in a program.
Pre initialization helps avoid errors or unexpected behavior caused by using uninitialized variables.
It is a good practice to pre initialize variables with default values.
Pre initialization can be done using constructors, default values, or initialization blocks.
Example: int count = 0; initializes the variable 'count' with the value 0.
Q100. What is inheritance?
Inheritance is a concept in object-oriented programming where a class inherits properties and behaviors from another class.
Inheritance allows for code reuse and promotes modularity.
The class that is being inherited from is called the superclass or base class.
The class that inherits from the superclass is called the subclass or derived class.
The subclass can access the public and protected members of the superclass.
Inheritance can be single, where a subclass inherits from only...read more
More about working at SAP
Top HR Questions asked in Magic Edtech
Interview Process at Magic Edtech
Top Software Developer Interview Questions from Similar Companies
Reviews
Interviews
Salaries
Users/Month