Beruflich Dokumente
Kultur Dokumente
Technical interview
The programming challenge was seen as how to write the logic, not how to define the data. Object-oriented
programming takes the view that what we really care about are the objects we want to manipulate rather than the
logic required to manipulate them. Examples of objects range from human beings (described by name, address, and
so forth) to buildings and floors (whose properties can be described and managed) down to the little widgets on a
computer desktop (such as buttons and scroll bars).
The first step in OOP is to identify all the objects the programmer wants to manipulate and how they relate to each
other, an exercise often known as data modeling. Once an object has been identified, it is generalized as a class of
objects (think of Plato's concept of the "ideal" chair that stands for all chairs) which defines the kind of data it
contains and any logic sequences that can manipulate it. Each distinct logic sequence is known as a method. Objects
communicate with well-defined interfaces called messages.
The concepts and rules used in object-oriented programming provide these important benefits:
The concept of a data class makes it possible to define subclasses of data objects that share some or all of the
main class characteristics. Called inheritance, this property of OOP forces a more thorough data analysis,
reduces development time, and ensures more accurate coding.
Since a class defines only the data it needs to be concerned with, when an instance of that class (an object) is
run, the code will not be able to accidentally access other program data. This characteristic of data
hiding provides greater system security and avoids unintended data corruption.
The definition of a class is reuseable not only by the program for which it is initially created but also by
other object-oriented programs (and, for this reason, can be more easily distributed for use in networks).
The concept of data classes allows a programmer to create any new data type that is not already defined in
the language itself.
For example consider we have a Class of Cars under which Santro Xing, Alto and WagonR represents individual
objects. In this context each Car Object will have its own, Model,Year of Manufacture, Colour, Top Speed, Engine
Power etc.,which form Properties of the Car class and the associated actions i.e., object functions like Start, Move,
Stop form the Methods of Car class. No memory is allocated when a class is created. Memory is
allocated only when an object is created, i.e., when an instance of a class is created.
3. Concepts of OOPS?
Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its
properties and its functions. Like Human Being, having body parts, and performing various actions.
Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat,
see etc. Male and Female are also classes, but most of the properties and functions are included in HumanBeing,
hence they can inherit everything from class HumanBeing using the concept of Inheritance.
Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being, Male or Female, we
just mean a kind, you, your friend, me we are the forms of these classes. We have a physical existence while a class
is just a logical definition. We are the objects.
Abstraction
Abstraction means, showcasing only the required things to the outside world while hiding the details. Continuing our
example, Human Being's can talk, walk, hear, eat, but the details are hidden from the outside world. We can take
our skin as the Abstraction factor in our case, hiding the inside mechanism.
Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk. Our hands, help us
hold things. This binding of the properties to functions is called Encapsulation.
Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either changing how it is done
or by changing the parts using which it is done. Both the ways have different terms for them.If we walk using our
hands, and not legs, here we will change the parts used to perform something. Hence this is called Overloading.And
if there is a defined way of walking, but I wish to walk differently, but using my legs, like everyone else. Then I can
walk like I want, this will be called as Overriding.
Technical Interview:
1. Tell me about yourself. (HR Question)
Ams: Depends upon Student.
2. What is the significance of OOPS? Give examples from real life.
Explanation: The main purpose of C++ programming is to add object orientation to the C programming
language and classes are the central feature of C++ that supports object-oriented programming and are
often called user-defined types.
A class is used to specify the form of an object and it combines data representation and methods for
manipulating that data into one neat package. The data and functions within a class are called members
of the class.
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents
individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Color,
Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e., object
functions like Start, Move, Stop form the Methods of Car Class. No memory is allocated when a class is
created. Memory is allocated only when an object is created, i.e., when an instance of a class is created.
3. Pillars of OOPS.
Explanation: Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects. It simplifies the software development and maintenance by
providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike
etc. It can be physical and logical.
Class
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convince the
customer differently, to draw something e.g. shape or rectangle etc.
In C++, we use Function overloading and Function overriding to achieve polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't
know the internal processing.
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example:
capsule, it is wrapped with different medicines.
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
There are mainly three reasons to use interface. They are given below.
5. Encapsulation
Explanation: Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example
capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.
If one task is performed by different ways, it is known as polymorphism. For example: to convince the
customer differently, to draw something, for example, shape, triangle, rectangle, etc.
Application can be to speak something; Application, a cat speaks meow, dog barks woof, etc.
7. Tell me about 2 projects one was on Android and the other was a Data Analytics Project.
Time-sharing operating systems schedule tasks for efficient use of the system and may also include
accounting software for cost allocation of processor time, mass storage, printing, and other resources.
For hardware functions such as input and output and memory allocation, the operating system acts as an
intermediary between programs and the computer hardware, although the application code is usually
executed directly by the hardware and frequently makes system calls to an OS function or is interrupted by
it. Operating systems are found on many devices that contain a computer – from cellular phones and video
game consoles to web servers and supercomputers.
9. How does a Java program works in accordance with the operating system?
Explanation: Java Program
Java, being a platform independent programming language, doesn’t work on one-step-compilation. Instead,
it involves a two-step execution, first through an OS independent compiler; and second, in a virtual machine
(JVM) which is custom-built for every operating system. The two principle stages are explained below:
Compilation
First, the source ‘.java’ file is passed through the compiler, which then encodes the source code into a
machine independent encoding, known as Bytecode. The content of each class contained in the source file is
stored in a separate ‘.class’ file. While converting the source code into the bytecode, the compiler follows the
following steps:
Parse: Reads a set of *.java source files and maps the resulting token sequence into AST (Abstract Syntax
Tree)-Nodes.
Enter: Enters symbols for the definitions into the symbol table.
Process annotations: If Requested, processes annotations found in the specifed compilation units.
Attribute: Attributes the Syntax trees. This step includes name resolution, type checking and constant
folding.
Flow: Performs dataflow analysis on the trees from the previous step. This includes checks for assignments
and reachability.
Desugar: Rewrites the AST and translates away some syntactic sugar.
Generate: Generates ‘.Class’ files.
Execution
The class files generated by the compiler are independent of the machine or the OS, which allows them to be
run on any system. To run, the main class file (the class that contains the method main) is passed to the JVM,
and then goes through three main stages before the final machine code is executed. These stages are:
Class Loader
The main class is loaded into the memory by passing its ‘.class’ file to the JVM, through invoking the latter.
All the other classes referenced in the program are loaded through the class loader.
A class loader, itself an object, creates a flat name space of class bodies that are referenced by a string
name.Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode verifier,
whose job is to check that the instructions don’t perform damaging actions. The following are some of the
checks carried out:
If any of the above checks fails, the verifier doesn’t allow the class to be loaded.
Just-In-Time Compiler
This is the final stage encountered by the java program, and its job is to convert the loaded bytecode into
machine code. When using a JIT compiler, the hardware can execute the native code, as opposed to having
the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a relatively lengthy
translation process. This can lead to performance gains in the execution speed, unless methods are executed
less frequently.
The process of learning begins with observations or data, such as examples, direct experience, or instruction,
in order to look for patterns in data and make better decisions in the future based on the examples that we
provide. The primary aim is to allow the computers learn automatically without human intervention or
assistance and adjust actions accordingly.
Supervised machine learning algorithms can apply what has been learned in the past to new data using
labeled examples to predict future events. Starting from the analysis of a known training dataset, the learning
algorithm produces an inferred function to make predictions about the output values. The system is able to
provide targets for any new input after sufficient training. The learning algorithm can also compare its output
with the correct, intended output and find errors in order to modify the model accordingly.
In contrast, unsupervised machine learning algorithms are used when the information used to train is neither
classified nor labeled. Unsupervised learning studies how systems can infer a function to describe a hidden
structure from unlabeled data. The system doesn’t figure out the right output, but it explores the data and can
draw inferences from datasets to describe hidden structures from unlabeled data.
Semi-supervised machine learning algorithms fall somewhere in between supervised and unsupervised
learning, since they use both labeled and unlabeled data for training – typically a small amount of labeled
data and a large amount of unlabeled data. The systems that use this method are able to considerably
improve learning accuracy. Usually, semi-supervised learning is chosen when the acquired labeled data
requires skilled and relevant resources in order to train it / learn from it. Otherwise, acquiringunlabeled data
generally doesn’t require additional resources.
Reinforcement machine learning algorithms is a learning method that interacts with its environment by
producing actions and discovers errors or rewards. Trial and error search and delayed reward are the most
relevant characteristics of reinforcement learning. This method allows machines and software agents to
automatically determine the ideal behavior within a specific context in order to maximize its performance.
Simple reward feedback is required for the agent to learn which action is best; this is known as the
reinforcement signal.
Answer B
Explanation: Ethernet is a family of computer networking technologies commonly used in local area networks
(LAN), metropolitan area networks (MAN) and wide area networks (WAN). It was commercially introduced in
1980 and first standardized in 1983 as IEEE 802.3, and has since been refined to support higher bit rates and
longer link distances.
2. 802. 1x is….
A. The theoretical throughput speed of fast Ethernet
B. A networking standard used for authentication
C. The latest Ubuntu release build number
D. The max distance Category 5 Ethernet data can travel before degradation
Answer B
Explanation: IEEE 802.1X is an IEEE Standard for port-based Network Access Control (PNAC). It is part of the
IEEE 802.1 group of networking protocols. It provides an authentication mechanism to devices wishing to attach
to a LAN or WLAN.
Explanation: Task Manager, previously known as Windows Task Manager, is a task manager, system monitor,
and startup manager included with Microsoft Windows systems. It provides information about computer
performance and running software, including name of running processes, CPU load, commit charge, I/O details,
logged-in users, and Windows services. Task Manager can also be used to set process priorities, processor
affinity, start and stop services, and forcibly terminate processes.
Explanation: A local area network (LAN) is a group of computers and associated devices that share a common
communications line or wireless link to a server. Typically, a LAN encompasses computers and peripherals
connected to a server within a distinct geographic area such as an office or a commercial establishment.
Answer D
Explanation: Several address ranges are reserved for "Special Use". These addresses all have restrictions of some
sort placed on their use, and in general should not appear in normal use on the public Internet. The overview
below briefly explains the purpose of these addresses – in general they are used in specialized technical contexts.
They are described in more detail in RFC 6890.
10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255
These address blocks are reserved for use on private networks, and should never appear in the public Internet.
There are millions of private networks (for example home firewalls often use them). People can use these
address blocks without informing us, so we have no record of who uses which of these addresses.
The point of private address space is to allow many organizations in different places to use the same addresses,
and as long as these disconnected or self-contained islands of IP-speaking computers (private networks) are not
connected, there is no problem. If you see an apparent attack, or spam, coming from one of these address ranges,
then either it is coming from your local environment, your ISP, or the address has been "spoofed".
The Private addresses are documented in RFC 1918. If you have further questions about RFC 1918 usage, please
contact your ISP.
"Autoconfiguration" IP Addresses:
169.254.0.0 - 169.254.255.255
Addresses in the range 169.254.0.0 to 169.254.255.255 are used automatically by most network devices when
they are configured to use IP, do not have a static IP Address assigned and are unable to obtain an IP address
using DHCP.
This traffic is intended to be confined to the local network, so the administrator of the local network should look
for misconfigured hosts. Some ISPs inadvertently also permit this traffic, so you may also want to contact your
ISP. This is documented in RFC 6890.
"Loopback" IP addresses:
127.0.0.0 - 127.255.255.255
Each computer on the Internet uses 127.0.0.0/8 to identify itself, to itself. 127.0.0.0 to 127.255.255.255 is
earmarked for what is called "loopback". This construct allows a computer to confirm that it can use IP and for
different programs running on the same machine to communicate with each other using IP. Most software only
uses 127.0.0.1 for loopback purposes (the other addresses in this range are seldom used). All of the addresses
within the loopback address are treated with the same levels of restriction in Internet routing, so it is difficult to
use any other addresses within this block for anything other than node specific applications, generally
bootstraping. This is documented in RFC 6890.
"Unallocated" IP addresses:
The IPv4 Address Registry and the Whois use the word unallocated (sometimes "reserved") to mean that the
addresses are reserved for future allocation. No one should be using these addresses now. These addresses will
be assigned for use in the public Internet in the future. If addresses are needed for private networks then the
private-use addresses mentioned above should be used.
Multicast IP addresses:
224.0.0.0 - 239.255.255.255
Addresses in the range 224.0.0.0 to 239.255.255.255 are set aside for the special purpose of providing multicast
services in the Internet. Multicast services allow a computer to send a single message to many destinations.
Examples include the software that keeps computers’ clocks synchronised and television services delivered over
IP, typically by cable ISPs. Various addresses in this range are used by routers and others are used by hosts that
are listening to multicast sessions.
6. Many versions of linux use this kind of licensing, which means the source code is made freely available and can
be redistributed or modified.
A. open source B. free C. pirated D. public domain
Answer A
Explanation: Open-source software (OSS) is a type of computer software in which source code is released
under a license in which the copyright holder grants users the rights to study, change, and distribute the
software to anyone and for any purpose. Open-source software may be developed in a collaborative public
manner. According to scientists who have studied it, open-source software is a prominent example of open
collaboration. The term is often written without a hyphen as "open source software".
Answer A
Explanation: The Windows Registry is a hierarchical database that stores low-level settings for the
Microsoft Windows operating system and for applications that opt to use the registry. The kernel, device
drivers, services, Security Accounts Manager, and user interface can all use the registry. The registry also
allows access to counters for profiling system performance.
In simple terms, the registry or Windows Registry contains information, settings, options, and other
values for programs and hardware installed on all versions of Microsoft Windows operating systems. For
example, when a program is installed, a new subkey containing settings such as a program's location, its
version, and how to start the program, are all added to the Windows Registry.
8. This command line utility in Windows will display the network address and related information.
A. ipconfig B. show network C. ifconfig D. view-ip
Answer A
Explanation: Displays all current TCP/IP network configuration values and refreshes Dynamic Host
Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without parameters, ipconfig
displays Internet Protocol version 4 (IPv4) and IPv6 addresses, subnet mask, and default gateway for all
adapters.
Answer D
Explanation: Loopback address is a special IP number (127.0.0.1) that is designated for the software loopback
interface of a machine. The loopback interface has no hardware associated with it, and it is not physically
connected to a network.
Explanation: Dynamic Host Configuration Protocol (DHCP) is a client/server protocol that automatically
provides an Internet Protocol (IP) host with its IP address and other related configuration information such as the
subnet mask and default gateway.
11. What Unix-based Mac command line utility can be used to query a machine’s IP address?
A. view-ip B. ifconfig C. ipconfig D. show network
Answer C
Explanation: Displays all current TCP/IP network configuration values and refreshes Dynamic Host
Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without parameters, ipconfig
displays Internet Protocol version 4 (IPv4) and IPv6 addresses, subnet mask, and default gateway for all
adapters.
12. This linux user account is similar to an administrative account on windows and has default access to all files and
commands.
A. admin B. root C. superuser D. default
Answer B
Explanation: Root is the user name or account that by default has access to all commands and files on a Linux or
other Unix-like operating system. It is also referred to as the root account, root user and the superuser.
Answer: B
Explanation: CPU is the abbreviation for central processing unit. Sometimes referred to simply as the central
processor, but more commonly called processor, the CPU is the brains of the computer where most calculations
take place.
14. What protocol is used to transmit web pages over the internet?
A. WWW B. HTTP C. SSH D. FTP
Answer B
Explanation: HTTP is based on the TCP/IP protocols, and is used commonly on the Internet for transmitting
web-pages from servers to browsers.
Answer: A
Explanation: Event Viewer is a component of Microsoft's Windows NT line of operating systems that lets
administrators and users view the event logs on a local or remote machine.
16. What is the name of the Mac command line environment?
A. Terminal B. Command Interface
C. Command Prompt D. Console
Answer: A
Explanation: Terminal provides a command line interface to control the UNIX-based operating system that lurks
below macOS (or Mac OS X).
Answer B
Explanation: A service set identifier (SSID) is a sequence of characters that uniquely names a wireless local area
network (WLAN). An SSID is sometimes referred to as a "network name."
18. Peripherals such as keyboards and mice are connected through this prost.
A. PCI B. HDMI C. Ethernet D. USB
Answer D
Explanation: USB (abbreviation of Universal Serial Bus) is an industry standard that establishes specifications
for cables, connectors and protocols for connection, communication and power supply between personal
computers and their peripheral devices.
19. You can enter Windows Safe Mode by hitting which key(s) during the boot up sequence.
A. Enter B. F8 C. F10 D. Ctrl + Alt + Del
Answer B
Explanation: The F8 key is called a function key. This key is usually used to enter the Windows Startup menu or
the Advanced Boot Options.
20. This software built-in to a motherboard allows you to select the boot up device along with other hardware
configuration options.
A. POST B. BIOS C. RAM D. HDD
Answer B
Explanation: BIOS (basic input/output system) is the program a personal computer's microprocessor uses to get
the computer system started after you turn it on. It also manages data flow between the computer's operating
system and attached devices such as the hard disk, video adapter, keyboard, mouse and printer.
21. The unique hardware id which is used to identify each device on a network is more commonly called….
A. SSID B. NIC C. IP Address D. Mac Address
Answer C
Explanation: An Internet Protocol address (IP address) is a numerical label assigned to each device connected to
a computer network that uses the Internet Protocol for communication. An IP address serves two principal
functions: host or network interface identification and location addressing.
22. When a PC is powered on, it uses this process to test hardware functionality.
A. BIOS B. Boot loader C. Hardware Self-Test D. POST
Answer D
Explanation: POST (Power-On Self-Test) is the diagnostic testing sequence that a computer's basic input/output
system (or "starting program") runs to determine if the computer keyboard, random access memory, disk drives,
and other hardware are working correctly.
If the necessary hardware is detected and found to be operating properly, the computer begins to boot. If the
hardware is not detected or is found not to be operating properly, the BIOS issues an error message which may
be text on the display screen and/or a series of coded beeps, depending on the nature of the problem. Since POST
runs before the computer's video card is activated, it may not be possible to progress to the display screen. The
pattern of beeps may be a variable numbers of short beeps or a mixture of long and short beeps, depending on
what type of BIOS is installed.
Answer B
Explanation: Random-access memory (RAM) is a form of computer data storage that stores data and machine
code currently being used. A random-access memory device allows data items to be read or written in almost the
same amount of time irrespective of the physical location of data inside the memory.
24. This is considered the central module of the Linux operating system that connects hardware to software.
A. run level B.kernel C. root D. CPU
Answer B
Explanation: A kernel is the central part of an operating system. It manages the operations of the computer and
the hardware - most notably memory and CPU time. There are two types of kernels: A micro kernel, which only
contains basic functionality; A monolithic kernel, which contains many device drivers.
25. This file format is a mountable disk image commonly used to install applications in OSX.
A. plist B. dmg C. exe D. dll
Answer B
Explanation: A DMG file is a mountable disk image created in Mac OS X. It contains raw block data typically
compressed and sometimes encrypted. DMG files are commonly used for OS X software installers that are
downloaded from the Internet and mounts a virtual disk on the desktop when opened.
Answer C
Explanation: The first octet of Class C IP address has its first 3 bits set to 110, that is: Class C IP addresses range
from 192.0.0.x to 223.255.255.x. The default subnet mask for Class C is 255.255.255.x. Class C gives 2097152
(221) Network addresses and 254 (28-2) Host addresses.
27. This protocol is connectionless and is commonly used to transmit voice and video data over the internet.
A. FTP B. TCP C. UDP D. APB
Answer C
Explanation: UDP (User Datagram Protocol) is an alternative communications protocol to Transmission Control
Protocol (TCP) used primarily for establishing low-latency and loss-tolerating connections between applications
on the internet.
28. This piece of software, embedded in a chip on the motherboard, allows you to select boot up devices in addition
to other configuration options:
A. BIOS B. RAM C. Configurator D. Ssd
Answer A
Explanation: BIOS (basic input/output system) is the program a personal computer's microprocessor uses to get
the computer system started after you turn it on. It also manages data flow between the computer's operating
system and attached devices such as the hard disk, video adapter, keyboard, mouse and printer.
29. Per second, what is the theoretical maximum speed rating of a Gigabit Ethernet connection?
A. 1000 Gigabits B. 2000 Megabits
C. 1000 Megabits D. 1000 Megabytes
Answer C
Explanation: The Gigabit Ethernet standard supports a theoretical maximum data rate of 1 gigabit per second
(Gbps) (1000 Mbps). When first developed, some thought achieving gigabit speeds with Ethernet would require
using fiber optic or other special network cable technology. However, that's only necessary for long distances.
Answer A
Explanation: In the Control Panel you can quickly access the old Add or Remove Programs by clicking or
tapping the "Uninstall a program" link found in the Programs section.
31. This is a network utility used to test connectivity to another device on the network.
A. nslookup B. nslookup C. ping D. ipconfig
Answer C
Explanation: Ping is a networking utility program or a tool to test if a particular host is reachable. It is a
diagnostic that checks if your computer is connected to a server. Ping, a term taken from the echo location of a
submarine, sends data packet to a server and if it receives a data packet back, then you have a connection.
Answer A
Explanation: WPA2 is a type of encryption used to secure the vast majority of Wi-Fi networks. A WPA2
network provides unique encryption keys for each wireless client that connects to it.
33. This is a security application in Windows that allows you to filter incoming and outgoing network data.
A. Windows Shield B. Windows Anti-Virus
C. Windows Blocker D. Windows Firewall
Answer D
Explanation: The Windows Firewall is a security application created by Microsoft and built into Windows,
designed to filter network data transmissions to and from your Windows system and block harmful
communications and/or the programs that are initiating them.
Answer A
Explanation: Alternatively referred to as a computer console, root console, system console, or terminal. Console
is a basic computer or monitor and keyboard that is connected to another computer, server, or a mainframe over
a network. It is used to maintain or monitor the status of the network or computer.
35. Which one of these is not a result of the command ‘ipconfig /all’
A. DNS Servers B. Default Gateway
C. DHCP Server D. Physical Address
Answer D
Explanation: A physical address is a binarynumber in the form of logical high and low states on an address
busthat corresponds to a particular cell of primary storage(also called main memory), or to a particular register in
a memory-mapped I/O(input/output) device.
Answer C
Explanation: Random-access memory (RAM) is a form of computer data storage that stores data and machine
code currently being used. A random-access memory device allows data items to be read or written in almost the
same amount of time irrespective of the physical location of data inside the memory.
Answer A
Explanation: The Domain Name System (DNS) is the phonebook of the Internet. Humans access information
online through domain names, like nytimes.com or espn.com. Web browsers interact through Internet Protocol
(IP) addresses. DNS translates domain names to IP addresses so browsers can load Internet resources.
Answer B
Explanation: Device Manager is a Control Panel applet in Microsoft Windows operating systems. It allows users
to view and control the hardware attached to the computer. When a piece of hardware is not working, the
offending hardware is highlighted for the user to deal with. The list of hardware can be sorted by various criteria.
Drive Name: Abyeti Technologies
Book Index: 61-(B)
1. An array of input is given with negative as well as positive values. Sort them using Stacks only. You can
use as many of stacks you want but no array. Print the final Output of sorted input.
2. Problem:
1. Print a specific pattern
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<”*”;
}
cout<<”\n”;
}
2. Given 2 numbers (where 6 can also be written as 5, and 5 as 6), calculate the maximum and minimum
possible sum
{
int result = 0;
int multiply = 1;
while (x % 10 > 0)
{
int reminder = x % 10;
else
result = result + reminder * multiply;
multiply *= 10;
x = x / 10;
}
return result;
}
3. Find sum of all values of (a[j]-a[i]) where j>i and j-i is a prime.
int maxIndexDiff(int arr[], int n)
{
int maxDiff = -1;
int i, j;
return maxDiff;
}
int main()
{
int arr[] = {9, 2, 3, 4, 5, 6, 7, 8, 18, 0};
int n = sizeof(arr)/sizeof(arr[0]);
int maxDiff = maxIndexDiff(arr, n);
printf("\n %d", maxDiff);
getchar();
return 0;
}
3. Problem
Knight and Queen Problem it is famous DP problem .
#include<stdio.h>
#define N 8
return true;
}
return false;
}
/* Driver program to test above functions */
int main()
{
solveKT();
return 0;
}
TECHNICAL INTERVIEW
1. 8 ball puzzle
proc weight n {
set num [expr {int(log($n*2-1)/log(3))+1}]
set len [expr {$n/3}]
set pn 0
set pri {2 5 7 11 13 17 19 23 29 31 37 41 43 59 61 67}
for {set i 0} {$i < $num} {incr i} {
set a {}
while {![llength $a]} {
set a {}
set b {}
set c {}
while {
($n+1)%[lindex $pri $pn]==0
||($n-1)%[lindex $pri $pn]==0
||$n%[lindex $pri $pn]==0} {incr pn; puts $pn}
set cpn [lindex $pri $pn]
for {set j 0} {$j < $len} {incr j} {
set tmp [expr {($j*$cpn)%$n}]
lappend a $tmp
incr tmp 1
if {$tmp in $a} {set a {}; break}
lappend b $tmp
}
incr pn
}
for {set j 0} {$j < $n} {incr j} {
if {$j ni $a && $j ni $b} {lappend c $j}
}
puts "[lsort -integer $a] VS [lsort -integer $b] - Which is havier? -1 = left,
0 = equal, 1 = right"
set idx [expr {[gets stdin] + 1}]
if {$i == 0} {
if {$idx == 1} {
set p1 $c
set p2 $c
} elseif {$idx == 0} {
set p1 $a
set p2 $b
} else {
set p1 $b
set p2 $a
}
} else {
set lists [list $a $c $b]
set p1 [lmap it [lindex $lists $idx] {if {$it ni $p1} continue; set it}]
set p2 [lmap it [lindex $lists 2-$idx] {if {$it ni $p2} continue; set it}]
}
}
if {[llength $p1]} {puts "Result $p1"} {puts "Result $p2"}
}
puts "Number of balls?"
weight [gets stdin]
Using a 3L and a 5L bottle, an exact quantity of 4L can be taken out of an unknown water source.
Let us denote 3L bottle the first bottle and 5L bottle the second one. The steps are as follows:
3. A company has employees. An employee can also be a manager. Let A, B, C, D, E, F, G are employees
such that A is manager for B,C,D and B is manager for E,F,G. Design database to store the given
information. Write a query to retrieve the names of employees working under any manager.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// Driver function
public static void main(String[] args)
{
Map<String, String> dataSet = new HashMap<String, String>();
dataSet.put("A", "C");
dataSet.put("B", "C");
dataSet.put("C", "F");
dataSet.put("D", "E");
dataSet.put("E", "F");
dataSet.put("F", "F");
populateResult(dataSet);
System.out.println("result = " + result);
}
directReportList.add(emp);
else
{
List<String> directReportEmpList = mngrEmpMap.get(mngr);
count = directReportEmpList.size();
for (String directReportEmp: directReportEmpList)
count += populateResultUtil(directReportEmp, mngrEmpMap);
result.put(mngr, count);
}
return count;
}
}
4. How so you check if a tree is a BST? What if the definition of this tree is altered a little.
As the name suggests, the data element stores any kind of data in the node.
The left and right pointers point to binary trees on the left and right side of the node respectively.
Commonly-used terminologies
Creating nodes
Simple node
Pointer to a node
In this case, you must explicitly allocate the memory of the node type to the pointer (preferred method).
The idea is to do a post-order traversal and maintain two variables to store the left depth and right depth and
return max of both the depths.
Time complexity
O(n)
Application of trees
6. String manipulation
A string is a sequence of characters. In other words, a string is an array of character data type. An instance of a
string is called a string literal. For instance in C++: string s = "HackerEarth"; s is a string literal.
String Manipulation is a class of problems where a user is asked to process a given string and use/change its
data. An example question would be a great way to understand the problems that are usually classified under
this category.
Given a string S of length N, shift each character of the string by K positions to the right, where K≤N.
Approach:
Implementation:
Every character array in C/C++ ends with a '\0' (NULL) character. It marks the end of the string. If it is not
added in the end, then the code may produce garbage characters after the string.
The idea is to write a recursive function isMirror() that takes two trees as argument and returns true if trees
are mirror and false if trees are not mirror. The isMirror() function recursively checks two roots and
subtrees under the root.
Below is implementation of above algorithm.
// C++ program to check if a given Binary Tree is symmetric or not
#include<bits/stdc++.h>
using namespace std;
// Returns true if trees with roots as root1 and root2 are mirror
bool isMirror(struct Node *root1, struct Node *root2)
{
// If both trees are emptu, then they are mirror images
if (root1 == NULL && root2 == NULL)
return true;
// Driver program
int main()
{
// Let us construct the Tree shown in the above figure
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(4);
root->right->right = newNode(3);
8. Multithreading
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program
for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-
weight processes within a process.
We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of our
new class and call start() method to start the execution of a thread. Start() invokes the run() method
on the Thread object.
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
9. Exception Handling
Exception handling is the process of responding to the occurrence, during computation, of exceptions –
anomalous or exceptional conditions requiring special processing – often changing the normal flow
of program execution. It is provided by specialized programming language constructs, computer
hardware mechanisms like interrupts or operating system IPC facilities like signals.
In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler.
The details of how this is done depends on whether it is a hardware or software exception and how the
software exception is implemented. Some exceptions, especially hardware ones, may be handled so gracefully
that execution can resume where it was interrupted.
Alternative approaches to exception handling in software are error checking, which maintains normal program
flow with later explicit checks for contingencies reported using special return values or some auxiliary global
variable such as C's errno or floating point status flags; or input validation to preemptively filter exceptional
cases.
A different view of exceptions is based on the principles of design by contract and is supported in particular by
the Eiffel language. The idea is to provide a more rigorous basis for exception handling by defining precisely
what is "normal" and "abnormal" behavior. Specifically, the approach is based on two concepts:
Failure: the inability of an operation to fulfill its contract. For example, an addition may produce an
arithmetic overflow (it does not fulfill its contract of computing a good approximation to the mathematical
sum); or a routine may fail to meet its postcondition.
Exception: an abnormal event occurring during the execution of a routine (that routine is the "recipient"
of the exception) during its execution. Such an abnormal event results from the failure of an operation
called by the routine.
The "Safe Exception Handling principle" as introduced by Bertrand Meyer in Object-Oriented Software
Construction then holds that there are only two meaningful ways a routine can react when an exception occurs:
Failure, or "organized panic": The routine fixes the object's state by re-establishing the invariant (this is
the "organized" part), and then fails (panics), triggering an exception in its caller (so that the abnormal
event is not ignored).
Retry: The routine tries the algorithm again, usually after changing some values so that the next
attempt will have a better chance to succeed.
10.Oops concepts
1. Objects
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Overloading
7. Exception Handling
Objects
Objects are the basic unit of OOP. They are instances of class, which have data members and uses various member
functions to perform tasks.
Class
It is similar to structures in C language. Class can also be defined as user defined data type but it also contains
functions in it. So, class is basically a blueprint for object. It declare & defines what data variables the object will
have and what operations can be performed on the class's object.
Abstraction
Abstraction refers to showing only the essential features of the application and hiding the details. In C++, classes can
provide methods to the outside world to access & use the data variables, keeping the variables hidden from direct
access, or classes can even declare everything accessible to everyone, or maybe just to the classes inheriting it. This
can be done using access specifiers.
Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables and functions together in class.
Inheritance
Inheritance is a way to reuse once written code again and again. The class which is inherited is called the Base class
& the class which inherits is called the Derived class. They are also called parent and child class.
So when, a derived class inherits a base class, the derived class can use all the functions which are defined in base
class, hence making code reusable.
Polymorphism
It is a feature, which lets us create functions with same name but different arguments, which will perform different
actions. That means, functions with same name, but functioning in different ways. Or, it also allows us to redefine a
function to provide it with a completely new definition. You will learn how to do this in details soon in coming
lessons.
Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at runtime.
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at
contiguous location; the elements are linked using pointers.
Arrays can be used to store linear data of similar types, but arrays have following limitations.
1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in
advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the
usage.
2) Inserting a new element in an array of elements is expensive, because room has to be created
for the new elements and to create room existing elements have to shifted.
The following is definition of Binary Search Tree(BST) according to Binary Search Tree, is a node-based
binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
There must be no duplicate nodes.
1. What is Bootstrap?
Bootstrap is a free and open-source front-end framework for designing websites and web applications. It
contains HTML- and CSS-based design templates for typography, forms, buttons, navigation and other
interface components, as well as optional JavaScript extensions.
Normalization is the process of reorganizing data in a database so that it meets two basic requirements: (1) There is
no redundancy of data (all data is stored in only one place), and (2) data dependencies are logical (all related data
items are stored together). Normalization is important for many reasons, but chiefly because it allows databases to
take up as little disk space as possible, resulting in increased performance.Normalization is also known as data
normalization.
Write()
writeLine(): create new line automatically
Input Functions:
read()
readLine():Reads the whole linea
5. What are IIS and JSP Servalets in Java?
Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through the use
of servlets, small programs that are specified in the Web page and run on the Web server to modify the Web page
before it is sent to the user who requested it. Sun Microsystems, the developer of Java, also refers to the JSP
technology as the Servlet application program interface (API). JSP is comparable to Microsoft's Active Server Page
(ASP) technology. Whereas a Java Server Page calls a Java program that is executed by the Web server, an Active
Server Page contains a script that is interpreted by a script interpreter (such as VBScript or JScript) before the page is
sent to the user.
IIS, or more specifically its Active Server Page (ASP) environment, contains a core group of classes that
virtually mirror those of the Java Servlet specification. ... You have to adapt (or wrap) the IIS versions of the
objects to make them look and act like servlet versions.
A servlet is a Java programming language class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response programming model. Although servletscan respond to
any type of request, they are commonly used to extend the applications hosted by web servers.
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
An access specifier is a defining code element that can determine which elements of a program are allowed to access
a specific variable or other piece of data. Different programming languages have their own protocols for access
specifiers, as well as defaults for some code elements including both individual variables and classes.they are of 3
types:
9. What is the query of inner Joins ,Outer Join, Constant, Unique Key, Primary key, Inheritance ,Programs
Related to Linked List , In capsulation , Abstraction (there real Life Examples )
INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as the condition
satisfies. This keyword will create the result-set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be same.
Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
ON table1.matching_column = table2.matching_column;
This query will show the names and age of students enrolled in different courses.
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
OUTER JOIN
when performing an inner join, rows from either table that are unmatched in the other table are not returned. In an
outer join, unmatched rows in one or both tables can be returned. There are a few types of outer joins:
LEFT JOIN returns only unmatched rows from the left table.
RIGHT JOIN returns only unmatched rows from the right table.
FULL OUTER JOIN returns unmatched rows from both tables.
UNIQUE KEY
All tables in your databse should have a PK (although this is not enforced by most dbms), and PK can span
multiple columns. Unique key constraints are used to ensure that data is not duplicated in two rows in the
database. One row in the database is allowed to have null for the value of the unique key constraint
PRIMARY KEY
A primary key is a special relational database table column (or combination of columns) designated to
uniquely identify all table records. A primary key'smain features are: It must contain a unique value for each
row of data. It cannot contain null values.
SQLite is an embedded SQL database engine. Unlike most other SQL databases, SQLite does not have a separate
server process. SQLite reads and writes directly to ordinary disk files. A complete SQL database with multiple
tables, indices, triggers, and views, is contained in a single disk file. The database file format is cross-platform - you
can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.
These features make SQLite a popular choice as an Application File Format. SQLite database files are
a recommended storage format by the US Library of Congress. Think of SQLite not as a replacement for Oracle but
as a replacement for fopen()
SQLite is a compact library. With all features enabled, the library size can be less than 600KiB, depending on the
target platform and compiler optimization settings. (64-bit code is larger. And some compiler optimizations such as
aggressive function inlining and loop unrolling can cause the object code to be much larger.) There is a tradeoff
between memory usage and speed. SQLite generally runs faster the more memory you give it. Nevertheless,
performance is usually quite good even in low-memory environments. Depending on how it is used, SQLite can
be faster than direct filesystem I/O.
SQLite is very carefully tested prior to every release and has a reputation for being very reliable. Most of the SQLite
source code is devoted purely to testing and verification. An automated test suite runs millions and millions of test
cases involving hundreds of millions of individual SQL statements and achieves 100% branch test coverage. SQLite
responds gracefully to memory allocation failures and disk I/O errors. Transactions are ACID even if interrupted by
system crashes or power failures. All of this is verified by the automated tests using special test harnesses which
simulate system failures. Of course, even with all this testing, there are still bugs. But unlike some similar projects
(especially commercial competitors) SQLite is open and honest about all bugs and provides bugs lists and minute-
by-minute chronologies of code changes.
The SQLite code base is supported by an international team of developers who work on SQLite full-time. The
developers continue to expand the capabilities of SQLite and enhance its reliability and performance while
maintaining backwards compatibility with the published interface spec, SQL syntax, and database file format. The
source code is absolutely free to anybody who wants it, but professional support is also available.
Student is “TableName”
Name is the “ColumnName representing names of the student’
Rollno is the “ColumnName”
12. What are the real life examples of Stack and Queue?
DML statements are SQL statements that manipulate data. DML stands for Data Manipulation Language. The SQL
statements that are in the DML class are INSERT, UPDATE and DELETE. Some people also lump the SELECT
statement in the DML classification.
Data Definition Languages (DDL) are used to define the database structure. Any CREATE, DROP and ALTER
commands are examples of DDL SQL statements
Sqlite is embeddable relational database management system. SQL is query language. ... Unlike other
databases (like SQL Server and MySQL) SQLite does not support stored procedures. SQLite is file-based,
unlike other databases, like SQL Server and MySQL which are server-based.
Data is stored in databases which in turn stores the data in tables that contains rows and columns. There are
several database applications available to handle the storage and management of data examples include Oracle,
Microsoft SQL and MySQL. ... Adding new record into a database. Deleting records from a database.e.g
Hospital records of patients and doctors.
Null Safety - As already mentioned in above section that Kotlin avoids NullPointerException. Kotlin fails at
compile-time whenever a NullPointerException may be thrown.
Data Classes - In Kotlin there are Data Classes which leads to autogeneration of boilerplate like equals,
hashCode, toString, getters/setters and much more.
Extension Functions - Kotlin allows us to extend the functionality of existing classes without inheriting from
them. Means to say that Kotlin provides the ability to extend a class with new functionality without having to
inherit from the class. This is done by extension functions. To declare an extension function, we need to
prefix its name with a receiver type, i.e. the type being extended.
For the language released in 2003 by McCabe and Clark, see Go! (programming language).
"Google Go" redirects here. For the computer program by Google to play the board game Go, see AlphaGo.
Go (often referred to as Golang[12]) is a programming language designed by Google[13] engineers Robert
Griesemer, Rob Pike, and Ken Thompson.[10] Go is a statically typed, compiled language in the tradition of C, with
the added benefits of memory safety, garbage collection, structural typing,[3] and CSP-style concurrency.
[14]
The compiler, tools, and source code are all free and open source.[15]
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;
Objects:
Objects are the basic run-time entities in an object-oriented programming. They may represents a person, a place, a
bank account, a table of data or any item that the program has to handle. They may also represents user-defined data
such as vector, time and lists. When the program is executed, the object interact by sending message to one another.
Classes:
Objects contain data, and code to manipulate that data. The entire set of data and code of an object can be made a
user-defined data type with the help of class. In fact, objects are variable of the type class. Once a class has been
defined, we can create a number of objects belonging to that class. A class is a collection of objects of similar type.
Data Abstraction:
Abstractions refer to the act of representing essential features without including background details or explanation.
They are commonly known as Abstraction Data Type(ADT).
Encapsulation:
The wrapping up of data and functions into single unit is known as encapsulation. Data encapsulation is a striking
feature of a class. The data is not accessible to the outside world, and only those functions which are wrapped in the
class can access it. These functions provide the interface between the object's data and the program.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of object of another class. The class
whose members are inherited is called the Base class and the class that inherits those members is called Derived
class. It supports class of hierarchical classification.
The concept of inheritance provides the ideas of reusability. This means we can add essential features to an exciting
class without modifying it.
Polymorphism:
Polymorphism is another OOP concept. Polymorphism means the ability to take more than one form. An operation
may exhibit different behaviors at different instances.
22. What is Project Architecture? What kind of Database you have used? Write its Database.
Ans: Ans: Project Architecure means what are the tiers in our project with flow diagram.
supposoe our project contains five tiers like client tier ,presentation tier, Business tier,Integration tier,Data tier. then
we draw the all tiers flow. Project approch is different from project architecure.
Client tier:
IE Browser (default) from which the end user will access the application
The request from the browser will be submitted to the Application Server using HTTP protocol.
The Response from the presentation layer (struts framework) will be interpreted into html pages to view on the
browsers.
Presentation Tier:
Struts Framework with Tiles
On Request from the browser, the appropriate Action Class handles the user request. The Action class then connects
to the business tier via Service Business Delegate.
Tiles have been used to create a set of pages with a consistent user interface (e.g.: the same navigation bar, header,
footer, etc.).
Taglibs are used for displaying tabular data (e.g. search results) in a consistent fashion, with pagination.
Business Tier
The Business Delegate identifies the business service class (the Session EJBs) and delegates client request to the
EJBs. Internally, the session beans are shallow, and delegate all business logic requests to business logic POJOs,
which in turn implement the actual functionality.
The Business Logic POJOs encapsulate the server side business logic. They do not use Hibernate directly, but
instead call upon Data Access Objects (DAO) to work with the model. Parameters and return values are modeled as
Data Transfer Objects (DTO), and hence no Hibernate model classes will ever leave the DAO layer. The business
logic is made available in the business service class, which increases maintainability and easy debugging, if
necessary.
DB Tier
The DAOs encapsulates the database access. For all practical purposes, we are using Hibernate (v 2.1) as the OR
mapping layer. This saves development time to write SQLs for executing insert and update statements, find by
primary key etc. For each value object that directly or compositely represent a table in the database, we have
Hibernate mapping files.
For some complex data retrieval, however we will be using raw SQLs (independent of database) from the DAOs and
populate the Value Object POJOs. In those specific cases, the DAOs will be having direct access to the Databases
using the available connection. The connection properties of the ?DB Manager?, holding the data sources, direct the
request to the appropriate database.
23. What is Cloud Computing? What are its platforms? What are its advantages? What are its
disadvantages? Why it was started? What are its Modules?
Ans: Cloud computing is the the use of various services, such as software development platforms, servers, storage
and software, over the internet, often referred to as the "cloud."
In general, there are three cloud computing characteristics that are common among all cloud-computing vendors:
1. The back-end of the application (especially hardware) is completely managed by a cloud vendor.
2. A user only pays for services used (memory, processing time and bandwidth, etc.).
3. Services are scalable
Many cloud computing advancements are closely related to virtualization. The ability to pay on demand and scale
quickly is largely a result of cloud computing vendors being able to pool resources that may be divided among
multiple clients.
It is common to categorize cloud computing services as infrastructure as a service (IaaS), platform as a service
(PaaS) or software as a service (SaaS).
Cost efficiency – The biggest reason behind shifting to cloud computing is that it takes considerably lesser
cost than an on-premise technology. Now the companies need not store the data in disks anymore as the Cloud
offers enormous space available saving money and resources of the companies.
High Speed – Cloud computing lets you deploy the service quickly in fewer clicks. This quick deployment
lets you get the resources required for your system within fewer minutes.
Excellent accessibility – Storing the information in cloud allows you to access it anywhere, anytime
regardless of the machine making it highly accessible and flexible technology of present times.
Back-up and restore data – Once the data is stored in Cloud, it is easier to get the back-up and recovery of
that, which is quite a time taking process on-premise.
Security issues – At time storing data in cloud may pose serious challenge of information theft in front of
the company. Though advanced security measures are deployed on cloud, still storing a confidential data in cloud
can be a risky affair.
Low bandwidth – At times the bandwidth is low as many users are accessing cloud at the same time which
causes its bandwidth to go down. With less speed the benefits of cloud computing cannot be realized.
Flexibility issues – The cloud services run on remote servers which make it hard for the companies to have
control over software and hardware. The services at times do not run the way it should.
Incompatibility – Since entire infrastructure gets virtualized, incompatibility issues may arise at times that
may pose serious challenges on the way of smooth running of services.
25. If there is a String A, B, C, D, E .Without affecting its elements, how will you reverse it?
Ans: Simple Solution:
1) Create a temporary character array say temp[].
2) Copy alphabetic characters from given array to temp[].
3) Reverse temp[] using standard string reversal algorithm.
4) Now traverse input string and temp in a single loop. Wherever there is alphabetic character is input string,
replace it with current character of temp[].
Efficient Solution:
Time complexity of above solution is O(n), but it requires extra space and it does two traversals of input string.
We can reverse with one traversal and without extra space. Below is algorithm.
Ans: The max() function of PHP is used to find the numerically maximum value in an array or the numerically
maximum value of several specified values. The max() function can take an array or several numbers as an argument
and return the numerically maximum value among the passed parameters. The return type is not fixed, it can be an
integer value or a float value based on input.
Syntax:
max(array_values)
or
max(value1, value2, ...)
Parameters: This function accepts two different types of arguments which are explained below:
1. array_values : It specifies an array containing the values.
2. value1, value2, … : It specifies two or more than two values to be compared.
Return Value: The max() function returns the numerically maximum value.
Ans: Joins help retrieving data from two or more database tables. The tables are mutually related using primary and
foreign keys.
Types of joins
Cross JOIN
Cross JOIN is a simplest form of JOINs which matches each row from one database table to all rows of another.
In other words it gives us combinations of each row of first table with all records in second table.
Suppose we want to get all member records against all the movie records, we can use the script shown below to get
our desired results.
INNER JOIN
The inner JOIN is used to return rows from both tables that satisfy the given condition.
Suppose , you want to get list of members who have rented movies together with titles of movies rented by them.
You can simply use an INNER JOIN for that, which returns rows from both tables that satisfy with given conditions.
SELECT members.`first_name` , members.`last_name` , movies.`title`
FROM members ,movies
WHERE movies.`id` = members.`movie_id`
Outer JOINs
MySQL Outer JOINs return all records matching from both tables .
It can detect records having no match in joined table. It returns NULL values for records of joined table if no match
is found.
LEFT JOIN
Assume now you want to get titles of all movies together with names of members who have rented them. It is clear
that some movies have not being rented by any one. We can simply use LEFT JOIN for the purpose.
The LEFT JOIN returns all the rows from the table on the left even if no matching rows have been found in the table
on the right. Where no matches have been found in the table on the right, NULL is returned.
SELECT A.`title` , B.`first_name` , B.`last_name`
FROM `movies` AS A
LEFT JOIN `members` AS B
ON B.`movie_id` = A.`id`
Executing the above script in MySQL workbench gives.You can see that in the returned result which is listed below
that for movies which are not rented, member name fields are having NULL values. That means no matching
member found members table for that particular movie.
RIGHT JOIN
RIGHT JOIN is obviously the opposite of LEFT JOIN. The RIGHT JOIN returns all the columns from the table on
the right even if no matching rows have been found in the table on the left. Where no matches have been found in the
table on the left, NULL is returned.
In our example, let's assume that you need to get names of members and movies rented by them. Now we have a
new member who has not rented any movie yet
In above JOIN query examples, we have used ON clause to match the records between table.
USING clause can also be used for the same purpose. The difference with USING is it needs to have identical
names for matched columns in both tables.
In "movies" table so far we used its primary key with the name "id". We referred to same in "members" table with
the name "movie_id".
ALTER TABLE `movies` CHANGE `id` `movie_id` INT( 11 ) NOT NULL AUTO_INCREMENT;
Apart from using ON and USING with JOINs you can use many other MySQL clauses like GROUP BY,
WHERE and even functions like SUM, AVG, etc.
Examples of SaaS
Google Apps, Dropbox, Salesforce, Cisco WebEx, Concur, GoToMeeting
Examples of PaaS
AWS Elastic Beanstalk, Windows Azure, Heroku, Force.com, Google App Engine, Apache Stratos, OpenShift
Examples of IaaS
DigitalOcean, Linode, Rackspace, Amazon Web Services (AWS), Cisco Metapod, Microsoft Azure, Google
Compute Engine (GCE)
33. What is Azure (Microsoft)
Ans: Microsoft has leveraged its constantly-expanding worldwide network of data centers to create Azure, a
cloud platform for building, deploying, and managing services and applications, anywhere. Azure lets you add
cloud capabilities to your existing network through its platform as a service (PaaS) model, or entrust Microsoft
with all of your computing and network needs with Infrastructure as a Service (IaaS). Either option provides
secure, reliable access to your cloud hosted data—one built on Microsoft’s proven architecture. Azure provides
an ever expanding array of products and services designed to meet all your needs through one convenient, easy
to manage platform. Below are just some of the capabilities Microsoft offers through Azure and tips for
determining if the Microsoft cloud is the right choice for your organization.
34. What is web view App (in Android)? How will it perform?
Ans: Android system Webview app comes pre-installed into Android OS for rendering an in app browser as a part of
activity layout. This in-app browser is what we term as Webviews.
35. How you can replace a number which is in middle of stack and link list?
Ans: Solution
Following example uses replaceAll() method to replace all the occurance of an element with a different element in a
list.
import java.util.*;
Result
List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six,
hundread, three, Four]
36. In SQL if we have to take out an element from a Table then what is its query?
Ans:
select TheFieldYouWant from YourTable where RowIdYouWant = 1
This will get from the table the row with Id = 1 and then, show you the field you want. You could put more fields, if
you want to show more, or * to show all of them
b. SQL is a query language, not a programming language. You can easily write commands almost same as you write
English.
c. It quickly stores and gets data from the database quickly. SQL is used for the query, insert, collect and manages
data from the database.
d. Almost every database system will need SQL for further processing.
a. It doesn't require coding - SQL easily manages the database system without any requirement of adding
significant code. It does so by using standard SQL.
b. Portability - I think this is the main benefit of SQL. You can run SQL on PCs, laptop, servers, tablets, even on the
smartphone. Also, the database can easily be moved from one device to other.
c. Easy to learn - As I told you, it is the easiest language contains English statements. You can easily learn to write
queries and manipulate data.
d. SQL Standard - DQL databases are used by established standards. The first standard for this by ANSI (American
National Standards Institute) in 1986 and ISO (International Standards Organization) in 1987.
.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs primarily on Microsoft Windows. It
includes a large class library named Framework Class Library (FCL) and provides language interoperability (each language can use
code written in other languages) across several programming languages. Programs written for .NET Framework execute in
a software environment (in contrast to a hardware environment) named Common Language Runtime(CLR), an application virtual
machine that provides services such as security, memory management, and exception handling. (As such, computer code written
using .NET Framework is called "managed code".) FCL and CLR together constitute .NET Framework.
FCL provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms,
and network communications. Programmers produce software by combining their source code with .NET Framework and other
libraries. The framework is intended to be used by most new applications created for the Windows platform. Microsoft also produces
an integrated development environment largely for .NET software called Visual Studio.
.NET Framework began as proprietary software, although the firm worked to standardize the software stack almost immediately, even
before its first release. Despite the standardization efforts, developers, mainly those in the free and open-source softwarecommunities,
expressed their unease with the selected terms and the prospects of any free and open-source implementation, especially
regarding software patents. Since then, Microsoft has changed .NET development to more closely follow a contemporary model of a
community-developed software project, including issuing an update to its patent promising to address the concerns.
.NET Framework led to a family of .NET platforms targeting mobile computing, embedded devices, alternative operating systems,
and web browser plug-ins. A reduced version of the framework, .NET Compact Framework, is available on Windows CE platforms,
including Windows Mobile devices such as smartphones. .NET Micro Framework is targeted at very resource-constrained embedded
devices. Silverlight was available as a web browser plugin. Mono is available for many operating systems and is customized into
popular smartphone operating systems (Android and iOS) and game engines. .NET Core targets the Universal Windows
Platform (UWP), and cross-platform and cloud computing workloads
Ans: Downtime
As cloud service providers take care of a number of clients each day, they can become overwhelmed and may even come up
against technical outages. This can lead to your business processes being temporarily suspended. Additionally, if your internet
connection is offline, you will not be able to access any of your applications, server or data from the cloud.
Security
Although cloud service providers implement the best security standards and industry certifications, storing data and important
files on external service providers always opens up risks. Using cloud-powered technologies means you need to provide your
service provider with access to important business data. Meanwhile, being a public service opens up cloud service providers to
security challenges on a routine basis. The ease in procuring and accessing cloud services can also give nefarious users the
ability to scan, identify and exploit loopholes and vulnerabilities within a system. For instance, in a multi-tenant cloud
architecture where multiple users are hosted on the same server, a hacker might try to break into the data of other users hosted
and stored on the same server. However, such exploits and loopholes are not likely to surface, and the likelihood of a
compromise is not great.
Vendor Lock-In
Although cloud service providers promise that the cloud will be flexible to use and integrate, switching cloud services is
something that hasn’t yet completely evolved. Organizations may find it difficult to migrate their services from one vendor to
another. Hosting and integrating current cloud applications on another platform may throw up interoperability and support
issues. For instance, applications developed on Microsoft Development Framework (.Net) might not work properly on the Linux
platform.
Limited Control
Since the cloud infrastructure is entirely owned, managed and monitored by the service provider, it transfers minimal control
over to the customer. The customer can only control and manage the applications, data and services operated on top of that, not
the backend infrastructure itself. Key administrative tasks such as server shell access, updating and firmware management may
not be passed to the customer or end user.
40. How many Modules were there in Your Project? How you connected it with the database? How you Fetch the
values from the database?
Ans: Based on student Project
Company Name: - Microsoft Placement Drive
Technical
1. Consider the following operation along with Enqueue and Dequeue operations on queues, where k is a global
parameter
MultiDequeue (Q)
{
N=k
While (Q is not empty) and (n > Ө)
{
Dequeue (Q)
n= n-1
}
}
What is the worst- case time complexity of a sequence of ‘m’ MultiDequeue () operations on an initially
empty queue?
A. Ө (mk)
B. Ө (m)
C. Ө (m2)
D. Ө (m+k)
Ans: A
Explanation: Since the queue is empty initially, the condition of while loop never becomes true. So the time
complexity is Ө (mk)
2. Let a priority queue be implemented as a Max- Heap. At first, it has 5 elements. The level-order traversal of
the heap is 10,8,5,3,2. Two new elements 1 and 7 are inserted into the heap in that order. The level-order
traversal of the heap after the insertion of the elements will be:
A. 10,8,7,3,2,1,5
B. 10,8,7,2,3,1,5
C. 10,8,7,5,3,2,1
D. 10,8,7,1,2,3,5
Ans-c
Explanation:
After insertion of 1
10
/ \
8 5
/ \ /
3 2 1
No need to heapify as 5 is greater than 1.
After insertion of 7
10
/ \
8 5
/ \ / \
3 2 1 7
Heapify 5 as 7 is greater than 5
10
/ \
8 7
/ \ / \
3 2 1 5
No need to heapify any further as 10 is
greater than 7
4. Consider an array A[20,10]. Assume 4 words per memory cell and the base address of array A is 100. Find
the address of A[11,5] assuming row-major storage.
A. 420
B. 560
C. 650
D. 770
Ans: B
Explanation.
(0,0)---------(0,9)
-
-
-
-
-
(10,0)-------(10,9)
(11,0),---(11,4),.
7. In Active Directory,__________ is a general purpose container that can be used to group most other
classes together for administrative purposes.
A. Domain
B. Organizational units
C. Forest
D. Tree
Ans: B
9. Which of the following activities does and Active Directory Site help to facilitate?
A. Authentication
B. Replication
C. Service Location
D. All of these
Ans: B
10. A hardware device in each of the nodes of the network, which is used to connect to the network is :
A. Bridge
B. Network Interface Card / Network Adapter
C. Hub
D. Cable
Ans: B
11. __________ in AD DS represent the physical structure, or topology, of your network.
A. Sites
B. Links
C. None of these
D. DNS
Ans: B
13. Active Directory supports multimaster replication of the directory data store between all domain
controllers (DC) in the domain.
A. False
B. True
Ans: A
14. What is the name of the snap – in that can be used to manage trusts in Active Directory?
A. Active Directory Trusts Editor
B. Active Directory Domains and Trusts
C. Active Directory Trusts Management Tool
D. Any of these
Ans: B
16. To backup the Active Directory database, you need to have all the AD services in a stopped state.
A. False
B. True
Ans: A
18. The first domain that is installed in the Active Directory Forest is referred as:
A. Primary Domain
B. Forest Domain
C. Root Domain
D. Key Domain
Ans: A
19. Which of the following AD partitions get replicated to all the domain controllers of a forest?
A. Schema
B. Domain
C. All of these
D. Configuration
Ans: B
20. ___________ describes the characteristics of some aspect of an object in Active Directory. It defines the
types of information that an object can hold.
A. Class
B. Schema
C. Syntaxes
D. Attributes
Ans: A
21. A process P1 has a period of 50 and a CPU burst of 25 and P2has a period of 80, CPU burst of 35 then
which of the following is the total CPU utilization?
A. 0.94
B. 0.49
C. 0.6
D. 0.82
Ans: B
Networking Technical
22. When data is transmitted from device (1) to device (2), the header from (1)’s 5 th layer is read by (2)’s:
A. Physical layer
B. None of the mentioned options
C. Session layer
D. Transport layer
Answer: C
Explanation: At device 1 the header from 5th layer that is session layer is read by the same layer at device 2
that is session layer. Because sender add the header and at the receiver same layer remove the header. So C is
correct answer.
Answer: A
Sol: After three way handshaking, client can send multiple web requests without waiting for response.
24. Which of the following mentioned physical topologies is used in Fiber Distributed Data Interface
(FDDI)?
A. Ring
B. Star
C. Bus
D. Tree
Ans: A
Sol. FDDI (Fiber Distributed Data Interface) is a set of ANSI and ISO standards for data transmission on
fiber optic lines in a local area network (LAN) that can extend in range up to 200 km (124 miles). The FDDI
protocol is based on the token ring protocol. In addition to being large geographically, an FDDI local area
network can support thousands of users. FDDI is frequently used on the backbone for a wide area
network (WAN). An FDDI network contains two token rings, one for possible backup in case the primary
ring fails. The primary ring offers up to 100 Mbps capacity. If the secondary ring is not needed for backup,
it can also carry data, extending capacity to 200 Mbps. The single ring can extend the maximum distance;
a dual ring can extend 100 km (62 miles).
25. Which of the following command is used to copy a file from the client to the server?
A. STOR command.
B. LIST command.
C. None of the mentioned
D. RETR command.
Ans: A
Sol. The STORE (STOR) command is used by the client to tell the server to accept the data
transferred via the data connection and to store the data as a file at the server site.
26. Which of the following conditions should be satisfied by G(x) to detect the odd number of bits in
error?
A. G (x) does not divide 1+xk, for any k not exceeding the frame length
B. G (x) has an odd number of terms.
C. G (x) contains more than two terms
D. 1 + x is a factor of G (x)
Answer: D
Answer: C
Sol: 1. SMTP stands for Simple Mail Transfer Protocol. SMTP is used when email is delivered from an email client, such as
Outlook Express, to an email server or when email is delivered from one email server to another. SMTP is a push protocol and is used to
send the mail whereas POP (post office protocol) are used to retrieve those mails at the receiver’s side.
2. Stands for "Hypertext Transfer Protocol." HTTP is the protocol used to transfer data over the web. It is part of the Internet
protocol suite and defines commands and services used for transmitting webpage data. HTTP uses a server-client model.
28. In Microsoft Windows Operating System, the size of the virtual address space varies for each
hardware platform.
A. Depends
B. TRUE
C. FALSE
D. Question too ambiguous
Ans: B
Sol: It depends on the OS for how much default process space is allocated. In Windows 64-bit, a
default virtual address space for a process is 8 terabytes (there are a total of 2 ^ 24 addressable
terabytes on a 64-bit byte addressable system) and in 32-bit it's only 2 GB (4 GB addressable total).
29. Arrange the order in which the below version of windows were released by Microsoft:
1. Windows 3.0
2. Windows Vista
3. Windows XP
4. Windows NT
5. Windows 2000
A. 53124
B. 14532
C. 34215
D. 12345
Answer: B
Windows 3.0 22 May 1990
Windows NT 3.1 27 July 1993
Windows 2000 17 February 2000
Windows XP 25 October 2001
Windows Vista 30 January 2007
Answer: C
31. What will be the bit rate in Ethemet when Manchester encoding is used?
A. Four time the baud rate
B. Twice the baud rate
C. Half the baud rate
D. Sane as the baud rate
Answer: C
Sol: In Manchester encoding, the bitrate is half of the baud rate.
32. Which of the following is the protocol data unit (PDU) for the application layer in the Internet stack?
A. Frame
B. Message
C. Segment
D. Datagram
Ans: B
Sol: The Layer 1 (Physical Layer) PDU is the bit or, more generally, symbol The Layer 2 (Data Link Layer)
PDU is the frame. The Layer 3 (Network Layer) PDU is the packet. The Layer 4 (Transport Layer) PDU is
the segment for TCP or the datagram for UDP. The Layer 5 (Application Layer) PDU is the data or message.
Drive Name: Microsoft
Book Index: 108-(C)
Technical Interview
1. Tell me about yourself.
Explanation:
Not a technical question
2. What are the subjects that you studied in your 3 years of Engineering?
Explanation:
Answer will vary for each student.
3. Apart from Academics, What special preparations did you do for Microsoft?
Explanation:
Answer will vary for each student.
The act of determining which process is in the ready state, and should be moved to the running state is known
as Process Scheduling.
The prime aim of the process scheduling system is to keep the CPU busy all the time and to deliver minimum
response time for all programs. For achieving this, the scheduler must apply appropriate rules for swapping
processes IN and OUT of CPU.
Scheduling fell into one of the two general categories:
Non Pre-emptive Scheduling: When the currently executing process gives up the CPU voluntarily.
Pre-emptive Scheduling: When the operating system decides to favour another process, pre-empting the
5. What is starvation?
Explanation:
Starvation is the name given to the indefinite postponement of a process because it requires some resource before it
can run, but the resource, though available for allocation, is never allocated to this process. It is sometimes called live
lock, though sometimes that name might be reserved for cases where the waiting process is doing something, but
nothing useful, as in a spin lock. However it happens, starvation is self-evidently a bad thing; more formally, it's bad
because we don't want a non-functional system. If starvation is possible in a system, then a process which enters the
system can be held up for an arbitrary length of time. To avoid starvation, it is often said that we want the system's
resources to be shared "fairly". This is an appealing suggestion, but in practice it isn't much use because it doesn't
define what we mean by "fairly", so it's really more of a description of the problem than a contribution to its solution.
It's more constructive to investigate the paths by which a system can reach a live locked state, and try to control
them.
Deadlock Avoidance
The general idea behind deadlock avoidance is to prevent deadlocks from ever happening, by preventing at
least one of the aforementioned conditions.
This requires more information about each process, AND tends to lead to low device utilization. ( I.e. it is a
conservative approach. )
In some algorithms the scheduler only needs to know the maximum number of each resource that a process
might potentially use. In more complex algorithms the scheduler can also take advantage of the schedule of
exactly what resources may be needed in what order.
When a scheduler sees that starting a process or granting resource requests may lead to future deadlocks,
then that process is just not started or the request is not granted.
A resource allocation state is defined by the number of available and allocated resources, and the maximum
requirements of all processes in the system.
8. Define sub-netting.
Explanation:
Subnetting is the strategy used to partition a single physical network into more than one smaller logical sub-networks
(subnets). An IP address includes a network segment and a host segment. Subnets are designed by accepting bits
from the IP addresses host part and using these bits to assign a number of smaller sub-networks inside the original
network. Subnetting allows an organization to add sub-networks without the need to acquire a new network number
via the Internet service provider (ISP). Subnetting helps to reduce the network traffic and conceals network
complexity. Subnetting is essential when a single network number has to be allocated over numerous segments of a
local area network (LAN).
Subnets were initially designed for solving the shortage of IP addresses over the Internet.
Types of clouds
1. Private Cloud-
Private cloud solutions are dedicated to one business or organizations. Its often have much more specific security
controls than does a public cloud. It may be owned, managed, and operated by the organization, a third party, or
some combination of them, and it may exist on or off premises. Using private cloud storage allows them to control
highly sensitive data by meeting regulations and industry-based criteria, whether that is medical records, trade
secrets, or other classified information.
2. Public Cloud-
Public cloud solutions are readily available from Google, Microsoft, Amazon, and others. The cloud infrastructure is
provisioned for open use by the general public. Gmail and “U” of “I” Box are examples of public cloud services. It
may be owned, managed, and operated by a business, academic, or some combination of them, or government
organization.
3. Hybrid Cloud-
Hybrid cloud is a cloud computing environment that uses a mix of on-premises, private cloud and third-party,
public cloud services with orchestration between the two platforms. Hybrid cloud solutions are a blend of public and
private clouds.
The process of learning begins with observations or data, such as examples, direct experience, or instruction, in order
to look for patterns in data and make better decisions in the future based on the examples that we provide. The
primary aim is to allow the computers learn automatically without human intervention or assistance and adjust
actions accordingly.
11. What is Active Directory?
Explanation:
Active Directory (AD) is a Windows OS directory service that facilitates working with interconnected, complex and
different network resources in a unified manner.
Active Directory was initially released with Windows 2000 Server and revised with additional features in Windows
Server 2008. Active Directory provides a common interface for organizing and maintaining information related to
resources connected to a variety of network directories. The directories may be systems-based (like Windows OS),
application-specific or network resources, like printers. Active Directory serves as a single data store for quick data
access to all users and controls access for users based on the directory's security policy.
In Windows Server 2003, the DHCP Server service provides the following benefits:
Reliable IP address configuration. DHCP minimizes configuration errors caused by manual IP address
configuration, such as typographical errors, or address conflicts caused by the assignment of an IP address to
more than one computer at the same time.
Reduced network administration. DHCP includes the following features to reduce network
administration:
o Centralized and automated TCP/IP configuration.
o The ability to define TCP/IP configurations from a central location.
o The ability to assign a full range of additional TCP/IP configuration values by means of DHCP
options.
o The efficient handling of IP address changes for clients that must be updated frequently, such as
those for portable computers that move to different locations on a wireless network.
o The forwarding of initial DHCP messages by using a DHCP relay agent, thus eliminating the need to
have a DHCP server on every subnet.
Every device on a TCP/IP-based network must have a unique unicast IP address to access the network and its
resources. Without DHCP, IP addresses must be configured manually for new computers or computers that are
moved from one subnet to another, and manually reclaimed for computers that are removed from the network.
DHCP enables this entire process to be automated and managed centrally. The DHCP server maintains a pool of IP
addresses and leases an address to any DHCP-enabled client when it starts up on the network. Because the IP
addresses are dynamic (leased) rather than static (permanently assigned), addresses no longer in use are
automatically returned to the pool for reallocation.
The network administrator establishes DHCP servers that maintain TCP/IP configuration information and provide
address configuration to DHCP-enabled clients in the form of a lease offer. The DHCP server stores the
configuration information in a database, which includes:
13. Types of classes in sub-netting along with their range. Calculate those ranges numerically/how do you get
the range of these classes.
Explanation:
An IP address is the unique numerical address of a device in a computer network that uses Internet Protocol for
communication. The IP addresses allow you to pinpoint a particular device from the billions of devices on the
Internet. To send you a letter, someone needs your mailing address. In the same sense, one computer needs the IP
address of another computer to communicate with it.
An IP address consists of four numbers; each can contain one to three digits. These numbers are separated with a
single dot (.). These four numbers can range from 0 to 255.
1) Class A address
2) Class B address
3) Class C address
4) Class D address
5) Class E address
Class A Address
The first bit of the first octet is always set to zero. So, the first octet ranges from 1 – 127. The class A address only
include IP starting from 1.x.x.x to 126.x.x.x. The IP range 127.x.x.x is reserved for loop back IP addresses. The
default subnet mask for class A IP address is 255.0.0.0. This means it can have 126 networks (2 7-2) and 16777214
hosts (224-2). Class A IP address format is thus: 0NNNNNNN.HHHHHHHH.HHHHHHHH.HHHHHHHH.
Class B Address
Here the first two bits are set to zero. Class B IP Addresses range from 128.0.x.x to 191.255.x.x. The default subnet
mask for Class B is 255.255.x.x. Class B has 16384 (2 14) Network addresses and 65534 (216-2) Host addresses. Class
B IP address format is: 10NNNNNN.NNNNNNNN.HHHHHHHH.HHHHHHHH
Class C Address
The first octet of this class has its first 3 bits set to 110. Class C IP addresses range from 192.0.0.x to 223.255.255.x.
The default subnet mask for Class C is 255.255.255.x. Class C gives 2097152 (2 21) Network addresses and 254 (2 8-2)
Host addresses. Class C IP address format is: 110NNNNN.NNNNNNNN.NNNNNNNN.HHHHHHHH
Class D Address
The first four bits of the first octet in class D IP address are set to 1110. Class D has IP address rage from 224.0.0.0
to 239.255.255.255. Class D is reserved for Multicasting. In multicasting data is not intended for a particular host,
but multiple ones. That is why there is no need to extract host address from the class D IP addresses. The Class D
does not have any subnet mask.
Class E Address
The class E IP addresses are reserved for experimental purpose only for R&D or study. IP addresses in the class E
ranges from 240.0.0.0 to 255.255.255.254. This class too is not equipped with any subnet mask.
TECHNICAL
int main()
{
unsigned int n;
unsigned long long factorial = 1;
Output
Enter a positive integer: 12
Factorial of 12 = 479001600
main()
{
int n, c, first = 0, second = 1, next;
cout << "Enter the number of terms of Fibonacci series you want" << endl;
cin >> n;
cout << "First " << n << " terms of Fibonacci series are :- " << endl;
return 0;
}
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
Output:
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
4. Explain arrays.
Answer:
An array is a collection of data that holds fixed number of values of same type. For example: if you want to store
marks of 100 students, you can create an array for it.
float marks[100];
The size and type of arrays cannot be changed after its declaration.
One-dimensional arrays
Multidimensional arrays (will be discussed in next chapter)
How to declare an array in C?
data_type array_name[array_size];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point values.
Suppose you declared an array mark as above. The first element is mark[0], second element is mark[1] and so on.
C Array declaration
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Example: C Arrays
// Program to find the average of n (n < 10) numbers using arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
STACK:
Stack is an abstract data type with a bounded (predefined) capacity. It is a simple data structure that allows adding
and removing elements in a particular order. Every time an element is added, it goes on the top of the stack and the
only element that can be removed is the element that is at the top of the stack, just like a pile of objects.
Basic features of Stack
Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then
pop letters from the stack.
There are other uses also like:
1. Parsing
2. Expression Conversion(Infix to Postfix, Postfix to Prefix etc)
QUEUES:
Queue is also an abstract data type or a linear data structure, just like stack data structure, in which the first element
is inserted from one end called the REAR(also called tail), and the removal of existing element takes place from the
other end called as FRONT(also called head).
This makes queue as FIFO(First in First Out) data structure, which means that element inserted first will be removed
first.
Which is exactly how queue system works in real world. If you go to a ticket counter to buy movie tickets, and are
first in the queue, then you will be the first one to get the tickets. Right? Same is the case with Queue data structure.
Data inserted first, will leave the queue first.
The process to add an element into queue is called Enqueue and the process of removal of an element from queue is
called Dequeue.
1. Like stack, queue is also an ordered list of elements of similar data types.
2. Queue is a FIFO( First in First Out ) structure.
3. Once a new element is inserted into the Queue, all the elements inserted before the new element in the queue
must be removed, to remove the new element.
4. peek( ) function is oftenly used to return the value of first element without de-queuing it.
Applications of Queue
Queue, as the name suggests is used whenever we need to manage any group of objects in an order in which the first
one coming in, also gets out first while the others wait for their turn, like in the following scenarios:
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life scenario, Call Center phone systems uses Queues to hold people calling them in an order, until a
service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order as they arrive i.e
First come first served.
LINKED LISTS:
They are a dynamic in nature which allocates the memory when required.
Insertion and deletion operations can be easily implemented.
Stacks and queues can be easily executed.
Linked List reduces the access time.
There are four basic types of SQL joins: inner, left, right, and full. The easiest and most intuitive way to explain the
difference between these four types is by using a Venn diagram, which shows all possible logical relations between
data sets.
Let’s say we have two sets of data in our relational database: table A and table B, with some
sort of relation specified by primary and foreign keys. The result of joining these tables
together can be visually represented by the following diagram:
The extent of the overlap, if any, is determined by how many records in Table A match the
records in Table B. Depending on what subset of data we would like to select from the two
tables, the four join types can be visualized by highlighting the corresponding sections of the
Venn diagram:
Examples of SQL Join Types
Let's use the tables we introduced in the “What is a SQL join?” section to show examples of these joins in action.
The relationship between the two tables is specified by the customer_id key, which is the "primary key" in
Note that (1) not every customer in our customers table has placed an order and (2) there
are a few orders for which no customer record exists in our customers table.
Inner Join
Let’s say we wanted to get a list of those customers who placed an order and the details of the order they placed.
This would be a perfect fit for an inner join, since an inner join returns records at the intersection of the two tables.
select first_name, last_name, order_date, order_amount
from customers c
inner join orders o
on c.customer_id = o.customer_id
Note that only George Washington, John Adams and Thomas Jefferson placed orders, with
Thomas Jefferson placing two separate orders on 3/14/1760 and 9/03/1790.
Left Join
If we wanted to simply append information about orders to our customers table, regardless of whether a customer
placed an order or not, we would use a left join. A left join returns all records from table A and any matching records
from table B.
select first_name, last_name, order_date, order_amount
from customers c
left join orders o
on c.customer_id = o.customer_id
Note that since there were no matching records for James Madison and James Monroe in our orders table,
the order_date and order_amount are NULL, which simply means there is no data for these fields.
So why would this be useful? By simply adding a “where order_date is NULL” line to our SQL query, it returns a
list of all customers who have not placed an order:
select first_name, last_name, order_date, order_amount
from customers c
left join orders o
on c.customer_id = o.customer_id
where order_date is NULL
Right Join
Right join is a mirror version of the left join and allows to get a list of all orders, appended with customer
information.
select first_name, last_name, order_date, order_amount
from customers c
right join orders o
on c.customer_id = o.customer_id
Note that since there were no matching customer records for orders placed in 1795 and 1787,
the first_name and last_name fields are NULL in the resulting set.
Also note that the order in which the tables are joined is important. We are right joining the orders table to the
customers table. If we were to right join the customers table to the orders table, the result would be the same as left
joining the orders table to the customers table.
Why is this useful? Simply adding a “where first_name is NULL” line to our SQL query returns a list of all orders
for which we failed to record information about the customers who placed them:
select first_name, last_name, order_date, order_amount
from customers c
right join orders o
on c.customer_id = o.customer_id
where first_name is NULL
Full Join
Finally, for a list of all records from both tables, we can use a full join.
select first_name, last_name, order_date, order_amount
from customers c
full join orders o
on c.customer_id = o.customer_id
8. What are the various advantages of using Java over any other language?
Answer:
Advantages of Java
Java offers higher cross- functionality and portability as programs written in one platform can run across
desktops, mobiles, embedded systems.
Java is free, simple, object-oriented, distributed, supports multithreading and offers multimedia and
network support.
Java is a mature language, therefore more stable and predictable. The Java Class Library enables cross-
platform development.
Being highly popular at enterprise, embedded and network level, Java has a large active user community
and support available.
Unlike C and C++, Java programs are compiled independent of platform in bytecodelanguage which
allows the same program to run on any machine that has a JVM installed.
Java has powerful development tools like Eclipse SDK and NetBeans which have debugging capability
and offer integrated development environment.
Increasing language diversity, evidenced by compatibility of Java with Scala, Groovy, JRuby, and
Clojure.
Relatively seamless forward compatibility from one version to the next
Encapsulation :
In normal terms Encapsulation is defined as wrapping up of data and information under a single unit. In
Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that
manipulates them.
Consider a real life example of encapsulation, in a company there are different sections like the accounts
section, finance section, sales section etc. The finance section handles all the financial transactions and keep
records of all the data related to finance. Similarly the sales section handles all the sales related activities and
keep records of all the sales. Now there may arise a situation when for some reason an official from finance
section needs all the data about sales in a particular month. In this case, he is not allowed to directly access
the data of sales section. He will first have to contact some other officer in the sales section and then request
him to give the particular data. This is what encapsulation is.
Polymorphism:
The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at a same time can have different characteristic. Like a man at a
same time is a father, a husband, a employee. So a same person possesses have different behaviour in
different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
Compile time Polymorphism
Runtime Polymorphism
Recursion:
The process in which a function calls itself is known as recursion and the corresponding function is called
the recursive function. The popular example to understand the recursion is factorial function.
Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. Don’t worry we wil discuss what
is base condition and why it is important.
In the following diagram. I have shown that how the factorial function is calling itself until the function
reaches to the base condition.
Binary Search Tree is a node-based binary tree data structure which has the following properties:
The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
11. If you don’t know about particular coding, what will you do?
Answer:
Not a Technical Question.
// Disconnect is optional
// autodisconnect will occur in destructor if needed
con.Disconnect();
printf("We are disconnected!\n");
}
catch(SAException & x)
{
// SAConnection::Rollback()
// can also throw an exception
// (if a network error for example),
// we will be ready
try
{
// on error rollback changes
con.Rollback ();
}
catch(SAException &)
{
}
// print error message
printf("%s\n", (const char*)x.ErrText());
}
return 0;
}
2. Explain your project in detail.
Ans:
3. int n=4, n=n>>2, if given is the code, What will be the output
Ans: output will be 1
// Driver code
int main() {
int a = 10, b = 3;
cout << divide(a, b) <<"\n";
a = 43, b = -8;
cout << divide(a, b);
return 0;
}
9. Write a program where the comparison between c++ and python can be drawn.
Ans:C++
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main() {
int a = 10, b = 3;
cout << divide(a, b) <<"\n";
a = 43, b = -8;
cout << divide(a, b);
return 0;
}
Python:
def divide(dividend, divisor):
# Driver code
a = 10
b=3
print(divide(a, b))
a = 43
b = -8
print(divide(a, b))
12. How can we print anything in java other than using SOPL?
Ans:import java.io.*;
if (currindex == n)
{
s.insert(sum);
return;
}
// Driver code
int main()
{
int arr[] = {2, 3, 4, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
printDistSum(arr, n);
return 0;
}
int main()
{
int n, first = 0, second = 1, next, c;
return 0;
}
struct LinkedList
{
Node *head;
LinkedList()
{
head = NULL;
}
ll.reverse();
What is recursion?
Ans: Recursion is a method of solving problems that involves breaking a problem down into smaller and smaller
subproblems until you get to a small enough problem that it can be solved trivially. Usually recursion involves a
function calling itself. While it may not seem like much on the surface, recursion allows us to write elegant solutions
to problems that may otherwise be very difficult to program.
Write a program to find repeated element in array.
Solution:
// C++ program to find the only repeating element in an
// array of size n and elements from range 1 to n-1.
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main()
{
int arr[] = {1, 2, 3, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int index = findRepeatingElement(arr, 0, n-1);
if (index != -1)
cout << arr[index];
return 0;
}
Write program for a tic-tok game.
Solution:
// A C++ Program to play tic-tac-toe
#include<bits/stdc++.h>
using namespace std;
#define COMPUTER 1
#define HUMAN 2
return;
}
printf("\t\t\t 1 | 2 | 3 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 4 | 5 | 6 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 7 | 8 | 9 \n\n");
printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n");
return;
}
// A function to initialise the game
void initialise(char board[][SIDE], int moves[])
{
// Initiate the random number generator so that
// the same configuration doesn't arises
srand(time(NULL));
return;
}
return(false);
}
int moves[SIDE*SIDE];
int moveIndex = 0, x, y;
// Keep playing till the game is over or it is a draw
while (gameOver(board) == false &&
moveIndex != SIDE*SIDE)
{
if (whoseTurn == COMPUTER)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = COMPUTERMOVE;
printf("COMPUTER has put a %c in cell %d\n",
COMPUTERMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = HUMAN;
}
// Driver program
int main()
{
// Let us play the game with COMPUTER starting first
playTicTacToe(COMPUTER);
return (0);
}
TECHNICAL INTERVEIW
Ans: A deadlock is a situation in which two computer programs sharing the same resource are effectively preventing
each other from accessing the resource, resulting in both programs ceasing to function.
The earliest computer operating systems ran only one program at a time. All of the resources of the system were
available to this one program. Later, operating systems ran multiple programs at once, interleaving them. Programs
were required to specify in advance what resources they needed so that they could avoid conflicts with other
programs running at the same time. Eventually some operating systems offered dynamic allocation of resources.
Programs could request further allocations of resources after they had begun running. This led to the problem of the
deadlock
3. What is Programming?
Ans: A programming language is a formal language, which comprises a set of instructions used to produce various
kinds of output. Programming languages are used to create programs that implement specific algorithms. Most
programming languages consist of instructions for computers, although there are programmable machines that use a
limited set of specific instructions, rather than the general programming languages of modern computers.
4. What is Recursion?
Ans: The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily.
Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph,
etc.
In recursive program, the solution to base case is provided and solution of bigger problem is expressed in terms of
smaller problems.
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to
smaller one till base case is reached.
Ans: Segmentation is also a memory management scheme. It supports the user’s view of the memory. The
process is divided into the variable size segments and loaded to the logical memory address space.
The logical address space is the collection of variable size segments. Each segment has its name and length. For
the execution, the segments from logical memory space are loaded to the physical memory space.
#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
Output:
Enter value for disp[0][0]:1
Enter value for disp[0][1]:2
Enter value for disp[0][2]:3
Enter value for disp[1][0]:4
Enter value for disp[1][1]:5
Enter value for disp[1][2]:6
Two Dimensional array elements:
123
456
Ans: Let’s say we have two sets of data in our relational database: table A and table B, with some sort of relation
specified by primary and foreign keys. The result of joining these tables together can be visually represented by the
following diagram:
The extent of the overlap, if any, is determined by how many records in Table A match the records in Table B.
Depending on what subset of data we would like to select from the two tables, the four join types can be visualized
by highlighting the corresponding sections of the Venn diagram:
Ans: Scope of variable is one of the important concept of Oops programming. Scope of variable can be defined
as lifetime of that variable. There are two type of scopes of a variable -
1.global
2.local
A variable is said to have global scope if they can be used anywhere but within the same class in which it is declared.
An instance variables are the variables that have global scope. The variable that are declared inside the method are
said to have a local scope .lets consider an example-
class Addition
{
int a=10; // a and b are the instance variables and they have a global scopethey can be used anywhere but within the
class only in which they are declared . When the control move out of the class their scope ends.
int b=20;
void add()
{
int c=a+b; //c is a local variable because it is declared inside the method. When scope go out of the method its scope
ends.
System.out.println("c");
}
public static void main( String[] args)
{
Addition ad=new Addition();
}
}
17. What is difference between arguments and parameters?
Ans: The parameters of a function/method describe to you the values that it uses to calculate its result.
The arguments of a are the values assigned to these parameters during a particular call of the function/method.
1. Which of the following sorting methods sorts a given set of items that is already in sorted order or in
reverse sorted order with equal speed?
A. Selection Sort B. Quick Sort C. insertion sort D. Heap sort
Answer A
Explanation: Selection Sort Best case complexity is Ω(n^2) and worst case complexity is also same O(n^2).
Best-case performance О(n2) comparisons, О(n) swaps
Average performance О(n2) comparisons, О(n) swaps
Explanation:
A is wrong. A try statement can exist without catch, but it must have a finally statement.
B is wrong. A try statement executes a block. If a value is thrown and the try statement has one or more
catch clauses that can catch it, then control will be transferred to the first such catch clause. If that catch
block completes normally, then the try statement completes normally.
C is wrong. Exceptions of type Error and RuntimeException do not have to be caught, only checked
exceptions (java.lang.Exception) have to be caught. However, speaking of Exceptions, Exceptions do not
have to be handled in the same method as the throw statement. They can be passed to another method.
If you put a finally block after a try and its associated catch blocks, then once execution enters the try block,
the code in that finally block will definitely be executed except in the following circumstances:
3. Which of the following is the measurement of degree to which a component, system or process meets
specified requirements and/or user/customer needs and expectations.
A. Software Product B. Software Process C. Software Quality D. Quantity
Answer: c
Explanation:
quality: The degree to which a component, system or process meets specified requirements and/or
user/customer needs and expectations.
software quality: The totality of functionality and features of a software product that bear on its ability to satisfy
stated or implied needs.
4. Which of the following model remains operative until the software is retired?
A. Water fall B. Spiral C. Incremental D. All of the above
Answer: C
Explanation: The spiral model is based on continuous refinement of key products for requirements definition and
analysis, system and software design, and implementation (the code). At each iteration around the cycle, the
products are extensions of an earlier product. This model uses many of the same phases as the waterfall model,
in essentially the same order, separated by planning, risk assessment, and the building of prototypes and
simulations
5. Which of the following sorting algorithm has the worst time complexity of nlog(n)?
A. Heap sort B. Selection Sort C. Quick Sort D. Insertion sort
Answer:A
Explanation:Heapsort has O(n) time when all elements are the same. Heapify takes O(n) time and then removing
elements from the heap is O(1) time for each of the n elements. The run time grows to O(nlog(n)) if all elements
must be distinct.
7. Consider the following scenario: A company decides that it only wants to use the most popular names
for its products. You have to give the number of employees against each unique first name. Which of the
following four core interfaces is best-suited for implementing the above scenario?
A. Map B. Set C. Queue D. List
Answer:A
Explanation: A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can
map to at most one value.
The <html> tag is the container for all other HTML elements (except for the <!DOCTYPE> tag).
Example: !DOCTYPE HTML>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
9. class MethodCall {
public static void main(String args[]) {
int num1 = 10, num2 = 20, result;
result = calc (num1, num2);
System.out.printin(result);
}
// insert code here
}
Which, inserted at line “// insert code here”, produces the output 30?
10. static void calc(n1, n2) {return (n1 + n2); }
11. public int calc(int n1, int n2) {return; }
12. public int calc(int n1, int n2) {return n1 + n2; }
13. static int calc(int n1, int n2) {return n1 + n2; }
Answer: D
Explanation: If we use C option there will be compile time error, because non-static method calc(int,int) cannot be
referenced from a static context.
14. What types of errors are missed by black-box testing and can be found by white-box testing?
15. Performance error
16. Interface error
17. Behavioral error
18. Logic errors
Answer:D
Explanation: BLACK BOX TESTING, also known as Behavioral Testing, is a software testing method in which the
internal structure/design/implementation of the item being tested is not known to the tester. These tests can be
functional or non-functional, though usually functional.
This method is named so because the software program, in the eyes of the tester, is like a black box; inside which
one cannot see.
This method attempts to find errors in the following categories:
Answer:A
Explanation: BLACK BOX TESTING, also known as Behavioral Testing, is a software testing method in which the
internal structure/design/implementation of the item being tested is not known to the tester. These tests can be
functional or non-functional, though usually functional.
This method is named so because the software program, in the eyes of the tester, is like a black box; inside which
one cannot see.
This method attempts to find errors in the following categories:
21. SQL statement SELECT SUBSTR(‘123456789’, INSTR(‘abcabcabc’, ‘b’0, 4) FROM DUAL will result?
A. 2345 B. 6789 C. 456789 D. 1234
Answer:A
Explanation: INSTR Function:- The INSTR function in SQL is used to find the starting location of a pattern in a
string. The syntax for the INSTR function is as follows:
INSTR (str, pattern): Find the starting location of pattern in string str.
SUBSTR Function:- The Substring function in SQL is used to grab a portion of the stored data. The syntax for
the SUBSTR function is as follows:
SUBSTR(str,pos,len): Starting with the position pos in string str select the characters upto the length len.
Create an empty stack called opstack for keeping operators. Create an empty list for output.
Convert the input infix string to a list by using the string method split.
Scan the token list from left to right.
If the token is an operand, append it to the end of the output list.
If the token is a left parenthesis, push it on the opstack.
If the token is a right parenthesis, pop the opstack until the corresponding left parenthesis is removed. Append each
operator to the end of the output list.
If the token is an operator, *, /, +, or -, push it on the opstack. However, first remove any operators already on the
opstack that have higher or equal precedence and append them to the output list.
When the input expression has been completely processed, check the opstack. Any operators still on the stack can be
removed and appended to the end of the output list.
Answer:A
Explanation: When parenthesized conditions are nested, the innermost condition is evaluated first. Under the default
precedence rules, the condition x AND NOT y OR z is equivalent to (x AND (NOT y)) OR z. It’s wise to use
parentheses, rather than rely on the default evaluation order, to make the evaluation order clear.
Answer:C
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared
protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a
nonrelated class from trying to use it.
26. …………….. defines rules regarding the values allowed in columns and is the standard mechanism for
enforcing database integrity.
A. Constraint B. Column C. Trigger D. Index
Answer:A
Explanation:QL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of
the data in the table. If there is any violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column, and table level
constraints apply to the whole table.
Answer:
If the low level modules and their combined functions are often invoked by other modules, then it is more useful
to test them first so that meaningful effective integration of other modules can be done.
Answer:C
Explanation:
HTML and XHTML are both subsets only of SGML, except that XHTML has additional specifications so that it
also validates as XML. Think of XML as XHTML's influential godfather.
Because of this relationship to SGML across all 3 of these languages, there are a lot of similarities, but they are
all considered different languages. However, much of what defines these languages is their restrictions on
SGML.
HTML restricts SGML by defining a list of tags that are allowed to be used.
XML restricts SGML by not allowing unclosed or empty start and end tags, and forces attributes to be explicit.
XML also has a large number of additional restrictions that are not found in SGML.
XHTML restricts SGML with the tags from HTML (with some exclusions, such as frameset, et al), and with
the tag and entity restrictions from XML.
30. The tag used to create a hypertext relationship between current document and another URL is
A. <A>
B. <LINK>
C. <ISINDEX>
D. None of the above
Answer:B
Explanation:For the most part, <LINK> is used to create an author-defined structure to other HTML
documents on a Web site. The attribute REL, for example, defines the relationship of the HREF URL to the
current document. Conversely, REV defines the relationship between the current document and the HREF'ed
URL
Answer: B
32. A text is made up of the characters a, b, c, d, e each occurring with the probability .12, .4, .15, .08 and .25
respectively. The optimal coding technique will have the average length of
A. 3.01 B. 2.3 C. 2.15 D. 1.78
Answer:C
Explanation: Using Hoffman's algorithm, code for a is 1111; b is 0; c is 110; d is 1110; e is 10. Average code
length is
4 x.12 + 1 x .4 + 3 x.15 + 4 x.08 + 2 x.25 = 2.15
Answer:D
Explanation: Data Definition Language (DDL) is a standard for commands that define the different structures in
a database. DDL statements create, modify, and remove database objects such as tables, indexes, and users.
Common DDL statements are CREATE, ALTER, and DROP.
Technical
Answer: D
Explanation:
Answer: B
Explanation:
36. The language used in application programs to request data from the DBMS is referred to as
A. DDL
B. DML
C. Query Language
D. All of the above
Answer: A
Explanation:
The SQL commands that deals with the manipulation of data present in database belong to DML or Data
Manipulation Language and this includes most of the SQL statements.
Examples of DML:
37. Which keyword is used to call the constructors of the same class?
A. default
B. instance of
C. super
D. this
Answer: D
Explanation:
this ()is used to call one constructor from another; but condition is two constructors (calling and called) should
belong to the same class (not of super of class; for super class super() comes).
38. ___________________ is a type of software testing that intends to determine how a system performs in
terms of responsiveness and stability under a certain load.
A. Regression Testing
B. Smoke Testing
C. Performance Testing
D. None of the above
Answer: C
Explanation:
Software Performance testing is type of testing perform to determine the performance of system to major the
measure, validate or verify quality attributes of the system like responsiveness, Speed, Scalability, Stability under
variety of load conditions. The system is tested under a mixture of load conditions and check the time required
responding by the system under varying workloads.
Answer: C
Explanation:
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
class C: public B
{
... ... ...
};
Here, class B is derived from the base class A and the class C is derived from the derived class B.
Answer: D
Explanation:
<h1> defines the most important heading. <h6> defines the least important heading.
41. As part of the maintenance work, you are entrusted with the work of rearranging the library books in a shelf
in proper order, at the end of each day. The ideal choice will be
A. Selection sort
B. merge sort
C. insertion sort
D. bubble sort
Answer: C
Explanation:
Library sort, or gapped insertion sort is a sorting algorithm that uses an insertion sort, but with gaps in the array to
accelerate subsequent insertions. The name comes from an analogy:
Suppose a librarian were to store his books alphabetically on a long shelf, starting with the As at the left end, and
continuing to the right along the shelf with no spaces between the books until the end of the Zs. If the librarian
acquired a new book that belongs to the B section, once he finds the correct space in the B section, he will have to
move every book over, from the middle of the Bs all the way down to the Zs in order to make room for the new
book. This is an insertion sort. However, if he were to leave a space after every letter, as long as there was still space
after B, he would only have to move a few books to make room for the new one. This is the basic principle of the
Library Sort.
42. An algorithm is made up of 2 modules M1&M2. If order of M1 is f(n) & M2 is g(n) then the order of
algorithm is?
A. f(n) X g(n)
B. max (f(n),g(n))
C. min (f(n),g(n))
D. f(n) + g(n)
Answer: B
Explanation:
Out of f(n) and g(n), the module which contributes most towards the time complexity of the given algorithm will be
the order of given algorithm.
Answer: B
Explanation:
Coupling or dependency is the degree to which each program module relies on each one of the other modules.
Answer: B
Explanation:
45. Which of the following algorithms solves the all-pair shortest path problem?
A. Warshall’s
B. Dijkstra’s algorithm
C. Floyd’s algorithm
D. Prim’s algorithm
Answer: C
Explanation:
Dijkstra's algorithm solves single source shortest path problem. Warshall's algorithm finds transitive closure of a
given graph. Prim's algorithm constructs a minimum cost spanning tree for a given weighted graph.
46. Which of the following algorithm design technique is used in the quick sort algorithm?
A. Backtracking
B. Greedy method
C. Divide and conquer
D. Dynamic programming
Answer: C
Explanation:
Like Merge Sort, Quick Sort is a Divide and Conquer algorithm. It picks an element as
pivot and partitions the given array around the picked pivot.
47. The attribute name could be structured as an attribute consisting of first name, middle initial and last name.
This type of attribute is called
A. Multi valued attribute
B. Composite attribute
C. Simple attribute
D. Derived attribute
Answer: B
Explanation:
Composite attributes can be divided into subparts (that is, other attributes)
48. Which of the following are true about interfaces? Select the correct answers.
A. An interface can extend any number of interfaces.
B. Methods declared in interfaces are implicitly private.
C. The keyword implements indicate that an interface inherits from another.
D. Interfaces can’t have variables declared.
Answer: A
Explanation:
Yes, An interface can extend multiple interfaces. Any interface which extend more than one interface will have
property of all the interfaces it extends.
interface A{
public void test();
public void test1();
}
interface B{
public void test();
public void test2();
}
interface C extends A,B{
public void test3();
}
class D implements C{
@Override
public void test(){
System.out.println("Testing....");
}
@Override
public void test1(){
System.out.println("Testing....1");
}
@Override
public void test2(){
System.out.println("Testing....2");
}
@Override
public void test3(){
System.out.println("Testing....3");
}
}
(AB+)(CD*E-)**F/G
Multiplication will be executed first due to left-right associativity
so, (AB+)(CD*E-)*F* /G
(AB+)(CD*E-)*F*G/
Answer: B
Explanation:
The client–server model is a distributed application structure that partitions tasks or workloads between the
providers of a resource or service, called servers, and service requesters, called clients.
Answer: B
Explanation:
We use big-O notation for asymptotic upper bounds, since it bounds the growth of the running time from above for
large enough input sizes.
53. State True or False: In black box testing; only a small number of possible inputs can be tested and many
program paths will be left untested.
A. TRUE B. FALSE
Answer: A
Explanation:
Black box testing, which is also known as behavioral, opaque-box, closed-box, specification-based or eye-to-eye
testing, is a Software Testing method that analyses the functionality of a software/application without knowing
much about the internal structure/design of the item that is being tested and compares the input value with the
output value.
Answer: C
Explanation:
RENAME, REVOKE and GRANT are DDL (Data Definition Language) commands and UPDATE is
DML(Data Manipulation Language) command.
Answer: A
Explanation:
Code Inspection is the most formal type of review, which is a kind of static testing to avoid the defect multiplication
at a later stage. The main purpose of code inspection is to find defects and it can also spot any process improvement
if any.
56. ………………joins two or more tables based on a specified column value not equaling a specified column
value in another table.
A. NON-EQUI JOIN
B. NATURAL JOIN
C. EQUIJOIN
D. OUTER JOIN
Answer: A
Explanation:
Answer: D
Explanation:
Ordered HTML List
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default. Ordered HTML List - The Type Attribute
The type attribute of the <ol> tag, defines the type of the list item marker:
Type Description
type="I" The list items will be numbered with uppercase roman numbers
type="i" The list items will be numbered with lowercase roman numbers
Answer: A
Explanation:
Integer cannot take value greater than Integer.MAX_VALUE. The statement above will be evaluated as
2147483647+ 10 > Integer.MAX_VALUE. Therefore, it will throw an arithmetic exception.
Part-2
Fname Lname
4. Write a query to find the train name and type description of all trains running between 0600 hours and 1800
hours.
Your output should contain 2 columns in the below mentioned order.
train_name type_description
Anagrams
5.
An anagram is a word, phrase, or name formed by rearranging the letters of another word, phrase, or name.
Write a function to check if two given strings are anagrams or not. Return “yes” if they are anagrams, otherwise
return “no”.
Input Specification:
input 1: the first string
input 2: the second string
Output Specification:
Return “yes” if they are anagrams, otherwise return “no”.
Example 1:
input 1: build
input 2: dubli
Output: yes
Example 2:
input 1: beast
input 2: yeast
Output: no
Explanation:
Below is a solution to check if two strings are k-anagrams of each other or not.
1. Stores occurrence of all characters of both strings in separate count arrays.
2. Count number of different characters in both strings (in this if a strings has 4 a and second has 3 ‘a’ then it
will be also count.
3. If count of different characters is less than or equal to k, then return true else false.
if (count > k)
return false;
}
// Driver code
int main()
{
string str1 = "fodr";
string str2 = "gork";
int k = 2;
if (areKAnagrams(str1, str2, k) == true)
cout << "Yes";
else
cout << "No";
return 0;
}
String within String
6.
Given two strings, ‘X’ and ‘Y’ (1 <= length(X), length(Y) <= 10000), find out if ‘Y’ is contained in ‘X’. Output
“yes”, if ‘Y’ is contained in ‘X’, “no”, if not.
Input
input1: the string ‘X’
input2: the string ‘Y’
Output
Return “yes” or “no” accordingly.
Example
Input: abac, bc
Output: yes
!
Explanation:
The idea is simple; we traverse both strings from one side to other side (say from rightmost character to leftmost). If
we find a matching character, we move ahead in both strings. Otherwise we move ahead only in str2.
// Iterative C++ program to check if a string is subsequence of another string
#include<iostream>
#include<cstring>
using namespace std;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
int m = strlen(X);
int n = strlen(Y);
return 0;
}
Drive Name: PERSISTENT SYSTEM
Book Index: 150
TECHNICAL INTERVIEW
int main()
{
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
return 0;
}
Output
Before swapping.
a = 5, b = 10
After swapping.
a = 10, b = 5
Company Name: - WIPRO
Book Index: 166- (C)
1. What is stream?
Ans: Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects
that supports various methods which can be pipelined to produce the desired result.
The features of Java stream are –
A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate
operations can be pipelined. Terminal operations mark the end of the stream and return the result.
In multiple inheritance, a class can inherit from more than one classes. In simple words, a class can have more than
one parent classes. This type of inheritance is not present in Java.
Suppose we have to make two classes A and B as the parent classes of class C, then we have to define class C as
follows.
C language however doesn’t support string as a data type. We can implement strings as array of characters.
Here size of the array is 12 including a ‘\0’ character automatically added to the end of the string by the compiler.
4. Databases
Ans: Database is a systematic collection of data. Databases support storage and manipulation of data. Databases
make data management easy. Let's discuss few examples.
An online telephone directory would definitely use database to store data pertaining to people, phone numbers,
other contact details, etc.
Your electricity service provider is obviously using a database to manage billing , client related issues, to handle
fault data, etc.
There are 4 major types of DBMS. Let's look into them in detail.
Hierarchical - this type of DBMS employs the "parent-child" relationship of storing data. This type of
DBMS is rarely used nowadays. Its structure is like a tree with nodes representing records and branches
representing fields. The windows registry used in Windows XP is an example of a hierarchical database.
Configuration settings are stored as tree structures with nodes.
Network DBMS - this type of DBMS supports many-to many relations. This usually results in complex
database structures. RDM Server is an example of a database management system that implements the
network model.
Relational DBMS - this type of DBMS defines database relationships in form of tables, also known as
relations. Unlike network DBMS, RDBMS does not support many to many relationships.Relational
DBMS usually have pre-defined data types that they can support. This is the most popular DBMS type in
the market. Examples of relational database management systems include MySQL, Oracle, and
Microsoft SQL Server database.
Object Oriented Relation DBMS - this type supports storage of new data types. The data to be stored is
in form of objects. The objects to be stored in the database have attributes (i.e. gender, ager) and
methods that define what to do with the data. PostgreSQL is an example of an object oriented relational
DBMS.
The try/catch statement is used in many programming languages, including C programming language (C++
and C#), Java, JavaScript and Structured Query Language (SQL).
6. Lambda expression
Ans: Lambda expression is a new feature which is introduced in Java 8. A lambda expression is an anonymous
function. A function that doesn’t have a name and doesn’t belong to any class. The concept of lambda expression
was first introduced in LISP programming language.
Java Lambda Expression Syntax:To create a lambda expression, we specify input parameters (if there are any) on
the left side of the lambda operator ->, and place the expression or block of statements on the right side of lambda
operator. For example, the lambda expression (x, y) -> x + y specifies that lambda expression takes two arguments x
and y and returns the sum of these.
7. HTML tags
Ans: There are tow types of tags:
1. Paired Tags
2. Unpaired Tags
A paired tag consist of two tags, first one is called an opening tag and the second one is called a closing tag. These
tags contains the text in between at which the effect of that tag will be applied.
Example: <b>ABC</b>
Here <b> is the opening tag, </b> is the closing tag and ABC the text in between which will result as ABC on the
browser screen.
More Examples:
<i> </i>
<div> </div>
<ul> </ul>
<h1> </h1> , etc.
An Unpaired tag is a single tag which does not need a companion tag.
These tags can be written like < > or < /> both works as same, it’s your choice which style you choose.
Example:
8. Basics of Java
Ans: Java is a programming language that produces software for multiple platforms. When a programmer
writes a Java application, the compiled code (known as bytecode) runs on most operating systems (OS),
including Windows, Linux and Mac OS. Java derives much of its syntax from the C and C++ programming
languages.
Java was developed in the mid-1990s by James A. Gosling, a former computer scientist with Sun
Microsystems.
Ans: There are many differences between final, finally and finalize. A list of differences between final, finally and
finalize are given below:
No. final finally finalize
Other differences:
C++ is WOCA(write once compile anywhere) whereas java is (WORA/WORE) write once run
anywhere/everywhere.
C++ is platform dependent and java is platform independent. (C++ uses compiler only. C++ is
compiled and run using a compiler which converts source code into machine code so, c++ is platform
dependent. Java uses compiler and interpreter. Java source code is compiled into bytecode at compiltaion
time. The interpreter executes the bytecode at runtime and produces output. Java is interpreted thus it is
platform independent.)
C++ support both call by value and call by reference. Java support call by value only.
You can write pointer program in c++. Java support pointer internally. But you can't write the pointer
program in java.
C++ supports structure and union. (Java does not)
C++ does not have built-in support for threads. Java has built-in thread support.
C++ creates new inheritance tree always. Java uses single inheritance tree always because all classes
are child of object class in java. Object class is the root of inheritance tree in java.
Memory management in c++ is done via constructors, destructors and smart pointers. Java offers
automatic garbage collection.
C++ can allocate arbitrary blocks of memory. Java only allocates memory via object instantiation.
Arbitrary memory blocks may be allocated in Java as an array of bytes
C++ has destructors, while Java has finalizers. Both are invoked before an object's deallocation, but
they differ significantly. A C++ object's destructor must be invoked implicitly (in the case of stack-bound
variables) or explicitly to deallocate an object. The destructor executes synchronously just before the point
in a program at which an object is deallocated. Synchronous, coordinated uninitializing and deallocating
in C++ thus satisfy the RAII idiom. In Java, object deallocation is implicitly handled by the garbage
collector. A Java object's finalizer is invoked asynchronously some time after it has been accessed for the
last time and before it is deallocated. Very few objects need finalizers. A finalizer is needed by only
objects that must guarantee some cleanup of the object state before deallocating, typically releasing
resources external to the JVM.
Java has generics, which main purpose is to provide type-safe containers. C++ has compile-time
templates, which provide more extensive support for generic programming and metaprogramming. Java
has annotations, which allow adding arbitrary custom metadata to classes and metaprogramming via an
annotation processing tool.
C++ provides low-level features which Java lacks. In C++, pointers can be used to manipulate specific
memory locations, a task necessary for writing low-level operating system components. Similarly, many
C++ compilers support an inline assembler. Assembly language codes can be imported to a C program
and vice versa. This makes C language even faster. In Java, such code must reside in external libraries,
and can only be accessed via the Java Native Interface, with a significant overhead for each.
Ans: Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.
Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All
other exceptions have to be handled in the method body, either with a try/catch statement or with a throws
declaration.
Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a
method has been called with illegal arguments. No throws needed.
Example for checked exceptions: IOException that some methods from the java.io package might throw.
Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to
the method caller.
int main()
{
person p1; //p1 is a object
}
Object take up space in memory and have an associated address like a record in pascal or structure or union in C.
When a program is executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data. Objects can interact without having to know details of
each others data or code, it is sufficient to know the type of message accepted and type of response returned by the
objects.
Class: Class is a blueprint of data and functions or methods. Class does not take any space.
Syntax for class:
class class_name
{
private:
//data members and member functions declarations
public:
//data members and member functions declarations
protected:
//data members and member functions declarations
};
Class is a user defined data type like structures and unions in C.
By default class variables are private but in case of structure it is public. in above example person is a class.
Encapsulation and Data abstraction: Wrapping up(combing) of data and functions into a single unit is known as
encapsulation. The data is not accessible to the outside world and only those functions which are wrapping in the
class can access it. This insulation of the data from direct access by the program is called data hiding or information
hiding.
Data abstraction refers to, providing only needed information to the outside world and hiding implementation
details. For example, consider a class Complex with public functions as getReal() and getImag(). We may implement
the class as an array of size 2 or as two variables. The advantage of abstractions is, we can change implementation at
any point, users of Complex class wont’t be affected as out method interface remains same. Had our implementation
be public, we would not have been able to change it.
Inheritance: inheritance is the process by which objects of one class acquire the properties of objects of another
class. It supports the concept of hierarchical classification. Inheritance provides re usability. This means that we can
add additional features to an existing class without modifying it.
Polymorphism: polymorphism means ability to take more than one form. An operation may exhibit different
behaviors in different instances. The behavior depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading.
Operator overloading is the process of making an operator to exhibit different behaviors in different instances is
known as operator overloading.
Function overloading is using a single function name to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Dynamic Binding: In dynamic binding, the code to be executed in response to function call is decided at runtime.
C++ has virtual functions to support this.
Message Passing: Objects communicate with one another by sending and receiving information to each other. A
message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving
object that generates the desired results. Message passing involves specifying the name of the object, the name of the
function and the information to be sent.
13. JDBC
Ans:
Java Database Connectivity (JDBC) is an application programming interface (API) for the programming
language Java, which defines how a client may access a database. It is a Java-based data access technology used for
Java database connectivity. It is part of the Java Standard Edition platform, from Oracle Corporation. It provides
methods to query and update data in a database, and is oriented towards relational databases. A JDBC-to-
ODBC bridge enables connections to any ODBC-accessible data source in the Java virtual machine (JVM) host
environment.
1. Overloading happens at compile-time while Overriding happens at runtime: The binding of overloaded
method call to its definition has happens at compile-time however binding of overridden method call to its
definition happens at runtime.
2. Static methods can be overloaded which means a class can have more than one static method of same name.
Static methods cannot be overridden, even if you declare a same static method in child class it has nothing to do
with the same method of parent class.
3. The most basic difference is that overloading is being done in the same class while for overriding base and
child classes are required. Overriding is all about giving a specific implementation to the inherited method of
parent class.
4. Static binding is being used for overloaded methods and dynamic binding is being used for
overridden/overriding methods.
5. Performance: Overloading gives better performance compared to overriding. The reason is that the binding
of overridden methods is being done at runtime.
6. private and final methods can be overloaded but they cannot be overridden. It means a class can have more
than one private/final methods of same name but a child class cannot override the private/final methods of their
base class.
7. Return type of method does not matter in case of method overloading, it can be same or different. However
in case of method overriding the overriding method can have more specific return type (refer this).
8. Argument list should be different while doing method overloading. Argument list should be same in method
Overriding.
Automata
Direction: 1-2 The current selected programming language is C. we emphasize the submission of a fully
working code over partially correct but efficient code. Once submitted, you cannot review this problem again.
You can use printf() to debug your code. The printf() may not work in case of syntax/runtime error. The version
of GCC being used is 5.2.0.
1. A sequence of parentheses is called balanced if it consists entirely of pairs of opening/closing parentheses
(in that order), which is well nested. For example, sequences "(())()" , "()" and "(()(()))" are balanced,
while "(()" and "(()))(" are not.
Write a function to determine if a given string contains balanced sequence of parentheses. The input to the
function balancedParentheses is a string str. Each character in the string will be "(" or ")". The output is
the count of balanced pairs if the sequence is balanced or -1 otherwise.
For example, if the input sequence is "(()(()))", the expected output is 4.
Solutions:
Algorithm:
1) Declare a character stack S.
2) Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character
is the matching starting bracket then fine and increment the static count else parenthesis are not balanced.
3) After complete traversal, if there is some starting bracket left in stack then “not balanced”
switch (expr[i])
{
case ')':
case '}':
// Store the top element in b
x = s.top();
s.pop();
if (x=='(' || x=='[')
return false;
break;
case ']':
if (areParanthesisBalanced(expr))
cout<< "Balanced"<<count;
else
cout<< "Not Balanced";
return 0;
}
2. Design a way to sort the list of positive integers in the descending order according to frequency of the
elements. The elements with higher frequency come before those with lower frequency. Elements with the
same frequency come in the same order as they appear in the given list.
Input
The input to the function/method consists of two arguments -
arr, a list of positive integers.
size, the number elements in the array.
Output
Return a list of positive integers sorted according to the frequency of elements present in arr.
Example
Input:
size = 19
arr = [1,2,2,3,3,3,4,4,5,5,5,5,6,6,6,7,8,9,10]
Output:
[5,5,5,5,3,3,3,6,6,6,2,2,4,4,1,7,8,9,10]
solution:
Algorithm :
1) Use a sorting algorithm to sort the elements O(nlogn)
2) Scan the sorted array and construct a 2D array of element and count O(n).
3) Sort the 2D array according to count O(nlogn).
Example:
Input 2 5 2 8 5 6 8 8
Sort by count
8, 3
2, 2
5, 2
6, 1
How to maintain order of elements if frequency is same?
The above approach doesn’t make sure order of elements if frequency is same. To handle this, we should use
indexes in step 3, if two counts are same then we should first process(or print) the element with lower index. In
step 1, we should store the indexes instead of elements.
Input 5 22 8 5 6 8 8
voidsortByFrequency(intarr[], int n)
{
structele element[n];
for (inti = 0; i< n; i++)
{
element[i].index = i; /* Fill Indexes */
element[i].count = 0; /* Initialize counts as 0 */
element[i].val = arr[i]; /* Fill values in structure
elements */
}
// Driver program
int main()
{
intarr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8};
int n = sizeof(arr)/sizeof(arr[0]);
sortByFrequency(arr, n);
Ans:
Linux is free and open source operating system whereas Windows is a commercial operating
system whose source code is inaccessible.
Windows is not customizable as against Linux is customizable and a user can modify the code and
can change its the look and feel.
Linux provides high security than windows because Linux is open source.
Windows must boot from the primary partition. In contrast, there is no such constraint in Linux it
can be booted from either primary or logical partition.
The separation of the directories is done using a backslash in windows. On the other hand, in Linux,
these are separated by using forward slash.
In Linux, file names are case sensitive while windows file name are case-insensitive.
Ans:
18. Write all the operations of stack. Now assume you have all these functions, using this, find out the
Maximum and Minimum in the stack.
Ans: An approach is discussed that supports minimum with O(1) extra space. We define a variable minEle that stores
the current minimum element in the stack. Now the interesting part is, how to handle the case when minimum
element is removed. To handle this, we push “2x – minEle” into the stack instead of x so that previous minimum
element can be retrieved using current minEle and its value stored in stack. Below are detailed steps and explanation
of working.
Push(x) : Inserts x at the top of stack.
If stack is empty, insert x into the stack and make minEle equal to x.
If stack is not empty, compare x with minEle. Two cases arise:
If x is greater than or equal to minEle, simply insert x.
If x is less than minEle, insert (2*x – minEle) into the stack and make minEle equal to x. For
example, let previous minEle was 3. Now we want to insert 2. We update minEle as 2 and insert 2*2 – 3 =
1 into the stack.
Pop() : Removes an element from top of stack.
Remove element from top. Let the removed element be y. Two cases arise:
If y is greater than or equal to minEle, the minimum element in the stack is still minEle.
If y is less than minEle, the minimum element now becomes (2*minEle – y), so update (minEle =
2*minEle – y). This is where we retrieve previous minimum from current minimum and its value in stack.
For example, let the element to be removed be 1 and minEle be 2. We remove 1 and update minEle as 2*2
– 1 = 3.
Important Points:
Stack doesn’t hold actual value of an element if it is minimum so far.
Actual minimum element is always stored in minEle
Illustration
Push(x)
Ans: Binary Tree : In a binary tree, each node can have a maximum
of 2 child nodes, and there is no ordering in terms of how the nodes
are organised in the binary tree. Nodes that do not have any child
nodes are called leaf nodes of the binary tree. Eg :
Binary Search Tree : Binary Search Tree is
essentially a binary tree, in terms of how many
child nodes a node in the binary search tree can
possibly have, but there is one important
difference between a binary tree and a binary
search tree : In a binary search tree there is a
relative ordering in how the nodes are organized,
while there is nothing of that sort in a binary tree.
In Binary search tree, all the nodes to the left of a
node have values less the value of the node, and
all the nodes to the right of a node have values
greater than the value of the node.
So, in a binary search tree we can efficiently perform operation which rely on orderly organization of nodes, as
compared to the binary tree. Examples of such operations are : find minimum / maximum value in the tree, find all
values greater / lesser than a particular value from the tree, traverse the tree from the least value to the max value,
etc. Performing such operations on plain binary tree wont be very efficient.
Ans: static block includes code i.e. executed when a class is first loaded. Static block in java is executed before main
method. If we declare a Static block in java class it is executed when class loads. This is initialize with the static
variables. Static blocks is mostly used in JDBC. Static block in java is executed every time when a class loads. This
is also known as Static initialization block. Static block in javainitializes when class load into memory , it means
when JVM read the byte code. Initialization can be anything; it can be variable initialization or anything else which
should be shared by all objects of that class. Static block is a normal block of code enclosed in braces { } and is
preceded by static keyword.
21. Polymorphism (both Static and Dynamic along with real life examples).
Ans: Compile time Polymorphism (or Static polymorphism): Polymorphism that is resolved during compiler
time is known as static polymorphism. Method overloading is an example of compile time polymorphism.
Method Overloading: This allows us to have more than one method having the same name, if the parameters of
methods are different in number, sequence and data types of parameters.
Runtime Polymorphism (or Dynamic polymorphism): It is also known as Dynamic Method Dispatch. Dynamic
polymorphism is a process in which a call to an overridden method is re solved at runtime, thats why it is called runtime
polymorphism.
22. Machine Learning and its types. explain it as if you’re explaining it to a 5 year old child.
Ans: Machine Learning is an branch of Artificial Intelligence. Generally, If We build a model without using
machine learning, It has a certain behavior. Even If you run that system for long term .There will be no change in
its behavior . In Opposite, If you build a model with machine learning , it will show different behavior with time.
As the time passes it will improve its accuracy . Now you must be thinking how it is possible . Actually In
Machine leaning models it does not have rigidity over logic written by developer . Instead of rigidity in
logic ,Model depends on data it has .
For Example in weather prediction , If you build the predictor with any machine learning algorithm . If you used
past 30 year data as training data set . At current you predict the temperature using decision tree implementation .
You will find some predicted value . Now you check your expected outcome with real outcome .Finally ,
calculate your accuracy . Now you add feed back of output to existed data set. If you continue your prediction
over the time, Your data set will increase . Lets see , if you go for prediction after 5 years you must have the data
of 35 years . It must give more accurate response than earlier.
Supervised Learning- In this style of Machine learning , We give some training to machine based on that we
test the accuracy of Machine Learning Algorithm on testing data . Suppose We have made Price prediction
algorithms based on machine learning and we have ten year past data of that Stocks . Now we can use three
years data for training to machine and rest 7 years data can be used to test and analyse the accuracy of our
algorithm.
Unsupervised Learning – In this style of learning We do not target any particular outcome . Machine try to
group different object based on the similar attribute they have based on its learning . For Example If you want
to Enhance the sale of Bread , You can use the pattern of related sold item with bread and put them
together .This will increase the sell of bread . To accomplish this issue you can use unsupervised machine
learning algorithm like K- mean.
Reinforcement Learning – This kind of learning is very different from other two type of machine
learning .Here we don’t train Machine , We write the algorithm in such a way that machine take decision and
improve outcomes until it reaches a accuracy level . Markov Decision Process is best example for Reinforcement
Machine Learning. Reinforcement Learning is used in Decision making process specially .
23. Inheritance.
Ans: Inheritance is a fundamental feature of an Object-Oriented programming. It is the process of creating a new
Class, called the Derived Class, from the existing class, called the Base Class. Inheritance is a very elegant way
to reuse and modify the data and functionality that has already been defined in the Base Class, also you can add
new data and functionality to the Derived Class. Since the Derived Class inherits all properties of the Base Class,
the Derived Class has a larger set of properties than the Base Class. However, the Derived Class may override
some or all the properties of the Base Class.
The Inheritance has many advantages, the most important of them being the reusability of code. Rather than
developing new Objects from scratch, new code can be based on the work of other developers, adding only the new
features that are needed. The reuse of existing classes saves time and effort. When you create a class to derive from
another class, the inherited class implicitly gains all the data and functionality of the base class, except for its
constructors and destructors.
From the above example, Cars and Trucks have certain common properties; all have engine, wheels, horns etc. Thus
they can be grouped under a Class called Vehicles. Apart from sharing these common features, each Derived Class
has its own particular features - Cars use petrol while Trucks use diesel.
1) Single Inheritance: Single inheritance is damn easy to understand. When a class
extends another one class only then we call it a single inheritance. The below flow diagram
shows that class B extends only one class which is A. Here A is a parent class of B and B
would be a child class of A.
Single Inheritance example program in Java
2) Multiple Inheritance: “Multiple Inheritance” refers to the concept of one
class extending (Or inherits) more than one base class. The inheritance we
learnt earlier had the concept of one base class or parent. The problem with
“multiple inheritance” is that the derived class will have to manage the
dependency on two base classes.
5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a
combination of Single and Multiple inheritance. A typical flow
diagram would look like below. A hybrid inheritance can be
achieved in the java in a same way as multiple inheritance can
be!! Using interfaces. yes you heard it right. By
using interfaces you can have multiple as well as hybrid
inheritance in Java.
24. Time Complexity of searching in BST.
Ans: The time complexity for a single search in a balanced binary search tree is O(log(n)). Maybe the
question requires you to do n searches in the binary tree, hence the total complexity is O(nlog(n)).
The worst case complexity for a single search in an unbalanced binary search tree is O(n). And similarly, if you
are doing n searches in the unbalanced tree, the total complexity will turn out to be O(n^2).
Map.Entry interface - This interface gives a map entry (key-value pair). HashMap in Java stores both key and
value object, in bucket, as an object of Node class which implements this nested interface Map.Entry. Read more
about Map.Entry interface here.
hashCode() - HashMap provides put(key, value) for storing and get(key) method for retrieving values from
HashMap. When put() method is used to store (Key, Value) pair, HashMap implementation calls hashcode on
Key object to calculate a hash that is used to find a bucket where Entry object will be stored.
When get() method is used to retrieve value, again key object (passed with the get() method) is used to calculate
a hash which is then used to find a bucket where that particular key is stored.
equals() - equals() method is used to compare objects for equality. In case of HashMap key object is used for
comparison, also using equals() method Map knows how to handle hashing collision (hashing collision means
more than one key having the same hash value, thus assigned to the same bucket). In that case objects are stored
in a linked list, refer figure for more clarity.
Where hashCode() method helps in finding the bucket where that key is stored, equals()method helps in finding
the right key as there may be more than one key-value pair stored in a single bucket.
** Bucket term used here is actually an index of array, that array is called table in HashMap implementation.
Thus table[0] is referred as bucket0, table[1] as bucket1 and so on.
As you can see for each element four things are stored in the following fields-
• hash- For storing Hashcode calculated using the key.
• key- For holding key of the element.
• value- For storing value of the element.
• next- To store reference to the next node when a bucket has more than one element and a linkedlist is formed
with in a bucket to store elements.
Following image shows how Node(key-value pair) objects are stored internally in table array of the HashMap
class.
Create a Table: Before establishing connection, let's first create a table in oracle database. Following is the SQL
query to create a table.
In this example, we are connecting to an Oracle database and getting data from emp table. Here, system and oracle
are the username and password of the Oracle database.
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
The above example will fetch all the records of emp table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
2. set classpath
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
temporary
permanent
Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
Ans: A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-
abstract class) cannot have abstract methods. In this guide we will learn what is a abstract class, why we use it and
what are the rules that we must remember while working with it in Java.
An abstract class can not be instantiated, which means you are not allowed to create an objectof it.
Ans: Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstractmethods. 8, it can have default and static methods also.
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
4) Abstract class can provide the implementation Interface can't provide the implementation of abstract
of interface. class.
5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.
6) An abstract classcan extend another Java class An interface can extend another Java interface only.
and implement multiple Java interfaces.
8) A Javaabstract classcan have class members Members of a Java interface are public by default.
like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).
Ans: Java supports multiple inheritance through interfaces only. A class can implement any number of interfaces but
can extend only one class.
Multiple inheritance is not supported because it leads to deadly diamond problem. However, it can be solved but it
leads to complex system so multiple inheritance has been dropped by Java founders.
30. You are given a Binary Tree. Print the Mirror image of the tree. Write the code.
Ans: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes
interchanged.
Algorithm – Mirror(tree):
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
So the tree...
4
/\
2 5
/\
1 3
is changed to...
4
/\
5 2
/\
3 1
*/
void mirror(struct Node* node)
{
if (node==NULL)
return;
else
{
struct Node* temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
return 0;
}
Output :
Inorder traversal of the constructed tree is
42513
Inorder traversal of the mirror tree is
31524
Ans: Given a linked list, check if the the linked list has loop or not. Below diagram shows a linked list with a loop.
// C++ program to detect loop in a linked list
#include<bits/stdc++.h>
using namespace std;
h = h->next;
}
return false;
}
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 10);
if (detectLoop(head))
cout << "Loop found";
else
cout << "No Loop";
return 0;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the Doubly Linked List */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
getchar();
}
#include <stdio.h>
#include <stdlib.h>
/* Helper function that allocates a new node with the given data and
NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
node->parent = NULL;
return(node);
}
/* Give a binary search tree and a number, inserts a new node with
the given number in the correct place in the tree. Returns the new
root pointer which the caller should then use (the standard trick to
avoid using reference parameters). */
struct node* insert(struct node* node, int data)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(data));
else
{
struct node *temp;
/* 2. Otherwise, recur down the tree */
if (data <= node->data)
{
temp = insert(node->left, data);
node->left = temp;
temp->parent= node;
}
else
{
temp = insert(node->right, data);
node->right = temp;
temp->parent = node;
}
getchar();
return 0;
}
In the above diagram, inorder successor of 8 is 10, inorder successor of 10 is 12 and inorder successor of 14 is 20.
34. Write function to implement convert Integer to string and string to integer.
//using Integer.parseInt
int i = Integer.parseInt("123");
System.out.println("i: " + i);
Integer.parseInt() method will throw NumberFormatException if String provided is not a proper number. Same
technique can be used to convert other data type like float and Double to String in Java. Java API provides static
methods like Float.parseFloat() and Double.parseDouble() to perform data type conversion.
2) Integer.valueOf() method
There is another way of converting String into Integer which was hidden to me for long time mostly because I
was satisfied with Integer.parseInt() method. This is an example of Factory method design pattern in Java and
known as Integer.valueOf(), this is also a static method like main and can be used as utility for string to int
conversion. Let’s see an example of using Integer.valueOf() to convert String into int in java.
How to convert Integer to String in Java: In the previous example of this String to int conversion we have seen
changing String value into int primitive type and this part of Java tutorial we will see opposite i.e. conversion of
Integer Object to String. In my opinion this is simpler than previous one. You can simply concatenate any number
with empty String and it will create a new String. Under the carpet + operator uses
either StringBuffer or StringBuilder to concatenate String in Java. anyway there are couple of more ways to convert
int into String and we will see those here with examples.
Simplicity aside, Using String concatenation for converting int to String is also one of the most poor way of doing it.
I know it's temptation because, it's also the most easiest way to do and that's the main reason of it polluting code.
When you write code like "" + 10 to convert numeric 10 to String, your code is translated into following :
1. And: Synchronization in Java is possible by using Java keywords synchronized and volatile and locks.
2. In Java, we can not have synchronized variable. Using synchronized keyword with a variable is illegal and
will result in compilation error. Instead of using the synchronized variable in Java, you can use the
java volatile variable, which will instruct JVM threads to read the value of volatile variable from main memory
and don’t cache it locally.
3. If a variable is not shared between multiple threads then there is no need to use the volatilekeyword.
Ans: Exception handling is the process of responding to the occurrence, during computation, of exceptions –
anomalous or exceptional conditions requiring special processing – often changing the normal flow
of program execution. It is provided by specialized programming language constructs, computer
hardware mechanisms like interrupts or operating systemIPC facilities like signals.
In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler. The
details of how this is done depends on whether it is a hardware or software exception and how the software exception
is implemented. Some exceptions, especially hardware ones, may be handled so gracefully that execution can resume
where it was interrupted.
Alternative approaches to exception handling in software are error checking, which maintains normal program flow
with later explicit checks for contingencies reported using special return values or some auxiliary global variable
such as C's errno or floating point status flags; or input validation to preemptively filter exceptional cases.
Ans: Java finally block is a block that is used to execute important code such as closing connection, stream etc. Java
finally block is always executed whether exception is handled or not.
Input: Head
1 2 3 4 4 6 Given
Output: Head 1 6 2 5 3 4
Sol:
Algorithm is:
2. Given an array of integers and an integer n. Calculate the number of subsets having the sums n.
Sol:
// A Dynamic Programming solution for subset sum problem
#include<stdio.h>
// Returns true if there is a subset of set[] with sun equal to given sum
boolisSubsetSum(int set[], int n, int sum)
{
// The value of subset[i][j] will be true if there is a
// subset of set[0..j-1] with sum equal to i
bool subset[n+1][sum+1];
return subset[n][sum];
}
3. Given and array of integers and calculate the number of subsets having sum = 0.
Sol:
Above code is used with one condition if sum is zero that we count it.
4. Given an integer, you have to calculate the number of 7 in the digits of that integer.
Sol:
The integer entered by the user is stored in variable n. Then the while loop is iterated until the test expression n != 0
is evaluated to 0 (false).
After first iteration, the value of n will be 345 and the count is incremented to 1.
After second iteration, the value of n will be 34 and the count is incremented to 2.
After third iteration, the value of n will be 3 and the count is incremented to 3.
After fourth iteration, the value of n will be 0 and the count is incremented to 4.
Then the test expression is evaluated to false and the loop terminates.
intcountDigit(long long n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
// Driver code
int main(void)
{
longlong n = 345289467;
printf("Number of digits : %d",
countDigit(n));
return 0;
}
Company Name: - FourKites
Book Index: 170-(D)
There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception.
The sun microsystem says there are three types of exceptions:
Checked Exception
Unchecked Exception
Error
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions
e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-
time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
try
catch
finally
throw
throws
Ques 4. Implement a thread in which you have to print simultaneously even and odd numbers.
Ans:
public class OddEvenPrintMain {
boolean odd;
int count = 1;
int MAX = 20;
while (!odd) {
try {
System.out.println("Odd waiting : " + count);
wait();
System.out.println("Notified odd :" + count);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Odd Thread :" + count);
count++;
odd = false;
notify();
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized (this) {
while (count < MAX) {
System.out.println("Checking even loop");
while (odd) {
try {
System.out.println("Even waiting: " + count);
wait();
System.out.println("Notified even:" + count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even thread :" + count);
count++;
odd = true;
notify();
}
}
}
@Override
public void run() {
oep.printEven();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
oep.printOdd();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
6. Question on data structures Trees, pre,post traversal for tree and what will be the complexity.
Ans:
Pre - Order Traversal ( root - leftChild - rightChild ): In Pre-Order traversal, the root node is visited before left
child and right child nodes. In this traversal, the root node is visited first, then its left child and later its right child.
This pre-order traversal is applicable for every root node of all subtrees in the tree.
In the above example of binary tree, first we visit root node 'A' then visit its left child 'B' which is a root for D and F.
So we visit B's left child 'D' and again D is a root for I and J. So we visit D's left child 'I' which is the left most child.
So next we go for visiting D's right child 'J'. With this we have completed root, left and right parts of node D and
root, left parts of node B. Next visit B's right child 'F'. With this we have completed root and left parts of node A. So
we go for A's right child 'C' which is a root node for G and H. After visiting C, we go for its left child 'G' which is a
root for node K. So next we visit left of G, but it does not have left child so we go for G's right child 'K'. With this we
have completed node C's root and left parts. Next visit C's right child 'H' which is the right most child in the tree. So
we stop the process.
That means here we have visited in the order of A-B-D-I-J-F-C-G-K-H using Pre-Order Traversal.
Post - Order Traversal ( leftChild - rightChild - root ): In Post-Order traversal, the root node is visited after left
child and right child. In this traversal, left child node is visited first, then its right child and then its root node. This is
recursively performed until the right most node is visited.
Java try block is used to enclose the code that might throw an exception. It must be used within the method.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
Java finally example Finally is used to place important code, it will be executed whether exception is handled or
not.
class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}
Java finalize example Finalize is used to perform clean up processing just before object is garbage collected.
class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
9. Schema of your project. What tables you have made in this project.
class Main {
public static void main(String args[]) {
Output:
static block called
Company Name: - MU SIGMA_TECHNICAL Placement Drive
Book Index: 172-(D)
initiateModel();
while(!game_over)
{
checkCornerChosen(); // Unimplemented, but it might be an improvement to change the
reference point for each 3 possible move:
evaluateResult() execute move with best score if no move is available, execute
forbidden move and undo,
recalculateModel()
}
evaluateResult()
{
calculatesBestCurrentModel() calculates distance to chosen model stores result
}
calculateBestCurrentModel()
{
(according to the current highest tile acheived and their distribution)
2. Tell me the number of Red Swift Cars in Chandigarh and who will you calculate it.
Ans: With these kind of questions, the intent is not to necessarily get to the correct answer, but to demonstrate
your thought process on how you approach the problem. For example, one possible approach might be as
follows:
Let’s say the population of Delhi is 10 million
Let’s assume that translates to about 2.5 million families in delhi (Assuming 4 people to a family)
Assuming that every family has on average 1.5 cars (or some reasonable number)
Which means there are 3.75 million cars in Delhi
Now Maruti must have the biggest percentage of cars sold, so lets assume that is 30% of all cars sold, which is
approx 1 million cars
Of this, lets say they are split between Swift, X, Y and Z cars each at 20%
So 200,000 swift cars in delhi
Of this, 50% cars might be red or blue, or 25% would be just red, which leaves us with 50,000 red swift cars in
delhi
This is an example of a top down approach, starting with a large number, and then making reasonable
assumptions (or asking questions of the interviewer) to whittle it down to your final number.
Certain problems are also open to a bottom up answer, where you work it out in the reverse manner, from a small
number, adding up to your final value.
At 4 minutes: 4 minutes hourglass runs out and flip it. 7 minutes hourglass is left with 3 minutes.
At 7 minutes: 4 minutes hourglass is left with 1 minute. 7 minutes hourglass runs out and flip it.
At 8 minutes: 4 minutes hourglass runs out and 7 is filled with 6 minutes and 1 minute in other side. Flip it as the
sand is left with 1 minute.
There is a room with a door (closed) and three light bulbs. Outside the room there are three switches, connected
to the bulbs. You may manipulate the switches as you wish, but once you open the door you can’t change them.
Identify each switch with its bulb.
Turn on switch X for 5 to 10 minutes. Turn it off and turn on switch Y. Open the door and touch the light bulb.
6. Which of the Classification Techniques was the most efficient and why?
7. Fibonacci Program.
Sol:
#include<stdio.h>
int main()
{
inti, n, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i<= n; ++i)
{ printf("%d, ", t1); nextTerm = t1 + t2; t1 = t2; t2 = nextTerm;
}
return 0;
}
8. How will calculate the overall consumption of Surf Excel by middle class families in India?
Sol:
The most important factor in these guesstimates is taking the right assumptions and backing them up with
appropriate logic. It essentially revolves around market sizing of products and can be solved with two
approaches:
1. Top-down
2. Bottom-up
I prefer going with the former one, as it is simpler to reduce a larger number into factions on sequentially
considering the factors which influence it. So, for estimating the amount of surf excel detergent used daily in
India:
Now only 33% (1/3rd) among them are above the poverty line: 1200/3=400
It is unlikely that the rural population of India (mix of tier III places and villages) will occupy a large portion of
the 400 million.
Lets assume they constitute 25%, which leaves us with: 400*75%=300
Say, Surf Excel only has 30% of the market due to cost-effectiveness and better penetration of competitors.
Hence, have 60*30%=18
So, average usage of Surf Excel in India per day is: 10*180,00,000/1000 = 180 tons.
Company Name: - CLICK LABS PVT LTD
Linear Data Structures: The data structure where data items are organized sequentially or linearly where
data elements attached one after another is called linear data structure. Data elements in a liner data
structure are traversed one after the other and only one element can be directly reached while traversing.
All the data items in linear data structure can be traversed in single run.
These kind of data structures are very easy to implement because memory of computer is also organized
in linear fashion.
Examples of linear data structures are Arrays, Stack, Queue and Linked List.
An arrays is a collection of data items having the same data types. A Stack is a LIFO (Last In First Out)
data structure where element that added last will be deleted first. All operations on stack are performed
from on end called TOP. A Queue is a FIFO (First In First Out) data structure where element that added
first will be deleted first. In queue, insertion is performed from one end called REAR and deletion is
performed from another end called FRONT. A Linked list is a collection of nodes, where each node is
made up of a data element and a reference to the next node in the sequence.
Non Linear Data Structures: The data structure where data items are not organized sequentially is called
non linear data structure. In other words, A data elements of the non linear data structure could be
connected to more than one elements to reflect a special relationship among them. All the data elements in
non linear data structure can not be traversed in single run.
A tree is collection of nodes where these nodes are arranged hierarchically and form a parent child
relationships. A Graph is a collection of a finite number of vertices and an edges that connect these
vertices. Edges represent relationships among vertices that stores data elements.
Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and time
complexity can be expressed as following recurrence relation.
T(n) = 2T(n/2) + \Theta(n)
The above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case II
of Master Method and solution of the recurrence is \Theta(nLogn).
Time complexity of Merge Sort is \Theta(nLogn) in all 3 cases (worst, average and best) as merge sort always
divides the array in two halves and take linear time to merge two halves.
Auxiliary Space: O(n)
Ans:
DML(Data Manipulation Language) : The SQL commands that deals with the manipulation of data
present in database belong to DML or Data Manipulation Language and this includes most of the SQL
statements.
Examples of DML:
SELECT – is used to retrieve data from the a database.
INSERT – is used to insert data into a table.
UPDATE – is used to update existing data within a table.
DELETE – is used to delete records from a database table.
Queries:
SELECT * FROM table_name;1
1. Hash function f is defined as f(key) = key mod 7. If linear probing is used to insert the key 37, 38, 72, 48, 98,
11, 56 into a table indexed from 0 to 6. 11 will be stored at the location
A. 3 B. 4 C. 5 D. 6
Answer: C
Explanation:
Hash function = f(key) = key mod 7
insertion order= 37, 38, 72, 48, 98, 11, 56
Insert 37: 37 mod 7 = 2
Insert 38: 38 mod 7 = 3
Insert 72: 72 mod 7 = 2, but already occupied, so after linear probing it would occupy index 4.
Insert 48: 48 mod 7 = 6
Insert 98: 98 mod 7 = 0
Insert 11: 11 mod 7 = 4, but already occupied, after linear probing it would get into index 5.
So, option (C) is correct.
Which one of the following can replace the ???? in the code above to determine if the end of a file has been
reached?
A. f = = EOF
B. feof( f )
C. eof( f )
D. f = = NULL
E. !f
Answer: B
Explanation:
In C/C++, getc() returns EOF when end of file is reached. getc() also returns EOF when it fails. So, only
comparing the value returned by getc() with EOF is not sufficient to check for actual end of file.To solve this
problem, C provides feof() which returns non-zero value only if end of file has reached, otherwise it returns 0.
For example, consider the following C program to print contents of file test.txt on screen. In the program, returned
value of getc() is compared with EOF first, then there is another check using feof(). By putting this check, we
make sure that the program prints “End of file reached” only if end of file is reached. And if getc() returns EOF
due to any other reason, then the program prints “Something went wrong”.
#include <stdio.h>
int main()
{
FILE *fp = fopen("test.txt", "r");
int ch = getc(fp);
while (ch != EOF)
{
/* display contents of file on screen */
putchar(ch);
ch = getc(fp);
}
if (feof(fp))
printf("\n End of file reached.");
else
printf("\n Something went wrong.");
fclose(fp);
getchar();
return 0;
}
Answer: B
Explanation:
Dijkstra's algorithm solves single source shortest path problem. Warshall's algorithm finds transitive closure of a
given graph. Prim's algorithm constructs a minimum cost spanning tree for a given weighted graph.
4. Given the following code, which statement is true about the minimum number of test cases required for full
statement and branch coverage?
Read p
Read q
IF p+q> 100
THEN Print “Large”
ENDIF
IF p > 50
THEN Print “p Large”
ENDIF
Answer: A
Explanation:
To calculate Statement Coverage, find out the shortest
number of paths following
which all the nodes will be covered. Here by traversing
through path 1A-2C-3D-E-4G-5H all
the nodes are covered. So by traveling through only one path
all the nodes 12345 are covered,
so the Statement coverage in this case is 1.
Branch Coverage (BC):
To calculate Branch Coverage, find out the minimum number of
paths which will
ensure covering of all the edges. In this case there is no
single path which will ensure coverage
of all the edges at one go. By following paths
1A-2C-3D-E-4G-5H, maximum numbers of
edges (A, C, D, E, G and H) are covered but edges B and F
are left. To covers these edges we can follow 1A-2B-E-4F. By
the combining the above two paths we can ensure of traveling
through all the paths. Hence Branch Coverage is 2. The aim
is to cover all possible true/false
decisions.
5. Complete the sentence:
#include<iostream>
Using namespace std;
int main()
{
char *ptr = NULL;
{
char ch = ‘a’;
ptr = &ch;
}
// line no. K
return 0;
}
Int the above program, ptr on line no. K is ____________.
A. ‘a’
B. NULL
C. This program produces compile-time error.
D. A dangling pointer
Answer: B
Explanation:
Character ‘ch’ has a local scope which is only visible within the inner block. Outside the inner block the pointer PTR
has NULL value.
Answer:
Core Subject Question
Answer:
Core Subject Question
8. For what values of x and xmin will the following program segment output -5?
{
(if (abs(x) < xmin) x = ((x>0)? xmin : -xmin);
printf (“%d “, x);
}
A. x = -4 xmin = 5
B. x = -4 xmin = -5
C. x = 4 xmin = 5
D. x = 4 xmin = -5
Answer: C
Explanation:
Abs(4) < 5 is true.
x>0 will be evaluate as true for option C, then x will be assigned value of xmin i.e. x=5.
Final output will be 5.
Answer: B
Explanation:
Initialize all Array elements but initialization is much straight forward. All values are assigned sequentially and row-
wise.
Consider the below example program –
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };
Output :
14
52
65
10. The folowing C function takes a singly-linked list of integers as a parameter and rearranges the elemets of the
list. The list is represented as a pointer to a structure. The functionis called with the list containing the integers
1,2,3,4,5,6,7 in the given order. What will be the contents of the list after the function completes execution?
Answer: B
Explanation:
The function rearrange () exchanges data of every node with its next node. It starts exchanging data
from the first node itself.
Answer: A
Explanation:
Yes, it can. However, there can only be one public top-level class per .java file, and public top-level classes must
have the same name as the source file.
The purpose of including multiple classes in one source file is to bundle related support functionality (internal data
structures, support classes, etc) together with the main public class. Note that it is always OK not to do this--the only
effect is on the readability (or not) of your code.
12. EvilBank’s admin Mr. Perkins is sittin near a seashore. He found N sealed containers of brickson the shore.
He is not sure how many bricks each container contains. However, there is a note written pointing the
following information:
The total number of bricks each container contains. However, there is a note written pointing the
following information:
An integer array high[] of size N will be given. For each i in high, container I (0-based index) contains
between 0 and high [1] bricks, inclusive.
You know that Mr. Perkins uses bricks as follows: first he chooses a subset of the containers, then he opens
them and uses all the bricks he found inside. He wants to use at least X bricks. And as he is smart, he will
always choose a subset of containers for which he is sure that they contain at least X bricks.
You are given the N, C and X, and the int [] high, Print the smallest number of containers Mr. Perkins may
choose.
Constraints:
1 ≤ N ≤ 50
1 ≤ high [i] ≤
1 ≤ C ≤ sumOf(high[i])
1≤X≤C
Input Format:
First line contains three space separated integers N, C, X respectively.
Second line contains three space separted integers, i th integer denoting high [i].
Output Format:
Print the smallest number of containers Mr. Perkins may choose.
Sample Input #00:
1 10 10
20
Sample Output #00:
1
Explantation #00: Mr. Perkins uses the subset (20). These are the minimum number of container at least X
bricks.
Sample Input #01:
5 10 7
33333
Sample Output #01:
4
Explantion #01: Mr. Perkins uses the subset (3,3,3,3). These are the minimum number of containers to be
choose such that the subset selected by Mr. Perkins contains at least X bricks.
Sample Input #02:
5 100 63
12 34 23 45 34
Sample Output #02:
3
Explanation #02: Mr. Perkins uses the subset (34,34,45). These are the minimum number of containers to be
choose such that the subset selected by Mr. Perkins contains at least X Bricks.
Answer:
Not an objective type question
13. Novell is working on creating a new mail server. You are writing part of a spam detection system. Your job is
to analyze the subject lines of e-mail messages and return a count of know spam signalling keywords in the
subject lines. Your task is made more difficult by the spammers who try to hide the keywords in several ways.
Here we will consider just one obfuscation technique: duplicating characters. Duplicating characters means
taking an existing character in a word and inserting more copies of that charcter into the same place in the
word. This process can then be repeated on a different character in the word. The spam signalling keyword
“credit” might be modified to “creddiT”, “CreddittT” or “ccrreeeddiitt”, etc., but not “credict”.
For the purposes of this problem we will consider subject lines which contain only letters and spaces. The
“words” in the subject line are delimited by spaces. A word in the subject line is cosidered a “match” if th etire
word is the same as at least one etire keyword, after possibly removing some duplicated characters from the
subject word. A keyword that matches only part of a subject word or a subject word that matches only part of a
keyword does not count. Note that if a keyword contains a double letter, the subject word must also contain (at
least) a double letter in the same position to match (“double letter” means two consecutive letters in the word
that are the same). For this application, all matches ( and the use of the term “same”) are case insensitive.
Given a subject line and a list of keywords, return the count of words in the subject line which “match” words
in the keyword list. If multiple words in the subject line match the same keyword, they are each counted , but a
word in the subject line that matches multiple keywords is only counted once.
Constraints
- subjectLine will contain between 0 and 50 characters, inclusive.
- subjectLine will include only letter (‘a’ to ‘z’ and ‘A’ to ‘Z’) and space (‘ ’) characters.
- keywords will have between 0 and 50 elements, inclusive.
- each element of keywords will contain between 1 and 50 characters, inclusive.
- each element of keywords will consist of onley letters (‘a’ to ‘z’ and ‘A’ to ‘Z’).
- The same letter (ignoring case) never appears more that twice consecutively in any element of keywords.
(ie. “aabbAAbb” is ok, but “aaAbb” is not allowed.)
Example 1
subjectLine = “LooW INTEREST RATES available don’t BE slow”
keywords = {“interest”, “rates”, “loan”, “available”, “LOW”}
Returns:4
“INTEREST” , “RATES” , “available”, and “Loow” match. Note that “slow” does not match, even
though it contains the substring “low” which is a keyword.
Example 2
subjectLine = “Dear Richard Get Rich Quick no risk”
keywords = {“rich”, “risk”, “Quicken”, “wealth”, “SAVE”}
Returns: 2
Don’t match “Richard”
Exmaple 3
subjectLine = “in debbtt againn and aAgain and AGAainIN”
keyWords = {“AGAIN”, “again”, “again”}
Returns:3
Answer:
Not an objective type question
14. HTTP (Hyper Text transfer protocol) has similarities to both ………. and …….
A. FTP:SNMP B. FTP:SMTP C. FTP:MTV D. FTP:URL
Answer : A.
Explanation: HTTP functions like a combination of FTP and SMTP . It is similar to FTP because it transfers files and
uses the services of TCP. However , it is much simpler than FTP because it uses only one TCP connection. HTTP is
like SMTP because the data transferred between the client and the server look like SMTP messages.
15. A problem encountered in multitasking when a process is perpetually denied necessary resources is called
A. Deadlock B. Starvation C. Inversion D. Aging
Answer: B
Explanantion: Starvation is a problem encountered in concurrent computing where a process is perpetually
denied necessary resources to process its work. Starvation may be caused by errors in a scheduling or mutual
exclusion algorithm, but can also be caused by resource leaks, and can be intentionally caused via a denial-of-
service attack such as a fork bomb.
16. In a depth-first traversal of a graph G with N vertices, K edges are marked as tree edges. The number of
connected components in G is
A. K B. K+1 C. N-K-1 D. N-K
Answer: D
Explanation: Tree edges are the edges that are part of DFS tree. If there are x tree edges in a tree, then
x+1 vertices in the tree.
The output of DFS is a forest if the graph is disconnected.
Answer D
Explanantion: Round-robin (RR) is one of the algorithms employed by process and network schedulers in
computing. As the term is generally used, time slices (also known as time quanta) are assigned to each
process in equal portions and in circular order, handling all processes without priority (also known as cyclic
executive). Round-robin scheduling is simple, easy to implement, and starvation-free .
Answer: B
Explanation: Heap allocation is needed for dynamic data structures like tree, linked list, etc. OR
To use dynamic data structures we need to use heap allocation or dynamic allocation of memory.
Answer: A
Explanation: A deadlock is a situation in which two computer programs sharing the same resource are effectively
preventing each other from accessing the resource, resulting in both programs ceasing to function.
Answer: C
Explanantion:An interrupt vector is the memory location of an interrupt handler, which prioritizes interrupts and
saves them in a queue if more than one interrupt is waiting to be handled.
21. The most relevant addressing mode to write position independent code is
A. auto – increment mode
B. direct mode
C. indexed mode
D. relative mode
Answer: D
Explanantion: -relative addressing mode can be used to load a register with a value stored in program memory
a short distance away from the current instruction. It can be seen as a special case of the "base plus offset"
addressing mode, one that selects the program counter (PC) as the "base register".
Answer: B C
Explanation: Both option (A) and (D) are correct. But option (B) is false because “a labeled rooted binary tree
can not be uniquely constructed given using its postorder and preorder traversal results”. It need inorder and
preorder/postorder for uniquely constructed binary tree.
Option (C) is also false, take counter example in given tree :
23. The most relevant addressing mode to write position independent code is
A. Auto – increment mode
B. Direct mode
C. Indexed mode
D. Relative mode
Explanantion:
A) It tells about time.
B) Same as A.
C) It does not remember the lines which are written only.
Suppose you read byte number 5, which also is cache line number 5, if only one byte is in one cache line.
Spatial locality says nearby bytes of accessed data is likely to be accessed next. Now there is NO bytes in
cache line number 5 which can be cached to get the benefit of locality. Had it been more than 1 byte, say 2 or
3, you would have copied that whole cache line and next accessed byte, say number 6 or 7 would have been
in cache, getting the benefit of spatial locality.
Technical
Answer:B
Answer:B
28. What will happen if you try to run the following code?
String str = “Java Learners”;
StringBuffer sb = new StringBuffer();
for(int i=0; i < str. Length(); i++)
sb.aoppend(str.charAt(i));
System.out.print1n(sb);
A. It will not print anything B. It will print “srenraeL avaj”
C. It will print “Java Learners” D. Error
Answer:D
Explanation: sb.append() should be there.
Answer:B(Size of the object will be 1Byte, 1 byte is the smallest memory unit that can be used as a
placeholder, and it cannot give zero size as it will not be possible to create an array of objects .)
};
Int main()
{
Base*b = new Base;
delete b;
return 0;
}
Answer:A
32. What does the following program print out?
main()
{
int array [] [3] = {1, 2, 3, 4, 5, 6};
int (*ptr)[3] = array;
Answer:A
Answer:A
34. The following function itoa written to convert an integer into a string
Void itoa ( int n, char string[] )
{
static int i;
if ( n / 10 )
itoa ( n/10, string) ;
else {
i = 0;
if (n < 0)
string [ i++] = ‘-‘ ;
}
Answer:D
Company Name: - BA CONTINUUM
Book Index: 179-(D)
Computer Programming
Answer: A
Explanation:
In the first iteration, mid will be computed as 40. So, 40 is the element to be searched.
Answer: C
Explanation:
A function's signature includes the function's name and the number, order and type of its formal parameters.
3.
Passage:
function MyBinarySearch(array arr, integer low, integer high, integer item)
{
if ( low > high )
}
return -1
{
Answer: A
Explanation:
4. A language has 28 different letters in total. Each word in the language consists of a maximum of 7 letters. A
programmer wants to create a data type to store a word of this language. She decides to store the word as an
array of letters. How many bits should she assign to the data type to store all kinds of words of the language?
A. 7 B. 35 C. 28 D. 196
Answer: B
Explanation:
1 bit -> 2 possible states
2 bits -> 4 possible states
3 bits -> 8 possible states
4 bits -> 16 possible states
5 bits -> 32 possible states
You need 5 bits to represent all possible letters in the language (28 > 16 & 28 < 32). Since you are told you are
storing an array of letters, you will need a total of 5*7 bits = 35 bits to represent all words in the language.
Answer: A
Explanation:
Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at
the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key’), and explores all of the
neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.
6. A function in the base class is redefined in the inherited class. What is the term used to describe
7. this situation?
A. Inheritance
B. Overriding
C. Overloading
D. Encapsulation
Answer: B
Explanation:
Class a
{
public:
virtual void display(){ cout << "hello"; }
}
Class b:public a
{
public:
void display(){ cout << "bye";};
}
8. The function given below takes an even integer “n” as the input and calculates the sum of first “n” even natural
numbers. The function is called by the statement “sum (30)”. How many times will the function “sum” be called
to compute the sum?
function sum(n)
{
if (n equals 2)
return 2
else
return(n + sum(n-2))
end
}
A. 1 B. 30 C. 15 D. 16
Answer: C
Explanation:
The function sum ( ) will only be called for even numbers between 30 & 1.There are total 15 even numbers between
30 and 1.So sum will be called 15 times.
The function calling hierarchy will be as follows:
Sum (30)
Sum (28)
Sum (26)
Sum (24)
Sum (22)
Sum (20)
.
.
.
Sum (4)
Sum (2)
A. 0
03
B. 0 3
036
C. 0
036
0369
D. 0 3 6
0369
0 3 6 9 12
Answer: A
Explanation:
10. Code A contains a set of eight lines that occur ten times in different points of the program. This code is passed to
a programmer who puts the set of eight lines in a function definition and calls them at the ten points in the
program. Assume this new code to be Code B. Which code will run faster using an interpreter?
A. Code A
B. Code B
C. Both the codes would run at the same speed
D. None of the above
Answer: C
Explanation:
An interpreter translates code like a compiler but reads the code and immediately executes on that code, and
therefore is initially faster than a compiler. Thus, interpreters are often used in software development tools as
debugging tools, as they can execute a single in of code at a time. Compilers translate code all at once and the
processor then executes upon the machine language that the compiler produced. If changes are made to the code after
compilation, the changed code will need to be compiled and added to the compiled code (or perhaps the entire
program will need to be re-compiled.) But an interpreter, although skipping the step of compilation of the entire
program to start, is much slower to execute than the same program that’s been completely compiled. Interpreters,
however, have usefulness in areas where speed doesn’t matter (e.g., debugging and training) and it is possible to take
the entire interpreter and use it on another ISA, which makes it more portable than a compiler when working
between hardware architectures.
11. What is the minimum number of stacks of size “n” required to implement a queue of size “n”?
A. 1 B. 2 C. 3 D. 4
Answer: B
Explanation:
A queue can be implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be
stack1 and stack2. q can be implemented in two ways:
enQueue(q, x)
1) While stack1 is not empty, push everything from satck1 to stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.
dnQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it
enQueue(q, x)
1) Push x to stack1 (assuming size of stacks is unlimited).
deQueue(q)
1) If both stacks are empty then error.
2) If stack2 is empty
While stack1 is not empty, push everything from satck1 to stack2.
3) Pop the element from stack2 and return it.
12. Grace writes a recursive algorithm. But she forgot to add a termination condition and hence entered an infinite
recursion. What will this situation lead to?
A. Overflow of runtime stack
B. Underflow of runtime stack
C. Underflow of usage of registers
D. Overflow of memory I/O
Answer: A
Explanation:
Recursion is a function calling itself, repeatedly. Due to calling itself, it uses STACK memory to store the
intermediate results (intermediate functions), mostly known as activation records. Every time Recursion process will
PUSH one activation record to top of the stack. Here in our algorithm, recursion is calling infinitely. So it will do
many PUSH operations into stack. STACK has limited space to store. So after some recursive calls stack will
completely FULL. When some nth recursive call trying make PUSH operation into stack, it gives "Stack Over Flow"
or "Segmentation fault"-core dumped. Here you are trying to access an address which is not available.
13. A data type is stored as a 6-bit signed integer. Which of the given options cannot be represented by this data
type?
A. -12 B. 0 C. 32 D. 18
Answer: C
Explanation:
For n bits, the range of 2’s complement signed integers that are allowed is -2^ (n-1) to (2^ (n-1))-1.
The range of 6 bit signed integers is -32 to +31 (both numbers included). Hence, 32 cannot be represented by using 6
bits.
Answer: B
Explanation:
It returns the smaller of the two integers passed to it. If both the integers are equal, it returns the equal value.
This is how it works. First, if condition check whether a is greater than b. If a is indeed greater than b, the function
calls itself, this time with the arguments interchanged. Otherwise, (this means a is less than or equal to b), it returns a
(hence returning the smaller-or-equal number).
15. A programmer writes an efficient program to sum two square diagonal matrices (matrices with elements only on
the diagonal positions). The size of each matrix is n X n. What is the time complexity of the algorithm?
A. Θ(n2)
B. Θ(n)
C. Θ(n^ log(n))
D. None of the above
Answer: B
Explanation:
O(n), where n is the size of the matrix. One just loops from 0 to n, and performs the addition.
for(i=0;i<n;i++)
{ c[i][i]=a[i][i] + b[i][i];
}
16. Two programmers, X and Y, are asked to write a code to evaluate the following expression:
a –b + c/(a-b) + (a-b)2
Which statement is TRUE if the taken to load a value in a variable for addition, multiplication or division
between two operands is the same?
A. Code A uses lesser memory and is slower than Code B.
B. Code A uses lesser memory and is faster than Code B.
C. Code A uses more memory and is faster than Code B.
D. Code A uses more memory and is slower than Code B.
Answer: A
Explanation:
Code A does not stores the intermediate results and re-computes similar operations again. For example:
(a-b) is computed twice. Code B stores the result of similar operations in variable d and avoids re-computation.
Therefore, Code B is faster. Code B uses some extra variables for storage; therefore it uses more memory in
comparison to code A.
17. Which of the given systems does the job of executing a program?
A. Linker B. Compiler C. Interpreter D. Loader
Answer: D
Explanation:
A loader is the part of an operating system that is responsible for loading programs and libraries. It is one of the
essential stages in the process of starting a program, as it places programs into memory and prepares them for
execution.
Answer: C
Explanation:
Function f (a, b) will return 0 if a=b. g (a-b) and g (b-a) will always return a positive value equal to 1.
Answer: C
Explanation:
Space Complexity of an algorithm is total space taken by the algorithm with respect to the input size. Space
complexity includes both Auxiliary space and space used by input.
Auxiliary Space is the extra space or temporary space used by an algorithm.
20. Which of the given statements is TRUE about a “bipartite graph” with “n” nodes?
A. It contains n edges.
B. It contains a cycle of odd length.
C. It contains no cycle of odd length.
D. It contains n2 edges.
Answer: C
Explanation:
A bipartite graph (or bi-graph) is a graph whose vertices can be divided into two disjoint and independent sets and
such that every edge connects a vertex in to one in. Vertex sets and are usually called the parts of the graph.
Equivalently, a bipartite graph is a graph that does not contain any odd-length cycles.
21. A librarian has to rearrange the library books on a shelf in a proper order at the end of each day. Which sorting
technique should be the librarian’s ideal choice?
A. Bubble sort
B. Insertion sort
C. Selection sort
D. Heap sort
Answer: B
Explanation:
Library sort, or gapped insertion sort is a sorting algorithm that uses an insertion sort, but with gaps in the array to
accelerate subsequent insertions. The name comes from an analogy:
Suppose a librarian were to store his books alphabetically on a long shelf, starting with the As at the left end, and
continuing to the right along the shelf with no spaces between the books until the end of the Zs. If the librarian
acquired a new book that belongs to the B section, once he finds the correct space in the B section, he will have to
move every book over, from the middle of the Bs all the way down to the Zs in order to make room for the new
book. This is an insertion sort. However, if he were to leave a space after every letter, as long as there was still space
after B, he would only have to move a few books to make room for the new one. This is the basic principle of the
Library Sort.
22. A tree has 5 levels and each node has either 4 or no children. All nodes on the same level have the same number
of children. How many nodes are there in the tree?
(Note: The root is at level 1.)
A. 341 B. 256 C. 1024 D. None of the above
Answer: A
Explanation:
23. How are protected members of a base class accessed in the derived class when inherited privately in C++?
A. Privately B. Publicly C. Protectedly D. Not inherited
Answer: A
Explanation:
class base
{
public:
int x;
protected:
int y;
private:
int z;
};
25. What is the maximum number of edges in an undirected graph with “n” vertices?
A. n*(n-1)/2 B. n*(n+1)/2 C. n*n D. 2*n
Answer: A
Explanation:
In an undirected graph, each edge is specified by its two endpoints and order doesn't matter. The number of edges is
therefore the number of subsets of size 2 chosen from the set of vertices. Since the set of vertices has size n, the
number of such subsets is given by the binomial coefficient C(n,2) (also known as "n choose 2"). Using the formula
for binomial coefficients, C(n,2) = n(n-1)/2.
Answer: A
Explanation:
The key step of any insertion sorting algorithm involves the insertion of an item into a sorted sequence. There are
two aspects to an insertion--finding the correct position in the sequence at which to insert the new element and
moving all the elements over to make room for the new one. Straight insertion sorting uses a linear search to locate
the position at which the next element is to be inserted.
9. Given 2 arrays of unsorted integers. Tell me which of the following process is efficient and why:
a) Sort the arrays and then merge them.
b) Merge the arrays and sort them.
Compare their complexities and given the logic of the option you do not choose.
Explanation:
return 0;
}
Output :
Auxiliary Space : O ( (n + m) )
// Driver code
int main()
{
int a[] = { 10, 5, 15 };
int b[] = { 20, 3, 2, 12 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
return 0;
}
Output :
Space Complexity : O ( (n + m) )
class Test
{
public static void main(String args[])
{
// create anonymous inner class object
new Thread(new Runnable()
{
@Override
public void run()
{
System.out.println("New thread created");
}
}).start();
}
}
Answer:
Java 8 provides following features for Java Programming:
Lambda expressions,
Method references,
Functional interfaces,
Stream API,
Default methods,
Base64 Encode Decode,
Static methods in interface,
Optional class,
Collectors class,
ForEach() method,
Parallel array sorting,
Nashorn JavaScript Engine,
Parallel Array Sorting,
Type and Repating Annotations,
IO Enhancements,
Concurrency Enhancements,
JDBC Enhancements etc.
3. Abstract Class?
Answer:
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract
and non-abstract methods (method with the body).
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
Java String is a powerful concept because everything is treated as a string if you submit any form in window
based, web based or mobile application.
We can use the following steps to insert a new node at beginning of the single linked list...
We can use the following steps to insert a new node at end of the single linked list...
Step 1: Create a newNode with given value and newNode → next as NULL.
Step 2: Check whether list is Empty (head == NULL).
Step 3: If it is Empty then, set head = newNode.
Step 4: If it is Not Empty then, define a node pointer temp and initialize with head.
Step 5: Keep moving the temp to its next node until it reaches to the last node in the list (until temp → next
is equal to NULL).
Step 6: Set temp → next = newNode.
6. What is polymorphism?
Answer:
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We
can perform polymorphism in java by method overloading and method overriding.
If you overload a static method in Java, it is the example of compile time polymorphism.
Runtime Polymorphism in Java
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference variable.
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and
overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it
refers to the subclass object and subclass method overrides the Parent class method, the subclass method is
invoked at runtime.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
Answer:
Data Abstraction is the property by virtue of which only the essential details are displayed to the user.
The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather
than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an
object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other
objects of similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators
will increase the speed of car or applying brakes will stop the car but he does not know about how on
pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.
Abstract classes and Abstract methods :
8.Each and every detail about the project candidate made in Depth?
Answer:
Depends
Answer:
Depends , Student can tell about queries known which is main.
Answer:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you
can add new methods and fields in your current class also.
Why use inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
Anomaly detection (outlier/change/deviation detection) – The identification of unusual data records, that
might be interesting or data errors that require further investigation.
Association rule learning (dependency modelling) – Searches for relationships between variables. For
example, a supermarket might gather data on customer purchasing habits. Using association rule learning,
the supermarket can determine which products are frequently bought together and use this information for
marketing purposes. This is sometimes referred to as market basket analysis.
Clustering – is the task of discovering groups and structures in the data that are in some way or another
"similar", without using known structures in the data.
Classification – is the task of generalizing known structure to apply to new data. For example, an e-mail
program might attempt to classify an e-mail as "legitimate" or as "spam".
Regression – attempts to find a function which models the data with the least error that is, for estimating the
relationships among data or datasets.
Summarization – providing a more compact representation of the data set, including visualization and
report generation.
Answer:
To decide which process to execute first and which process to execute last to achieve maximum CPU
utilisation, computer scientists have defined some algorithms, they are:
In the "First come first serve" scheduling algorithm, as the name suggests, the process which arrives first,
gets executed first, or we can say that the process which requests the CPU first, gets the CPU allocated first.
First Come First Serve, is just like FIFO(First in First out) Queue data structure, where the data element
which is added to the queue first, is the one who leaves the queue first.
This is used in Batch Systems.
It's easy to understand and implement programmatically, using a Queue data structure, where a new process
enters through the tail of the queue, and the scheduler selects process from the head of the queue.
A perfect real life example of FCFS scheduling is buying tickets at ticket counter.
Problems with FCFS Scheduling
Below we have a few shortcomings or problems with the FCFS scheduling algorithm:
It is Non Pre-emptive algorithm, which means the process priority doesn't matter.
If a process with very least priority is being executed, more like daily routine backup process, which takes
more time, and all of a sudden some other high priority process arrives, like interrupt to avoid system crash,
the high priority process will have to wait, and hence in this case, the system will crash, just because of
improper process scheduling.
Not optimal Average Waiting Time.
Resources utilization in parallel is not possible, which leads to Convoy Effect, and hence poor
resource(CPU, I/O etc) utilization.
Shortest Job First scheduling works on the process with the shortest burst time or duration first.
Priority Scheduling
Answer:
Third Normal Form –
A relation is in third normal form, if there is no transitive dependency for non-prime attributes is it is in
second normal form.
A relation is in 3NF iff at least one of the following condition holds in every non-trivial function dependency
X –> Y
X is a super key.
Y is a prime attribute (each element of Y is part of some candidate key).
Answer:
Normalization is the process of minimizing redundancy from a relation or set of relations. Redundancy in
relation may cause insertion, deletion and updation anomalies. So, it helps to minimize the redundancy in
relations. Normal forms are used to eliminate or reduce redundancy in database tables.
First Normal Form –
If a relation contain composite or multi-valued attribute, it violates first normal form or a relation is in first
normal form if it does not contain any composite or multi-valued attribute. A relation is in first normal form
if every attribute in that relation is singled valued attribute.
To be in second normal form, a relation must be in first normal form and relation must not contain any
partial dependency. A relation is in 2NF iff it has No Partial Dependency, i.e., no non-prime attribute
(attributes which are not part of any candidate key) is dependent on any proper subset of any candidate key
of the table.
A relation is in third normal form, if there is no transitive dependency for non-prime attributes is it is in
second normal form.
A relation is in 3NF iff at least one of the following condition holds in every non-trivial function dependency
X –> Y
X is a super key.
Y is a prime attribute (each element of Y is part of some candidate key).
A relation R is in BCNF if R is in Third Normal Form and for every FD, LHS is super key. A relation is in
BCNF iff in every non-trivial functional dependency X –> Y, X is a super key.
Answer:
Initialize three pointers prev as NULL, curr as head and next as NULL.
Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next
Answer:
Following are some of the differences between C and C++.
When compared to C++, C is a subset of C++. All valid C programs are valid C++ programs.
C is a structural or procedural programming language, while C++ is an object oriented
programming language.
In C, Functions are the fundamental building blocks, while in C++, Objects are the fundamental
building blocks.
C doesn't have variable references, while C++ has variable references.
C uses malloc and free for memory allocation while C++ uses new and delete for memory
allocation.
C does not provide direct support for error handling, while C++ supports exception handling that
helps in error detection and smooth handling.
C does not support function and operator overloading, while C++ supports both function and
operator overloading.
C doesn't support Generic programming, while templates in C++ allow to write generic programs.
C doesn't support namespaces while C++ supports them.
Answer:
A passive transponder allows a computer or robot to identify an object. Magnetic labels, such as those on
credit cards and store items, are common examples. A passive transponder must be used with an active
sensor that decodes and transcribes the data the transponder contains. The transponder unit can be physically
tiny, and its information can be sensed up to several feet away.
Simple active transponders are employed in location, identification, and navigation systems for commercial
and private aircraft. An example is an RFID (radio-frequency identification) device that transmits a coded
signal when it receives a request from a monitoring or control point. The transponder output signal is
tracked, so the position of the transponder can be constantly monitored. The input (receiver) and output
(transmitter) frequencies are preassigned. Transponders of this type can operate over distances of thousands
of miles.
19. What are the different memories you know about? Which of them takes the shortest access time?
Answer:
In computer architecture, the memory hierarchy separates computer storage into a hierarchy based on
response time. Since response time, complexity, and capacity are related, the levels may also be
distinguished by their performance and controlling technologies.[1] Memory hierarchy affects performance
in computer architectural design, algorithm predictions, and lower level programming constructs involving
locality of reference.
Designing for high performance requires considering the restrictions of the memory hierarchy, i.e. the size
and capabilities of each component. Each of the various components can be viewed as part of a hierarchy of
memories (m1,m2,...,mn) in which each member mi is typically smaller and faster than the next highest
member mi+1 of the hierarchy. To limit waiting by higher levels, a lower level will respond by filling a
buffer and then signaling to activate the transfer.
Answer:
In a operating systems that use paging for memory management, page replacement algorithm are needed to
decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not
present in memory, page fault occurs and Operating System replaces one of the existing pages with newly
needed page. Different page replacement algorithms suggest different ways to decide which page to replace.
The target for all algorithms is to reduce number of page faults.
Page Fault – A page fault is a type of interrupt, raised by the hardware when a running program accesses a
memory page that is mapped into the virtual address space, but not loaded in physical memory.
Answer:
Zombie Process:
A process which has finished the execution but still has entry in the process table to report to its parent
process is known as a zombie process. A child process always first becomes a zombie before being removed
from the process table. The parent process reads the exit status of the child process which reaps off the child
process entry from the process table.
Orphan Process:
A process whose parent process no more exists i.e. either finished or terminated without waiting for its child
process to terminate is called an orphan process.
Answer:
Semaphore is a simply a variable. This variable is used to solve critical section problem and to achieve
process synchronization in the multi processing environment.
The two most common kinds of semaphores are counting semaphores and binary semaphores. Counting
semaphore can take non-negative integer values and Binary semaphore can take the value 0 & 1. only.
Some point regarding P and V operation
P operation is also called wait, sleep or down operation and V operation is also called signal, wake-up or up
operation.
Both operations are atomic and semaphore(s) is always initialized to one.
A critical section is surrounded by both operations to implement process synchronization.See below
image.critical section of Process P is in between P and V operation.
Counting semaphore
Binary Semaphore
Binary semaphore is a semaphore with the integer value ranges over 0 and 1 whereas the counting
semaphore's integer value ranges over unrestricted domain.
Binary semaphores are easier to implement comparing with the counting semaphore.
Binary semaphore allows only one thread to access the resource at a time. But counting semaphore allows N
accesses at a time. The 2 operations that are defined for binary semaphores are take and release.
Take:Taking a binary semaphore brings it in the “taken” state, trying to take a semaphore that is already
taken enters the invoking thread into a waiting queue.
Release:Releasing a binary semaphore brings it in the “not taken” state if there are not queued threads. If
there are queued threads then a thread is removed from the queue and resumed, the binary semaphore
remains in the “taken” state. Releasing a semaphore that is already in its “not taken” state has no effect.
Counting Semaphore:
Counting Semaphore may have value to be greater than one, typically used to allocate resources from a pool
of identical resources.
A counting semaphore is a synchronization object that can have an arbitrarily large number of states. The
internal state is defined by a signed integer variable, the counter.
b. Zero, no waiting threads, a wait operation would put in queue the invoking thread.
c. Positive, no waiting threads, a wait operation would not put in queue the invoking thread.
• Wait (chSemWait() in ChibiOS/RT). This operation decreases the semaphore counter; if the result is
negative then the invoking thread is queued.
• Signal (chSemSignal() in ChibiOS/RT). This operation increases the semaphore counter, if the result is
non-negative then a waiting thread is removed from the queue and resumed.
Answer:
Question is not clear
24. Define red-black trees.
Answer:
Red-Black Tree is a self-balancing Binary Search Tree (BST) where every node follows following rules.
RedBlackTree
1) Every node has a color either red or black.
3) There are no two adjacent red nodes (A red node cannot have a red parent or red child).
4) Every path from root to a NULL node has same number of black nodes.
int i;
for (i=n-1; ( i >= 0 && arr[i] > key); i--)
arr[i+1] = arr[i];
arr[i+1] = key;
return (n+1);
}
26. What is a web server? What are the load limits in it?
Answer:
Web server refers to server software, or hardware dedicated to running said software, that can serve contents
to the World Wide Web. A web server processes incoming network requests over HTTP and several other
related protocols.
The primary function of a web server is to store, process and deliver web pages to clients. The
communication between client and server takes place using the Hypertext Transfer Protocol (HTTP). Pages
delivered are most frequently HTML documents, which may include images, style sheets and scripts in
addition to the text content.
A web server (program) has defined load limits, because it can handle only a limited number of concurrent
client connections (usually between 2 and 80,000, by default between 500 and 1,000) per IP address (and
TCP port) and it can serve only a certain maximum number of requests per second (RPS, also known as
queries per second or QPS) depending on:
Answer:
int main()
{
int array[100], n, c, d, swap;
return 0;
}
Whenever party A wants to send data to party B, it will send the data along with this ACK field. Considering
the sliding window here of size 8 bits, if A has send frames up to 5 correctly (from B), and wants to send
frames starting from frame 6, it will send ACK6 with the data.
If station A wants to send both data and an acknowledgment, it keeps both fields there.
If station A wants to send just the acknowledgment, then a separate ACK frame is sent.
If station A wants to send just the data, then the last acknowledgment field is sent along with the data.
Station B simply ignores this duplicate ACK frame upon receiving .
29. Given an array of integers, devise a program to replace every element with the next greatest element on
the right side in the array. Also, replace the last element with 5 as there no element on the right side of it.
Ans: void nextGreatest(int arr[], int size)
{
// Initialize the next greatest element
int max_from_right = arr[size-1];
Answer:
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is
a way to destroy the unused objects.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
31. What are pointers in C? Give an example where to illustrate their significance.
Answer:
: A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer
variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in
this statement the asterisk is being used to designate a variable as a pointer.
int main () {
return 0;
}
Answer:
The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative,
hypermedia information systems. This is the foundation for data communication for the World Wide Web
(i.e. internet) since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as
well using extensions of its request methods, error codes, and headers.
Basically, HTTP is a TCP/IP based communication protocol, that is used to deliver data (HTML files, image
files, query results, etc.) on the World Wide Web. The default port is TCP 80, but other ports can be used as
well. It provides a standardized way for computers to communicate with each other. HTTP specification
specifies how clients' request data will be constructed and sent to the server, and how the servers respond to
these requests.
Basic Features
There are three basic features that make HTTP a simple but powerful protocol:
HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP request and after a request is
made, the client disconnects from the server and waits for a response. The server processes the request and
re-establishes the connection with the client to send a response back.
HTTP is media independent: It means, any type of data can be sent by HTTP as long as both the client and
the server know how to handle the data content. It is required for the client as well as the server to specify
the content type using appropriate MIME-type.
HTTP is stateless: As mentioned above, HTTP is connectionless and it is a direct result of HTTP being a
stateless protocol. The server and client are aware of each other only during a current request. Afterwards,
both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser can
retain information between different requests across the web pages.
HTTP Method and Description
1 GET:The GET method is used to retrieve information from the given server using a given URI. Requests
using GET should only retrieve data and should have no other effect on the data.
2 HEAD:Same as GET, but transfers the status line and header section only.
3 POST:A POST request is used to send data to the server, for example, customer information, file upload,
etc. using HTML forms.
4 PUT:Replaces all current representations of the target resource with the uploaded content.
8 TRACE:Performs a message loop-back test along the path to the target resource.
Answer:
A B+ tree is an N-ary tree with a variable but often large number of children per node. A B+ tree consists of
a root, internal nodes and leaves.The root may be either a leaf or a node with two or more children.
A B+ tree can be viewed as a B-tree in which each node contains only keys (not key–value pairs), and to
which an additional level is added at the bottom with linked leaves.
The primary value of a B+ tree is in storing data for efficient retrieval in a block-oriented storage context —
in particular, filesystems. This is primarily because unlike binary search trees, B+ trees have very high
fanout (number of pointers to child nodes in a node, typically on the order of 100 or more), which reduces
the number of I/O operations required to find an element in the tree.
Bulk-loading
Given a collection of data records, we want to create a B+ tree index on some key field. One approach is to
insert each record into an empty tree. However, it is quite expensive, because each entry requires us to start
from the root and go down to the appropriate leaf page. An efficient alternative is to use bulk-loading.
The first step is to sort the data entries according to a search key in ascending order.
We allocate an empty page to serve as the root, and insert a pointer to the first page of entries into it.
When the root is full, we split the root, and create a new root page.
Keep inserting entries to the right most index page just above the leaf level, until all entries are indexed.
Answer:
:Constants refer to fixed values that the program may not alter and they are called literals.Constants can be of
any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters,
Strings and Boolean Values.
Again, constants are treated just like regular variables except that their values cannot be modified after their
definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or
0X for hexadecimal, 0 for octal, and nothing for decimal.
212
215u
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can
represent floating point literals either in decimal form or exponential form.
3.14159
314159E-5L
Boolean Literals
There are two Boolean literals and they are part of standard C++ keywords −
Character Literals
Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide
character literal (e.g., L'x') and should be stored in wchar_t type of variable . Otherwise, it is a narrow
character literal (e.g., 'x') and can be stored in a simple variable of char type.
String Literals
String literals are enclosed in double quotes. A string contains characters that are similar to character literals:
plain characters, escape sequences, and universal characters.
"hello, dear"
35. Describe the merge sort principle and what will be its time complexity?
Ans: Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the
two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The
merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two
sorted sub-arrays into one.
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and time
complexity can be expressed as following recurrence relation.
T(n) = 2T(n/2) +
The above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case
Time complexity of Merge Sort is in all 3 cases (worst, average and best) as merge sort
always divides the array in two halves and take linear time to merge two halves.
Company Name: NEXT SCM
Book Index: 181-(D)
TECHNICAL INTERVIEW
// Driver class
class SyncDemo
{
public static void main(String args[])
{
Sender snd = new Sender();
ThreadedSend S1 =
new ThreadedSend( " Hi " , snd );
ThreadedSend S2 =
new ThreadedSend( " Bye " , snd );
Output:
Sending Hi
Hi Sent
Sending Bye
Bye Sent
Waterfall Model: This model involves finishing each phase completely before commencing
the next one. When each phase is completed successfully, it is reviewed to see if the
project is on track and whether it is feasible to continue.
V-Shaped Model: This model focuses on the execution of processes in a sequential
manner, similar to the waterfall model but with more importance placed on testing. Testing
procedures are written even before the commencement of writing code. A system plan is
generated before starting the development phase.
Incremental Model: This life cycle model involves multiple development cycles. The cycles
are divided up into smaller iterations. These iterations can be easily managed and go
through a set of phases including requirements, design, implementation and testing. A
working version of the software is produced during the first iteration, so working software is
created early in the development process.
Ans: In SQL, dates are complicated for newbies, since while working with database, the format of the date in table
must be matched with the input date in order to insert. In various scenarios instead of date, datetime (time is also
involved with date) is used.
The DATE() function extracts the date part of a date or date/time expression.
Syntax
DATE(date)
ProductName OrderDate
SYSDATE()
MySQL SYSDATE() returns the current date and time in YYYY-MM-DD HH:MM:SS or
YYYYMMDDHHMMSS.uuuuuu format depending on the context of the function.
Note: For example codes using SYSDATE(), your output may vary from the output shown.
Syntax:
SYSDATE()
Example:
Code:
SELECT SYSDATE();
Sample Output:
Note: Many database systems do rounding differently than you might expect. When rounding a number with a
fractional part to an integer, our school teachers told us to round .1 through .4 DOWN to the next lower integer,
and .5 through .9 UP to the next higher integer. But if all the digits 1 through 9 are equally likely, this introduces a
slight bias towards infinity, since we always round .5 up. Many database systems have adopted the IEEE 754
standard for arithmetic operations, according to which the default rounding behavior is "round half to even." In this
scheme, .5 is rounded to the nearest even integer. So, both 11.5 and 12.5 would be rounded to 12.
Ans: UNION
UNION combines the result set of two or more queries into a single result set. This result set includes all the
rows that belong to all queries in the UNION.
The following points need to be considered when using the UNION operator:
The number of columns and sequence of columns must be the same in all queries
The data types must be compatible.
Syntax
Example
Consider the following example. I have two tables that have Id, name and phone number columns.
Output
UNION ALL
UNION ALL is very similar to UNION. It also includes duplicate rows in the result set.
UNION always returns distinct rows. In other words it eliminates duplicate rows from the result set.
Example
Consider the following example. I have two tables and both has two rows. One row is common to both tables.
When we union these two tables it returns three rows (removes duplicate rows from the result set).
1. DECLARE @Table1 AS Table (ID INT, Name VARCHAR(10), PhoneNumber VARCHAR(12))
2. DECLARE @Table2 AS Table (ID INT, Name VARCHAR(10), PhoneNumber VARCHAR(12))
3.
4. INSERT INTO @Table1 VALUES(1,'Tejas', '88996655')
5. INSERT INTO @Table1 VALUES(2,'Jignesh', '99986655')
6.
7. INSERT INTO @Table2 VALUES(1,'Rakesh', '88446655')
8. INSERT INTO @Table2 VALUES(2,'Jignesh', '99986655')
9.
10. SELECT * FROM @Table1
11. UNION
12. SELECT * FROM @Table2
Output
Ans: ArrayList and Vector both implements List interface and maintains insertion order.
But there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
Ans: Always ArrayList will shows better performance compared to Vector, except
Synchronization both are almost same in their performance. Vector is Synchronized means
thread safe, only 1 thread can access so its very slow compared to ArrayList, because in our
real time projects we should not require synchronized methods always.
What am saying is always try to use ArrayList rather Vector if its not required
any Synchronization in your requirements, even if so you know how to make ArrayList as
synchronized right (just like above).
Ans: The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at a same time can have different characteristic. Like a man at a same
time is a father, a husband, a employee. So a same person posses have different behavior in different situations. This
is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
Compile time Polymorphism
Runtime Polymorphism
1. Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator
overloading.
Function Overloading: When there are multiple functions with same name but different parameters then these
functions are said to be overloaded. Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
Rules of Function Overloading
// C++ program for function overloading
#include <bits/stdc++.h>
int main() {
Geeks obj1;
Output:
value of x is 7
value of x is 9.132
In the above example, a single function named func acts differently in three different situations which is the property
of polymorphism.
1.
Operator Overloading: C++ also provide option to overload operators. For example, we can make
the operator (‘+’) for string class to concatenate two strings. We know that this is the addition
operator whose task is to add to operands. So a single operator ‘+’ when placed between integer
operands , adds them and when placed between string operands, concatenates them.
Example:
// CPP program to illustrate
// Operator Overloading
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Run on IDE
Output:
12 + i9
In the above example the operator ‘+’ is overloaded. The operator ‘+’ is an addition operator and can
add two numbers(integers or floating point) but here the operator is made to perform addition of two
imaginary or complex numbers. To learn operator overloading in details visit this link.
2. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.
Function overriding on the other hand occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
// C++ program for function overriding
#include <bits/stdc++.h>
using namespace std;
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
void show ()
{ cout<< "show derived class" <<endl; }
};
//main function
int main()
{
base *bptr;
derived d;
bptr = &d;
return 0;
}
Output:
The compiler checks the checked exception. The compiler does not check the Unchecked
exception.
Except "RuntimeException" class all the child "RuntimeException" class and its child classes,
If we do not handle the checked exception, then the Even if we do not handle the unchecked
The program doesn't compile if there is an The program compiles successfully even if
unhandled checked exception in the program code. there is an unhandled unchecked exception in
t1.run();
t2.run();
}
}
Test it Now
Output:1
2
3
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because
here t1 and t2 will be treated as normal object not thread object.
15. What is different in extend Thread class and implement Runnable interface?
Ans:Java provides multithreading to parallelize execution of tasks (code) and you need threads to run multiple things
in parallel e.g. download a file in the background and show the progress bar at front-end. There are two ways to
create a Thread in Java, first by extending java.lang.Thread class and second by implementing
the java.lang.Runnable interface. Since interviewer loves comparison based questions, what is the difference
between extending thread and implementing Runnable is also a popular Java thread question. In this article, I'll tell
you how to answer this question by explaining the difference between extending the Thread class and implementing
the Runnable interface, and which one is the better way to create threads In Java. Both approaches have their pros
and cons and there is a situation when extending Thread is logical but in most cases implementing Runnable is the
better option. Let's see the difference between extends Thread and implements Runnable in Java.
As I said, there are two main ways to create a thread in Java, by extending Thread class and
overriding run() method or by implementing Runnable interface and overriding run() method, let's see the
advantages and disadvantage and differences between these two approaches.
1) The first and most important difference between extending Thread and implementing Runnable comes from
the fact that a class can only extend one class in Java. So if you extend the Thread class then your class lose
that option and it cannot extend another class, but if you implement Runnable then your Thread class can still
extend another class e.g. Canvas. It's a common pattern in Java GUI programming that your class
extends Canvas and implements Runnable, EventListener etc.
2) The second difference between extends Thread and implements Runnable is that using the Runnable instance
to encapsulate the code which should run in parallel provides better reusability. You can pass that Runnable to
any other thread or thread pool.
3) The third difference comes from OOP perspective. In case, you implement Runnable, both Task and Executor
( a thread which execute the task) are loosely coupled but if you extend Thread then they are tightly coupled.
4) Another difference between Thread and Runnable comes from the fact that you are extending Thread class
just for run() method but you will get overhead of all other methods which come from Thread class. So, if your
goal is to just write some code in run() method for parallel execution then use Runnable instead of
extending Thread class.
5) The fifth difference between extending Thread and implementing Runnable also comes from OOP
perspective. In Object oriented programming you extend a class to enhance it, to put some new features on it. So,
if you just want to reuse the run() method, then stick with implementing the Runnable interface rather than
extending Thread class.
6) It's easier to maintain code encapsulated in Runnable interface because you only need to make the change in
one place but if that code is scattered around multiple Thread class, you need to make the change at multiple
places.
7) Last but not the least difference between extends Thread and implements Runnable is that it's good coding
practice to use Runnable for the specifying task as you can reuse it on Thread as well as on Executor framework.
17.
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its
properties and its functions. Like Human Being, having body parts, and performing various actions.
Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat,
see etc. Male and Female are also classes, but most of the properties and functions are included in HumanBeing,
hence they can inherit everything from class HumanBeing using the concept of Inheritance.
Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being, Male or Female, we
just mean a kind, you, your friend, me we are the forms of these classes. We have a physical existence while a class
is just a logical definition. We are the objects.
Abstraction
Abstraction means, showcasing only the required things to the outside world while hiding the details. Continuing our
example, Human Being's can talk, walk, hear, eat, but the details are hidden from the outside world. We can take
our skin as the Abstraction factor in our case, hiding the inside mechanism.
Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk. Our hands, help us
hold things. This binding of the properties to functions is called Encapsulation.
Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either changing how it is done
or by changing the parts using which it is done. Both the ways have different terms for them.
If we walk using our hands, and not legs, here we will change the parts used to perform something. Hence this is
called Overloading.
And if there is a defined way of walking, but I wish to walk differently, but using my legs, like everyone else. Then I
can walk like I want, this will be called as Overriding
1. Overloading happens at compile-time while Overriding happens at runtime: The binding of overloaded
method call to its definition has happens at compile-time however binding of overridden method call to its
definition happens at runtime.
2. Static methods can be overloaded which means a class can have more than one static method of same name.
Static methods cannot be overridden, even if you declare a same static method in child class it has nothing to
do with the same method of parent class.
3. The most basic difference is that overloading is being done in the same class while for overriding base and
child classes are required. Overriding is all about giving a specific implementation to the inherited method of
parent class.
4. Static binding is being used for overloaded methods and dynamic binding is being used for
overridden/overriding methods.
5. Performance: Overloading gives better performance compared to overriding. The reason is that the binding
of overridden methods is being done at runtime.
6. private and final methods can be overloaded but they cannot be overridden. It means a class can have more
than one private/final methods of same name but a child class cannot override the private/final methods of
their base class.
7. Return type of method does not matter in case of method overloading, it can be same or different. However
in case of method overriding the overriding method can have more specific return type (refer this).
8. Argument list should be different while doing method overloading. Argument list should be same in method
Overriding.
Streams are generally associated to a physical source or destination of characters, like a disk file, the keyboard,
or the console, so the characters gotten or written to/from our abstraction called stream are physically
input/output to the physical device. For example, file streams are C++ objects to manipulate and interact with
files; Once a file stream is used to open a file, any input or output operation performed on that stream is
physically reflected in the file.
To operate with streams, C++ provides the standard iostream library
22. Array
Ans:When there is a need to use many variables then There is a big problem because we will Conflict with name of
variables So that in this Situation where we wants to Operate on many numbers then we can use array . The Number
of Variables also increases the complexity of the Program. So that we uses Arrays.
Arrays are Set of Elements having same data type or we can Say that Arrays are Collection of Elements having same
name and same data type But Always Remember Arrays are Always Start From its index value and the index of
array is start From 0 to n-1.
Suppose we wants to Access 5th Element of array then we will use 4th Element Because Arrays are Start From 0 and
arrays are always stored in Continuous Memory Locations The Number of Elements and Types of array are
Identified by Subscript of array Elements. The Various types of Array those are provided by c as Follows:-
Ans:You can have an array of any data type: integer, float, double etc. You can even have character arrays which
can store strings. A string is an array of characters terminated by the null character (‘\0’). For example, if we store
the word "hello" in a character array, the individual characters of "hello" will be stored and the last character of the
array will be a null character (‘\0’). It is the null character that denotes the end of the string (this is very important
when doing string operations –without the null character we will not be able to identify the end of the string in
memory). The character data type can store only a single character but a character array can take in a consecutive
series of characters depending on the size of the character array.
Example:
char word[6]={'h','e','l','l','o','\0'};
You have to provide space to accommodate the null character. You can also assign a string constant directly as
below:
char word[6]="Hello";
"Hello" is called a string constant and the compiler will automatically add the null character to the array.
is incorrect and will produce a compile error because there is no space for adding the null character. But if you don’t
specify the size of the array then it is acceptable:
In this case while compiling the compiler will set the size of the array and provide space for the null character also.
Beware: You can assign a string literal to a character array only at the time of declaration. You cannot use:
word[6]="Helloo"; //WRONG
Another Example:
char name[10];
The above declaration declares an array of character type that can store 10 characters. The name of the array is
‘name’.
// A program for getting the name of a person and displaying the name
# include <iostream.h>
int main ( )
{
char name[15];
cout<< "Enter your name : ";
cin>> name;
cout<< "Your name is "<<name;
return 0;
}
24. Database
Ans:: Database is a systematic collection of data. Databases support storage and manipulation of data. Databases
make data management easy. Let's discuss few examples.
An online telephone directory would definitely use database to store data pertaining to people, phone numbers, other
contact details, etc.
Your electricity service provider is obviously using a database to manage billing , client related issues, to handle
fault data, etc.
Let's also consider the facebook. It needs to store, manipulate and present data related to members, their friends,
member activities, messages, advertisements and lot more.
Ans: Errors can be broadly categorized into two types. We will discuss them one by one.
Run Time Errors - They are also known as exceptions. An exception caught during run time creates serious issues.
Errors hinder normal execution of program. Exception handling is the process of handling errors and exceptions in
such a way that they do not hinder normal execution of the system. For example, User divides a number by zero, this
will compile successfully but an exception or run time error will occur due to which our applications will be crashed.
In order to avoid this we'll introduce exception handling technics in our code.
Try
Catch
Throw
Syntax:
Try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}
Try
Try block is intended to throw exceptions, which is followed by catch blocks. Only one try block.
Catch
Catch block is intended to catch the error and handle the exception condition. We can have multiple catch blocks.
Throw
It is used to throw exceptions to exception handler i.e. it is used to communicate information about error. A throw
expression accepts one parameter and that parameter is passed to handler.
Drive Name: EPAM
Book Index: 183-(D)
TECHNICAL INTERVIEW
Explanation:
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a super class. The determination of
the method to be called is based on the object being referred to by the reference variable.
Upcasting:-
When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:
class A{}
A a=new B();//upcasting
In this example, we are creating two classes vehical and pulsor. pulsor class extends vehical class and overrides its
run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass
object and subclass method overrides the Parent class method, subclass method is invoked at runtime.
note: Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism
class vehical{
void run(){System.out.println("running");}
b.run();
}
}
Explanation:
The main differences between abstract class and interface are given bellow.
Abstract class
1)abstract class can extend only one class or one
abstract class at a time Interface
2)A class can extend only one abstract class 1)Interface can extend any number of interfaces at a
3)abstract class can have protected , public and public time
abstract methods 2)A class can implement any number of interfaces
4)abstract class can have static methods 3)Interface can have only public abstract methods i.e.
5) Abstract class can have constructor. by default
6)abstract class can have both abstract and concrete 4)Interface cannot have static methods.
methods 5)Interface cannot have constructor.
7)An abstract class can have method body (non-abstract 6)interface can have only abstract methods
methods). 7)Interface have only abstract methods.
8)An abstract class can have instance variables. 8)An interface cannot have instance variables.
9)In abstract class keyword ‘abstract’ is mandatory to 9)In an interface keyword ‘abstract’ is optional to
declare a method as an abstract declare a method as an abstract
A Wrapper class is a class whose object wraps or contains a primitive data types. When we create an object to a
wrapper class, it contains a field and in this field, we can store a primitive data types. In other words, we can wrap a
primitive value into a wrapper class object.
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments
passed into a method (because primitive types are passed by value).
2. The classes in java.util package handle only objects and hence wrapper classes help in this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference
types) and not primitive types.
4. An object is needed to support synchronization in multithreading.
Explanation:
The meaning of platform independent is that, the java source code can run on all operating systems.
A program is written in a language which is a human readable language. It may contain words, phrases etc which
the machine does not understand. For the source code to be understood by the machine, it needs to be in a
language understood by machines, typically a machine-level language. So, here comes the role of a compiler.
The compiler converts the high-level language (human language) into a format understood by the machines.
Therefore, a compiler is a program that translates the source code for another program from a programming
language into executable code.
This executable code may be a sequence of machine instructions that can be executed by the CPU directly, or it
may be an intermediate representation that is interpreted by a virtual machine. This intermediate representation
in Java is the Java Byte Code.
Explanation:
Explanation:
No, you cannot override private method; hence the method is called private so that no class extending that
class has any access to the private method. Private methods are not visible to child classes.
Static methods also cannot be overridden, because static methods are a part of the Class itself, and not a part
of any instance (object) of that class. You however can declare same static method with same signature in child
classes, but that would not be considered as runtime polymorphism (override of methods).
Explanation:
The association between two objects is known as Composition, when one class owns other class and other class
cannot meaningfully exist, when it's owner destroyed, for example, Human class is a composition of several
body parts including Hand, Leg and Heart. When human object dies, all it's body part ceased to exist
meaningfully, this is one example of Composition.
Another example of Composition is Car and it's part e.g. engines, wheels etc. Individual parts of the car cannot
function when a car is destroyed.
}
Public static void main(String args[]){
Addition addition = new Addition();
addition.add();
}
}
Here the add() method having different parameters in the Addition class is overloaded in the same class as
well as with the super class.
Note: Polymorphism is not applicable for method overloading.
12. What is singleton class and how can we make a class singleton?
Explanation:
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at
a time.
After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.
So whatever modifications we do to any variable inside the class through any instance, it affects the variable of the
single instance created and is visible if we access that variable through any variable of that class type defined.
To design a singleton class:
1. Make constructor as private.
2. Write a static method that has return type object of this singleton class. Here, the concept of Lazy
initialization in used to write this static method.
class Singleton
public String s;
private Singleton()
if (single_instance == null)
return single_instance;
// Driver Class
class Main
Singleton x = Singleton.getInstance();
Singleton y = Singleton.getInstance();
Singleton z = Singleton.getInstance();
x.s = (x.s).toUpperCase();
System.out.println("String from x is " + x.s);
System.out.println("\n");
z.s = (z.s).toLowerCase();
Output:
1. JDK – Java Development Kit (in short JDK) is Kit which provides the environment to develop and
execute(run) the Java program. JDK is a kit(or package) which includes two things
1. Development Tools(to provide an environment to develop your java programs)
2. JRE (to execute your java program).
Note : JDK is only used by Java Developers.
2. JRE – Java Runtime Environment (to say JRE) is an installation package which provides environment
to only run(not develop) the java program(or application)onto your machine. JRE is only used by them
who only wants to run the Java Programs i.e. end users of your system.
3. JVM – Java Virtual machine(JVM) is a very important part of both JDK and JRE because it is contained
or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible
for executing the java program line by line hence it is also known as interpreter.
Java supports property 1, 2, 3, 4 and 6 but fails to support property 5 and 7 given above. Java
language is not a Pure Object Oriented Language as it contain these properties:
Primitive Data Type ex. int, long, bool, float, char, etc as Objects: Smalltalk is a “pure” object-
oriented programming language unlike Java and C++ as there is no difference between values which are
objects and values which are primitive types. In Smalltalk, primitive values such as integers, booleans and
characters are also objects.
In Java, we have predefined types as non-objects (primitive types).
int a = 5;
System.out.print(a);
The static keyword: When we declares a class as static then it can be used without the use of an object
in Java. If we are using static function or static variable then we can’t call that function or variable by using
dot(.) or class object defying object oriented feature.
Wrapper Class: Wrapper class provides the mechanism to convert primitive into object and object into
primitive. In Java, you can use Integer, Float etc. instead of int, float etc. We can communicate with objects
without calling their methods. ex. using arithmetic operators.
String s1 = "ABC" + "A" ;
Even using Wrapper classes does not make Java a pure OOP language, as internally it will use the operations
like Unboxing and Autoboxing. So if you create instead of int Integer and do any mathematical operation on it,
under the hoods Java is going to use primitive type int only.
Sometimes interviewer also ask : Explain the meaning of each word in public static void
main? it is also a important one.
Public : is an Access Specifier, which defines who can access this Method. Public means that
this Method will be accessible by any Class(If other Classes are able to access this Class.).
Static : is a keyword which identifies the class related thing. This means the given Method or
variable is not instance related but Class related. It can be accessed without creating the instance
of a Class.
Void : is used to define the Return Type of the Method. It defines what the method can return.
Void means the Method will not return any value.
main: is the name of the Method. This Method name is searched by JVM as a starting point for
an application with a particular signature only.
String[] args : is the parameter to the main Method. you can put any name instead of args.
10. What is the difference between static (class) method and instance method?
Ans:
Instance method can access the instance methods and instance variables directly.
Instance method can access static variables and static methods directly.
Static methods can access the static variables and static methods directly.
Static methods can’t access instance methods and instance variables directly. They must use reference to
object. And static method can’t use this keyword as there is no instance for ‘this’ to refer to.
12. Which class is the super class for all the classes?
Ans: Object class is the Super class of every class. when you create a java program java.lang.* package
automatically imported to you program so that you do not need to import it explicitely.
For example throwable class is super class of all error and exceptions.
With an interface, though, you're describing something the class is capable of doing,
rather than borrowing another class's method of doing something. Multiple interfaces are
much less likely to cause tricky conflicts that need to be resolved than are multiple
parent classes.
Ans: this(...) will call another constructor in the same class whereas super() will call a
super constructor. If there is no super() in a constructor the compiler will add one
implicitly.
Thus if both were allowed you could end up calling the super constructor twice.
Example (don't look for a sense in the parameters):
class A {
public A() {
this( false );
}
class B extends A {
public B() {
super();
}
Now, if you call new B(5) the following constructors are invoked:
this( false);
A() ---------------> A(false)
^
|
| super();
|
| this();
B() <--------------- B(5) <--- you start here
Update:
If you were able to use this() and super() you could end up with something like this:
(Attention: this is meant to show what could go wrong, if you were allowed to do that -
which you fortunately aren't)
this( false);
A() ---------------> A(false)
^ ^
| |
| super(); | super( true ); <--- Problem: should the parameter be true or false?
| |
| this(); |
B() <--------------- B(5) <--- you start here
As you can see, you'd run into a problem where the A(boolean) constructor could be
invoked with different parameters and you'd now have to somehow decide which should
be used. Additionally the other constructors (A() and B()) could contain code that now
might not get called correctly (i.e. out of order etc.) since the call to super( true ) would
circumvent them while this() wouldn't.
Method overriding is one of the way by which java achieve Run Time Polymorphism.The version
of a method that is executed will be determined by the object that is used to invoke it. If an object
of a parent class is used to invoke the method, then the version in the parent class will be
executed, but if an object of the subclass is used to invoke the method, then the version in the
child class will be executed.In other words, it is the type of the object being referred to (not the type
of the reference variable) that determines which version of an overridden method will be
executed.
When final is used with non-primitive variables (Note that non-primitive variables are always
references to objects in Java), the members of the referred object can be changed. final for non-
primitive variables just mean that they cannot be changed to refer to any other object
class Test1 {
int i = 10;
}
1) Synchronization: ArrayList is non-synchronized which means multiple threads can work on ArrayList at
the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be an another
thread performing remove operation on ArrayList at the same time in a multithreaded environment
while Vector is synchronized. This means if one thread is working on Vector, no other thread can get a hold
of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.
2) Resize: Both ArrayList and Vector can grow and shrink dynamically to maintain the optimal use of
storage, however the way they resized is different. ArrayList grow by half of its size when resized while
Vector doubles the size of itself by default when grows.
3) Performance: ArrayList gives better performance as it is non-synchronized. Vector operations gives poor
performance as they are thread-safe, the thread which works on Vector gets a lock on it which makes other
thread wait till the lock is released.
4) fail-fast: First let me explain what is fail-fast: If the collection (ArrayList, vector etc) gets structurally
modified by any means, except the add or remove methods of iterator, after creation of iterator then the
iterator will throw ConcurrentModificationException. Structural modification refers to the addition or
deletion of elements from the collection.
As per the Vector javadoc the Enumeration returned by Vector is not fail-fast. On the other side the iterator
and listIterator returned by ArrayList are fail-fast.
5) Who belongs to collection framework really? The vector was not the part of collection framework, it has
been included in collections later. It can be considered as Legacy code. There is nothing about Vector which
List collection cannot do. Therefore Vector should be avoided. If there is a need of thread-safe operation
make ArrayList synchronized as discussed in the next section of this post or use CopyOnWriteArrayList
which is a thread-safe variant of ArrayList.
22. What is the difference between Hash Set and Hash Map?
Explanation: Differences:
HashSet HashMap
In HashSet we store HashMap is used for storing key & value pairs. In short it
objects(elements or values) e.g. If maintains the mapping of key & value (The HashMap class is
we have a HashSet of string roughly equivalent to Hashtable, except that it is unsynchronized
elements then it could depict a set and permits nulls.) This is how you could represent HashMap
of HashSet elements: {“Hello”, “Hi”, elements if it has integer key and value of String type: e.g. {1-
“Bye”, “Run”} >”Hello”, 2->”Hi”, 3->”Bye”, 4->”Run”}
PreparedStatement ps=con.prepareStatement(
"insert into filetable values(?,?)");
ps.setInt(1,101);
ps.setCharacterStream(2,fr,(int)f.length());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is
a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive
automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa
unboxing.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
There are some important differences between an applet and a standalone Java application, including the
following −
A main() method is not invoked on an applet, and an applet class will not define main().
When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's
machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate
runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes various methods during
the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of an applet is often
referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that
must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.
Locale (computer software), a set of parameters that defines the user's language, region and any special
variant preferences that the user wants to see in their user interface. Usually a locale identifier consists of at
least a language identifier and a region identifier.
Locale (computer hardware), an abstraction of the concept of a localized set of hardware resources which are
close enough to enjoy uniform memory access.
Both processes and threads are independent sequences of execution. The typical difference is that threads (of
the same process) run in a shared memory space, while processes run in separate memory spaces.
DRIVE NAME: NEWGEN
Book Index: 187-(D)
TECHNICAL INTERVIEW
1. What is Servlet?
Sol:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the
right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the
left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
5. Triggers in SQL.
Sol: A trigger is a special type of stored procedure that automatically executes when an event occurs in the
database server. DML triggers execute when a user tries to modify data through a data manipulation
language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view.
6. Overriding in Java.
Sol: Overriding in Java. In any object-oriented programming language, Overriding is a feature that allows a
subclass or child class to provide a specific implementation of a method that is already provided by one of
its super-classes or parent classes.
Syntax
The basic syntax of the UPDATE query with a WHERE clause is as follows −
Example
The following query will update the ADDRESS for a customer whose ID number is 6 in the table.
If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS table, you
do not need to use the WHERE clause as the UPDATE query would be enough as shown in the following
code block.
1. Tell me something about yourself along with your technical skills and projects undertaken in
detail.
Sol:
I’m really excited to join this practicing page to improve and practice my English. I’m a second year
Software engineering student. I have a very good computer skills using Microsoft office and
programming using C++,Java and C# . I don’t have a job experience yet, but I’m a fast learner, team
sprite and hardworking that looking for this position to utilize my proven and developing programming
skills.
TECHNICAL INTERVIEW
The process of learning begins with observations or data, such as examples, direct experience, or
instruction, in order to look for patterns in data and make better decisions in the future based on the
examples that we provide. The primary aim is to allow the computers learn automatically without human
intervention or assistance and adjust actions accordingly.
Supervised machine learning algorithms can apply what has been learned in the past to new data
using labeled examples to predict future events. Starting from the analysis of a known training
dataset, the learning algorithm produces an inferred function to make predictions about the output
values. The system is able to provide targets for any new input after sufficient training. The learning
algorithm can also compare its output with the correct, intended output and find errors in order to
modify the model accordingly.
In contrast, unsupervised machine learning algorithms are used when the information used to train
is neither classified nor labeled. Unsupervised learning studies how systems can infer a function to
describe a hidden structure from unlabeled data. The system doesn’t figure out the right output, but
it explores the data and can draw inferences from datasets to describe hidden structures from
unlabeled data.
Semi-supervised machine learning algorithms fall somewhere in between supervised and
unsupervised learning, since they use both labeled and unlabeled data for training – typically a
small amount of labeled data and a large amount of unlabeled data. The systems that use this
method are able to considerably improve learning accuracy. Usually, semi-supervised learning is
chosen when the acquired labeled data requires skilled and relevant resources in order to train it /
learn from it. Otherwise, acquiring unlabeled data generally doesn’t require additional resources.
Reinforcement machine learning algorithms is a learning method that interacts with its environment
by producing actions and discovers errors or rewards. Trial and error search and delayed reward are
the most relevant characteristics of reinforcement learning. This method allows machines and
software agents to automatically determine the ideal behavior within a specific context in order to
maximize its performance. Simple reward feedback is required for the agent to learn which action is
best; this is known as the reinforcement signal.
Machine learning enables analysis of massive quantities of data. While it generally delivers faster, more
accurate results in order to identify profitable opportunities or dangerous risks, it may also require
additional time and resources to train it properly. Combining machine learning with AI and cognitive
technologies can make it even more effective in processing large volumes of information.
Drive Name: NIIT
/* UTILITY FUNCTIONS */
/*Function to reverse any sequence starting with pointer
begin and ending with pointer end */
void reverse(char* begin, char* end)
{
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
vector<string> split_string(string);
/*
* Complete the buildString function below.
*/
int buildString(int a, int b, string s) {
/*
* Write your code here.
*/
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int n = stoi(nab[0]);
int a = stoi(nab[1]);
int b = stoi(nab[2]);
string s;
getline(cin, s);
fout.close();
return 0;
}
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == '') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = '';
size_t i = 0;
size_t pos = input_string.find(delimiter);
i = pos + 1;
pos = input_string.find(delimiter, i);
}
return splits;
}
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
SELECT ID, NAME, SALARY FROM CUSTOMERS;
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
10. How you can add validation while coding for password?
Ans: <div class="container">
<form action="/action_page.php">
<label for="usrname">Username</label>
<input type="text" id="usrname" name="usrname" required>
<label for="psw">Password</label>
< input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must
contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters"
required>
<div id="message">
<h3>Password must contain the following:</h3>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
11. Have you implemented database in your project?
Ans : Depends what project is.
15. Two strings are given, how many times first string is being repeated in second string.
Ans: #include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s[1000], r[1000];
int begin, end, count = 0;
printf("Input a string\n");
gets(s);
end = count - 1;
for (begin = 0; begin < count; begin++) {
r[begin] = s[end];
end--;
}
r[begin] = '\0';
printf("%s\n", r);
return 0;
}
20. How many maximum rows and columns can be there when you create a table?
Ans: It's true that if you use an INT or BIGINT as your primary key, you can only have as many rows as the
number of unique values in the data type of your primary key, but you don't have to make your primary key an
integer, you could make it a CHAR(100). You could also declare the primary key over more than one column.
There are other constraints on table size besides number of rows. For instance you could use an operating system
that has a file size limitation. Or you could have a 300GB hard drive that can store only 300 million rows if each
row is 1KB in size.
22. How many marks will you give yourself on the basis of your knowledge of DBMS?
Ans: Depends on student’s response
23. What is the latest of DBMS?
Ans: Oracle database is the most widely used object-relational database management software. The latest version of
this tool is 12c where c means cloud computing. It supports multiple Windows, UNIX, and Linux versions
t = x;
x = y;
y = t;
return 0;
}
27. Create a program swapping of two characters without using third variable.
Ans: int main()
{
int a, b;
a = a + b;
b = a - b;
a = a - b;
Customers" table:
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico
3 Antonio Moreno Taquería Antonio Moreno Mexico
Result
import java.sql.*;
class MysqlCon{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
Statement stmt=con.createStatement();
while(rs.next())
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
con.close();
}
Drive Name: AMAZON
TECHNICAL INTERVIEW
1. Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no
two numbers in the sequence should be adjacent in the array.
Solution:
Algorithm: Loop for all elements in arr[] and maintain two sums incl and excl where incl = Max sum including
the previous element and excl = Max sum excluding the previous element.
Max sum excluding the current element will be max(incl, excl) and max sum including the current element will be
excl + current element (Note that only excl is considered because elements cannot be adjacent).
At the end of the loop return max of incl and excl.
Example:
arr[] = {5, 5, 10, 40, 50, 35}
incl = 5
excl = 0
#include<stdio.h>
Given any source point and destination point on a chess board, we need to find whether Knight can move to
the destination or not.
The above figure details the movements for a knight ( 8 possibilities ). Note that a knight cannot go out of the
board.
If yes, then what would be the minimum number of steps for the knight to move to the said point.
If knight can not move from the source point to the destination point, then return -1
Input:
Input : 8 8 1 1 8 8
Output : 6
Assume this problem as searching in graph where each block of chess board is vertex.
Define edges in such a graph and the ways when can you travel from vertex i to vertex
j. Once we have the graph, then it reduces to finding the shortest path in an
unweighted graph.
(x, y) ->
(x + 2, y + 1)
(x + 2, y - 1)
(x - 2, y + 1)
(x - 2, y - 1)
(x + 1, y + 2)
(x + 1, y - 2)
(x - 1, y + 2)
(x - 1, y - 2)
#include<bits/stdc++.h>
#define pb push_back
#define ff first
#define ss second
#define mpa make_pair
using namespace std;
typedef long long LL;
int bfs(pair<int, int> p1, pair<int, int> p2, pair<int, int> p3) {
int N = p3.ff;
int M = p3.ss;
queue<pair<pair<int, int>, int> > Que;
map<pair<int, int>, bool> Vis;
Que.push(mpa(p1, 0));
while(!Que.empty()) {
if(Vis.count(mpa(x, y)))
continue;
Vis[mpa(x, y)] = true;
int x1 = x + dx[i];
int y1 = y + dy[i];
if(valid(x1, y1, N, M))
Que.push(mpa(mpa(x1, y1), dis));
}
return -1;
}
int solve(int N, int M, int x1, int y1, int x2, int y2) {
int main() {
3. Write an algorithm to traverse a knight covering all the squares on a chessboard starting at a particular
point.
Solution:
Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems
which are typically solved using backtracking technique have following property in common. These problems can
only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for
these problems is to try all configurations and output a configuration that follows given problem constraints.
Backtracking works in incremental way and is an optimization over the Naive solution where all possible
configurations are generated and tried.
The knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each
square exactly once.
Following is chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight.
knight-tour-problem
Let us first discuss the Naive algorithm for this problem and then the Backtracking algorithm.
The Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints.
Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and
one by one add items (Meaning of item varies from problem to problem. In context of Knight’s tour problem, an
item is a Knight’s move). When we add an item, we check if adding the current item violates the problem constraint,
if it does then we remove the item and try other alternatives. If none of the alternatives work out then we go to
previous stage and remove the item added in the previous stage. If we reach the initial stage back then we say that no
solution exists. If adding an item doesn’t violate constraints then we recursively add items one by one. If the solution
vector becomes complete then we print the solution.
Backtracking Algorithm for Knight’s tour
Else
a) Add one of the next moves to solution vector and recursively check if this move leads to a solution. (A Knight
can make maximum eight moves. We choose one of the 8 moves in this step).
b) If the move chosen in the above step doesn't lead to a solution then remove this move from the solution vector
and try other alternative moves.
c) If none of the alternatives work then return false (Returning false will remove the previously added item in
recursion and if false is returned by the initial call of recursion then "no solution exists" )
4. In a given maze, find out how many paths are there to get the cheese (program).
Solution:
In this post a different solution is discussed that can be used to solve the above Rat in a Maze
problem also.
The idea is to modify the given grid[][] so that grid[i][j] contains count of paths to reach (i, j)
from (0, 0) if (i, j) is not a blockage, else grid[i][j] remains -1.
We can recursively compute grid[i][j] using below
formula and finally return grid[R-1][C-1]
// Driver code
int main()
{
int maze[R][C] = {{0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
cout << countPaths(maze);
return 0;
}
Output:
4
Time Complexity : O(R x C)
5. Create a class of watch having two member functions and two data members.
/*C++ program to read time in HH:MM:SS format and convert into total
seconds.*/
#include <iostream>
#include <iomanip>
class Watch
{
private:
int seconds;
int hh,mm,ss;
public:
void getTime(void);
void convertIntoSeconds(void);
void displayTime(void);
};
void Time::getTime(void)
{
cout << "Enter time:" << endl;
cout << "Hours? "; cin >> hh;
cout << "Minutes? "; cin >> mm;
cout << "Seconds? "; cin >> ss;
}
void Time::convertIntoSeconds(void)
{
seconds = hh*3600 + mm*60 + ss;
}
void Time::displayTime(void)
{
cout << "The time is = " << setw(2) << setfill('0') << hh << ":"
<< setw(2) << setfill('0') << mm << ":"
<< setw(2) << setfill('0') << ss << endl;
cout << "Time in total seconds: " << seconds;
}
int main()
{
Watch W; //creating objects
W.getTime();
W.convertIntoSeconds();
W.displayTime();
return 0;
}
Output
Enter time:
Hours? 1
Minutes? 1
Seconds? 6
The time is = 01:01:06
Time in total seconds: 3666
Given two Binary Trees, write a function that returns true if two trees are mirror of each other,
else false. For example, the function should return true for following input trees.
For two trees ‘a’ and ‘b’ to be mirror images, the following three conditions must be true:
1. Their root node’s key must be same
2. Left subtree of root of ‘a’ and right subtree root of ‘b’ are mirror.
3. Right subtree of ‘a’ and left subtree of ‘b’ are mirror.
Below is implementation of above idea.
// C++ program to check if two trees are mirror
// of each other
#include<bits/stdc++.h>
using namespace std;
b->left = newNode(3);
b->right = newNode(2);
b->right->left = newNode(5);
b->right->right = newNode(4);
return 0;
}
Yes
Time Complexity : O(n)
Solution: An approach that uses O(1) time and O(n) extra space is discussed here.
In this article, a new approach is discussed that supports minimum with O(1) extra space. We define a
variable minEle that stores the current minimum element in the stack. Now the interesting part is, how to handle the
case when minimum element is removed. To handle this, we push “2x – minEle” into the stack instead of x so that
previous minimum element can be retrieved using current minEle and its value stored in stack. Below are detailed
steps and explanation of working.
Push(x) : Inserts x at the top of stack.
If stack is empty, insert x into the stack and make minEle equal to x.
If stack is not empty, compare x with minEle. Two cases arise:
If x is greater than or equal to minEle, simply insert x.
If x is less than minEle, insert (2*x – minEle) into the stack and make minEle equal to x. For
example, let previous minEle was 3. Now we want to insert 2. We update minEle as 2 and insert 2*2 – 3
= 1 into the stack.
Pop() : Removes an element from top of stack.
Remove element from top. Let the removed element be y. Two cases arise:
If y is greater than or equal to minEle, the minimum element in the stack is still minEle.
If y is less than minEle, the minimum element now becomes (2*minEle – y), so update (minEle =
2*minEle – y). This is where we retrieve previous minimum from current minimum and its value in
stack. For example, let the element to be removed be 1 and minEle be 2. We remove 1 and update
minEle as 2*2 – 1 = 3.
Important Points:
Stack doesn’t hold actual value of an element if it is minimum so far.
Actual minimum element is always stored in minEle
Illustration
Push(x)
8. How will you insert the elements in Binary trees and tell me about the functioning of Binary search tree
with the help of program.
Solution:
The idea is to do iterative level order traversal of the given tree using queue. If we find a node
whose left child is empty, we make new key as left child of the node. Else if we find a node
whose right child is empty, we make new key as right child. We keep traversing the tree until we
find a node whose either left or right is empty.
// C++ program to insert element in binary tree
#include <iostream>
#include <queue>
using namespace std;
inorder(temp->left);
cout << temp->key << " ";
inorder(temp->right);
}
if (!temp->left) {
temp->left = newNode(key);
break;
} else
q.push(temp->left);
if (!temp->right) {
temp->right = newNode(key);
break;
} else
q.push(temp->right);
}
}
// Driver code
int main()
{
struct Node* root = newNode(10);
root->left = newNode(11);
root->left->left = newNode(7);
root->right = newNode(9);
root->right->left = newNode(15);
root->right->right = newNode(8);
return 0;
}
Copy CodeRun on IDE
Output:
9. What is the difference between Binary Tree and Binary Search tree?
Ans: A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer,
and a data element. The "root" pointer points to the topmost node in the tree. The left and right
pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree
with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty
(represented by a null pointer), or is made of a single node, where the left and right pointers
(recursive definition ahead) each point to a binary tree.
A binary search tree (BST) or "ordered binary tree" is a type of binary tree where the nodes are
arranged in order: for each node, all elements in its left subtree are less to the node (<), and all the
elements in its right subtree are greater than the node (>).
5
/ \
3 6
/ \ \
1 4 9
The tree shown above is a binary search tree -- the "root" node is a 5, and its left subtree nodes (1, 3,
4) are < 5, and its right subtree nodes (6, 9) are > 5. Recursively, each of the subtrees must also
obey the binary search tree constraint: in the (1, 3, 4) subtree, the 3 is the root, the 1 < 3 and 4 > 3.
10. Given an integer and a tree, represented by an array, find out who is ancestor of the given integer value in
the tree.
Solution:
Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given
binary tree.
For example, if the given tree is following Binary Tree and key is 7, then your function should
print 4, 2 and 1.
1
/ \
2 3
/ \
4 5
/
7
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
return(node);
}
printAncestors(root, 7);
getchar();
return 0;
}
Output:
421
Time Complexity: O(n) where n is the number of nodes in the given Binary Tree.
11. A matrix is given, such that in every row and column numbers are in increasing order, Find an element in
complexity of O (n).
return 0;
}
12. In a 2-D Character matrix, mine sweeper game, (.) was representing empty Cells,(x) was representing
mines. Find the number of groups of mines?
Solution: This is an interactive problem. Interactive problems differ from classic problems in that your solution
will send and receive data from a special judge program instead of from static files. Pay special attention to the
notice on output buffering described in the "Input + Output" section below.
An N × N field contains many mines. Each mine occupies some cell of the field. Each cell could contain at most
one mine. There are M mines in all at the field. You need to neutralize all of the mines so it will be safe to pass
through. The mines are neutralized with dynamite. A single piece of dynamite can be used to neutralize a single
cell. You have only K pieces of dynamite. But don't worry, it is guaranteed that K ≥ M.
You may perform two operations:
Neutralize - neutralize the mine in the specified cell, if one exists. Otherwise has no effect. This
operation may be performed at most K times.
Survey - check a cell for a mine, and if it doesn't have a mine count the number of cells adjacent to it
containing mines. Previously neutralized mines are not counted. Each cell is adjacent to up to 8 other cells
(2 horizontally, 2 vertically, and 4 diagonally). This operation may be performed at most N2 times. But you
could survey the same cell twice if necessary and also it is allowed to survey the cell after neutralize
operation was applied to it.
Surveying is very dangerous, so you need to try to minimize the number of survey operations you perform.
Submissions that use fewer survey operations will score more points.
Input + Output
Input begins with the line containing 3 space separated integers N, M, and K, the size of the field, the number
of mines, and the number of pieces of dynamite, respectively. The locations of mines are predetermined but
currently unknown to you.
To perform a neutralize operation, print a line containing "N x y" (without quotes), where x and y are the
coordinates of the cell you wish to neutralize (0 ≤ x, y < N).
To perform a survey operation, print "S x y" (without quotes), where x and y are the coordinates of the cell you
wish to check (0 ≤ x, y < N). Then read a line containing a single character. This character will be 'M' if the cell
contains a mine, otherwise it will be an integer between 0 and 8, indicating the number of cells adjacent to the
specified cell that contain mines.
When you are finished, print "Done" (without quotes).
Note that you will receive Wrong Answer verdict if one of the following happens:
You will perform more than N2 survey operations.
You will perform more than K neutralize operations.
You will output operation in wrong format.
In particular, x and y should be between 0 and N − 1, inclusive.
You will output "Done" but not all mines are neutralized.
Attention: the program should clear the output buffer after printing each line. It can be done using
fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution -
setlinebuf(stdout). Failure to flush the output buffer will result in Time Limit Exceeded verdict.
For example, at C/C++ you could use the following routines:
char Survey(int x, int y) {
printf("S %d %d\n", x, y);
fflush(stdout);
char res;
scanf(" %c", &res);
return res;
}
Scoring
Suppose you successfully neutralized all mines using S survey operations.
Then your score is 10 * (S + 1) / N2. Lower scores will earn more points.
13. In Binary Search Tree, Print Right View of the tree O(n).
Solution: Given a Binary Tree, print Right view of it. Right view of a Binary Tree is set of nodes visible
when tree is visited from Right side.
Right view of following tree is 1 3 7 8
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
The Right view contains all nodes that are last nodes in their levels. A simple solution is to do level order
traversal and print the last node in every level.
The problem can also be solved using simple recursive traversal. We can keep track of level of a node by
passing a parameter to all recursive calls. The idea is to keep track of maximum level also. And traverse the
tree in a manner that right subtree is visited before left subtree. Whenever we see a node whose level is
more than maximum level so far, we print the node because this is the last node in its level (Note that we
traverse the right subtree before left subtree). Following is C implementation of this approach.
struct Node
{
int data;
struct Node *left, *right;
};
rightView(root);
return 0;
}
Output:
1 3 7 8
14. Suppose an Array is given as 1 3 5 7 8.Print a pyramid such that above elements becomes the base and
every element above it is sum of elements below it.
Ans:
15. How websites are blocked by Government?
Ans: Governments definitely can block your websites.Just look at examples such as Russia, China
or UAE. China, for example, has adopted a practice of blocking IPs of websites that don’t agree
with the ideology of China’s politics. Another example is Dubai where websites including adult
content, gambling or betting, anything anti-Islam, dating or drugs are blocked.
Website blocks are worked around with VPNs. But of course most governments, like China and
UAE block VPNs too. So the only way to work around this issues is to find a VPN service which
can provide you with servers that are not yet blocked by your country.
16. Find the distance between two nodes in Binary Search Tree.
17.
Ans: Given a Binary Search Tree and two keys in it. Find the distance between two nodes with given two
keys. It may be assumed that both keys exist in BST.
In case of BST, we can find distance faster. We start from root and for every node, we do
following.
1. If both keys are greater than current node, we move to right child of current node.
2. If both keys are smaller than current node, we move to left child of current node.
3. If one keys is smaller and other key is greater, current node is Lowest Common Ancestor
(LCA) of two nodes. We find distances of current node from two keys and return sum of the
distances.
// CPP program to find distance between
// two nodes in BST
#include <bits/stdc++.h>
using namespace std;
struct Node {
struct Node* left, *right;
int key;
};
// Driver code
int main()
{
struct Node* root = NULL;
root = insert(root, 20);
insert(root, 10);
insert(root, 5);
insert(root, 15);
insert(root, 30);
insert(root, 25);
insert(root, 35);
int a = 5, b = 55;
cout << findDistWrapper(root, 5, 35);
return 0;
}
Output:
2
Time Complexity : O(h) where h is height of Binary Search Tree.
19. The players are ranked from 1 to 2 ^n .Condition is player 1 can beat all players ranked below him, similarly
player 2 can beat all ranked above him, So who will win the tournament and how many matches are to be played
in order to player two winning the tournament if it is knock out tournament?
Ans: Aptitude Question
20. What is the Thread in Operating System?
Ans: A process, in the simplest terms, is an executing program. One or more threads run in the
context of the process. A thread is the basic unit to which the operating system allocates processor
time. A thread can execute any part of the process code, including parts currently being executed by
another thread.
Drive Name: ZS ASSOCIATES
Book Index: 213 (C)
TECHNICAL INTERVIEW
1) Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked
exception, then the method must either handle the exception or it must specify the exception using throws keyword.
For example, consider the following Java program that opens file at location “C:\test\a.txt” and prints the first three
lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a
checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also
throw checked exception IOException
import java.io.*;
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
fileInput.close();
}
}
Output:
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
fileInput.close();
}
}
Output: First three lines of file “C:\test\a.txt”
2) Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is
not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and
specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under
throwable is checked.
Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler
allows it to compile, because ArithmeticException is an unchecked exception.
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
Output:
2. Have you ever panicked in a tough situation? How did you handle it?
Answer:
Not a Technical Question.
Deadlock is a situation where a set of processes are blocked because each process is holding a resource and waiting
for another resource acquired by some other process.
Consider an example when two trains are coming toward each other on same track and there is only one track, none
of the trains can move once they are in front of each other. Similar situation occurs in operating systems when there
are two or more processes hold some resources and wait for resources held by other(s). For example, in the below
diagram, Process 1 is holding Resource 1 and waiting for resource 2 which is acquired by process 2, and process 2 is
waiting for resource 1.
4. If There is a bridge to be built in an island, but it’s faulty. How will you convince the people of the island
not to build it?
Answer:
Not a Technical Question.
A Database model defines the logical design and structure of a database and defines how data will be stored,
accessed and updated in a database management system. While the Relational Model is the most widely used
database model, there are other models too:
Hierarchical Model
Network Model
Entity-relationship Model
Relational Model
Hierarchical Model
This database model organises data into a tree-like-structure, with a single root, to which all the other data is linked.
The hierarchy starts from the Root data, and expands like a tree, adding child nodes to the parent nodes.
In this model, a child node will only have a single parent node.
This model efficiently describes many real-world relationships like index of a book, recipes etc.
In hierarchical model, data is organised into tree-like structure with one one-to-many relationship between two
different types of data, for example, one department can have many courses, many professors and of-course many
students.
Network Model
This is an extension of the Hierarchical model. In this model data is organised more like a graph, and are allowed to
have more than one parent node.
In this database model data is more related as more relationships are established in this database model. Also, as the
data is more related, hence accessing the data is also easier and fast. This database model was used to map many-to-
many data relationships.
This was the most widely used database model, before Relational Model was introduced.
Entity-relationship Model
In this database model, relationships are created by dividing object of interest into entity and its characteristics into
attributes.
Different entities are related using relationships.
E-R Models are defined to represent the relationships into pictorial form to make it easier for different stakeholders
to understand.
This model is good to design a database, which can then be turned into tables in relational model(explained below).
Let's take an example, If we have to design a School Database, then Student will be an entity with attributes name,
age, address etc. As Address is generally complex, it can be another entity with attributes street name, pincode, city
etc, and there will be a relationship between them.
Relationships can also be of different types. To learn about E-R Diagrams in details, click on the link.
Relational Model
In this model, data is organised in two-dimensional tables and the relationship is maintained by storing a common
field.
This model was introduced by E.F Codd in 1970, and since then it has been the most widely used database model,
infact, we can say the only database model used around the world.
The basic structure of data in the relational model is tables. All the information related to a particular type is stored in
rows of that table.
Hence, tables are also known as relations in relational model.
In the coming tutorials we will learn how to design tables, normalize them to reduce data redundancy and how to use
Structured Query language to access data from tables.
Drive Name: SOFT PRODIGY
Book Index: 211-(D)
Technical interview
1. What are access specifications?
Ans: Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility
of classes, methods, and other members. Access modifiers are a specific part of programming language syntax
used to facilitate the encapsulation of components.1
So an Access Specifier aka Access Modifier takes certain class, method, or variable and decides what other
classes are allowed to use them. The most common Access Specifiers are Public, Protected, and Private. What
these mean can vary depending on what language you are in, but I'm going to use C++ as an example since that's
what the article uses.
1) Final is used to apply restrictions on class, Finally is used to place important Finalize is used to perform clean up
method and variable. Final class can't be code, it will be executed whether processing just before object is garbage
inherited, final method can't be overridden exception is handled or not. collected.
and final variable value can't be changed.
Syntax:
a = ++x;
Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets modified before using it in
the expression.
// CPP program to demonstrate pre increment
// operator.
#include <iostream>
using namespace std;
int main()
{
int x = 10, a;
a = ++x;
cout << "Pre Increment Operation";
return 0;
}
Output :
Pre Increment Operation
a = 11
x = 11
Post-increment operator: A post-increment operator is used to increment the value of variable after executing
expression completely in which post increment is used. In the Post-Increment, value is first used in a expression
and then incremented.
Syntax:
a = x++;
Here, suppose the value of ‘x’ is 10 then value of variable ‘b’ will be 10 because old value of ‘x’ is
used.
// CPP program to demonstrate pre increment
// operator.
#include <iostream>
using namespace std;
int main()
{
int x = 10, a;
a = x++;
return 0;
}
Output :
Post Increment Operation
a = 10
x = 11
For example, you want to simulate ejection, or dismissal. Since only players and coaches can be ejected from the
field you cannot make it a method of the parent class that represent people. So you create an interface Ejectable
with a method Ejection() and make Player and Coach implement it.
Example of an Interface
interface Ejectable
{
Ejection()
}
interface Ejectable
{
Ejection()
}
There is not a standard way of describing the relationship that an interface establish, but you can thought it as
behave-as. In our example a Player behave-as Ejectable.
6. Tell me something about your project. What was your role in the project?
Ans: Depends on Student Answer
7. How you handled any conflicts, which occurred while working in the project?
Ans: Depends on Student Answer
Drive Name: MAVEN WAVE INDIA PVT. LTD.
Book Index: 215 (D)
TECHNICAL INTERVIEW
1. What is polymorphism?
Answer:
The word polymorphism is used in various contexts and describes situations in which something
occurs in several different forms. In computer science, it describes the concept that objects of different
types can be accessed through the same interface. Each type can provide its own, independent
implementation of this interface. It is one of the core concepts of object-oriented programming (OOP).
Java supports 2 types of polymorphism:
2. What is inheritance?
Answer:
In object-oriented programming, inheritance is the mechanism of basing an object or class upon
another object or class, retaining similar implementation. In most class-based object-oriented languages, an
object created through inheritance acquires all the properties and behaviors of the parent object.
OOP stands for Object-oriented programming and is a programming approach that focuses on data rather
than the algorithm, whereas POP, short for Procedure-oriented programming, focuses on procedural
abstractions.
Programs
In OOP, the program is divided into small chunks called objects which are instances of classes, whereas in
POP, the main program is divided into small parts based on the functions.
Accessing Mode
Three accessing modes are used in OOP to access attributes or functions – ‘Private’, ‘Public’, and
‘Protected’. In POP, on the other hand, no such accessing mode is required to access attributes or functions
of a particular program.
1. Focus
The main focus is on the data associated with the program in case of OOP while POP relies on functions or
algorithms of the program.
1. Execution
In OOP, various functions can work simultaneously while POP follows a systematic step-by-step approach
to execute methods and functions.
1. Data Control
In OOP, the data and functions of an object act like a single entity so accessibility is limited to the member
functions of the same class. In POP, on the other hand, data can move freely because each function
contains different data.
1. Security
OOP is more secure than POP, thanks to the data hiding feature which limits the access of data to the
member function of the same class, while there is no such way of data hiding in POP, thus making it less
secure.
1. Ease of Modification
New data objects can be created easily from existing objects making object-oriented programs easy to
modify, while there’s no simple process to add data in POP, at least not without revising the whole
program.
1. Process
OOP follows a bottom-up approach for designing a program, while POP takes a top-down approach to
design a program.e.gCommonly used OOP languages are C++, Java, VB.NET, etc. Pascal and Fortran are
used by POP.
6. What is Java?
Java is a programming language that produces software for multiple platforms. When a programmer writes
a Java application, the compiled code (known as bytecode) runs on most operating systems (OS), including
Windows, Linux and Mac OS. Java derives much of its syntax from the C and C++ programming
languages.
Java was developed in the mid-1990s by James A. Gosling, a former computer scientist with Sun
Microsystems.
7. What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987
SELECT Syntax
Select col1,col2……… from tablename;
The first way specifies both the column names and the values to be inserted:
If you are adding values for all the columns of the table, you do not need to specify the column names in
the SQL query. However, make sure the order of the values is in the same order as the columns in the table.
The INSERT INTO syntax would be as follows:
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Drive Name: Just Dial
Book Index: 281(D)
Technical
// The main function that prints the arrangement with the largest value.
// The function accepts a vector of strings
void printLargest(vector<string> arr)
{
// Sort the numbers using library sort funtion. The function uses
// our comparison function myCompare() to compare two strings.
// See http://www.cplusplus.com/reference/algorithm/sort/ for details
sort(arr.begin(), arr.end(), myCompare);
return 0;
}
2. Write a program to find the sum of contiguous sub array within one-
dimensional array of numbers, which has the largest sum.
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
int main()
{
int i, j, rows;
C C++
C was developed by
Dennis Ritchie between C++ was developed by Bjarne Stroustrup in 1979 with C++'s predecessor "C
1969 and 1973 at AT&T with Classes".
Bell Labs.
When compared to C++, C C++ is a superset of C. C++ can run most of C code while C cannot run C++
is a subset of C++. code.
C supports procedural
C++ supports both procedural and object oriented programming paradigms;
programming paradigm
therefore C++ is also called a hybrid language.
for code development.
In C (because it is a In C++ (when it is used as object oriented programming language), data and
procedural programming functions are encapsulated together in form of an object. For creating
language), data and objects class provides a blueprint of structure of the object.
functions are separate and
free entities.
C, being a procedural
While, C++, being an object oriented programming, it is an object driven
programming, it is a
language.
function driven language.
C provides malloc() C++ provides new operator for memory allocation and delete operator
and calloc() functions for memory de-allocation.
for dynamic memory
allocation, and free()
for memory de-allocation.
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in
wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole
pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
int x = 5;
int y = 6;
int *p;
p = &x;
p = &y;
On the other hand, a reference cannot be re-assigned, and must be assigned at initialization.
int x = 5;
int y = 6;
int &r = x;
struct parent {
int parent_i;
char parent_c;
};
struct descendant {
struct parent parent_data;
int descendant_d;
};
#define descendant_i parent_data.parent_i
#define descendant_c parent_data.parent_c
13. Given a table in HTML, write a code to divide a cell of the table in two parts.
Answer: <TABLE BORDER>
<TR>
<TD>Item 1</TD>
<TD>Item 1</TD>
<TD COLSPAN=2>Item 2</TD>
</TR>
<TR>
<TD>Item 3</TD>
<TD>Item 3</TD>
<TD>Item 4</TD>
<TD>Item 5</TD>
</TR>
</TABLE>
14. How to implement and display the data using join query when data is given to you about different
employees and managers?
Answer: SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULLOUTERJOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
// Disconnect is optional
// autodisconnect will occur in destructor if needed
con.Disconnect();
printf("We are disconnected!\n");
}
catch(SAException & x)
{
// SAConnection::Rollback()
// can also throw an exception
// (if a network error for example),
// we will be ready
try
{
// on error rollback changes
con.Rollback ();
}
catch(SAException &)
{
}
// print error message
printf("%s\n", (const char*)x.ErrText());
}
return 0;
}
16. Explain your project in detail.
Ans:
17. int n=4, n=n>>2, if given is the code, What will be the output
Ans: output will be 1
// Driver code
int main() {
int a = 10, b = 3;
cout << divide(a, b) <<"\n";
a = 43, b = -8;
cout << divide(a, b);
return 0;
}
23. Write a program where the comparison between c++ and python can be drawn.
Ans:C++
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main() {
int a = 10, b = 3;
cout << divide(a, b) <<"\n";
a = 43, b = -8;
cout << divide(a, b);
return 0;
}
Python:
def divide(dividend, divisor):
# Driver code
a = 10
b=3
print(divide(a, b))
a = 43
b = -8
print(divide(a, b))
26. How can we print anything in java other than using SOPL?
Ans:import java.io.*;
Technical interview
if (currindex == n)
{
s.insert(sum);
return;
}
// Driver code
int main()
{
int arr[] = {2, 3, 4, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
printDistSum(arr, n);
return 0;
}
int main()
{
int n, first = 0, second = 1, next, c;
return 0;
}
struct LinkedList
{
Node *head;
LinkedList()
{
head = NULL;
}
ll.reverse();
What is recursion?
Ans: Recursion is a method of solving problems that involves breaking a problem down into smaller and smaller
subproblems until you get to a small enough problem that it can be solved trivially. Usually recursion involves a
function calling itself. While it may not seem like much on the surface, recursion allows us to write elegant solutions
to problems that may otherwise be very difficult to program.
Write a program to find repeated element in array.
Solution:
// C++ program to find the only repeating element in an
// array of size n and elements from range 1 to n-1.
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main()
{
int arr[] = {1, 2, 3, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int index = findRepeatingElement(arr, 0, n-1);
if (index != -1)
cout << arr[index];
return 0;
}
Write program for a tic-tok game.
Solution:
// A C++ Program to play tic-tac-toe
#include<bits/stdc++.h>
using namespace std;
#define COMPUTER 1
#define HUMAN 2
return;
}
printf("\t\t\t 1 | 2 | 3 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 4 | 5 | 6 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 7 | 8 | 9 \n\n");
printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n");
return;
}
// A function to initialise the game
void initialise(char board[][SIDE], int moves[])
{
// Initiate the random number generator so that
// the same configuration doesn't arises
srand(time(NULL));
return;
}
return(false);
}
int moves[SIDE*SIDE];
int moveIndex = 0, x, y;
// Keep playing till the game is over or it is a draw
while (gameOver(board) == false &&
moveIndex != SIDE*SIDE)
{
if (whoseTurn == COMPUTER)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = COMPUTERMOVE;
printf("COMPUTER has put a %c in cell %d\n",
COMPUTERMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = HUMAN;
}
// Driver program
int main()
{
// Let us play the game with COMPUTER starting first
playTicTacToe(COMPUTER);
return (0);
}
1. What is Multiplexing?
Ans: Multiplexing is a technique by which different analog and digital streams of transmission can be simultaneously
processed over a shared link. Multiplexing divides the high capacity medium into low capacity logical medium
which is then shared by different streams.
2. What is GSM,
Ans: GSM stands for Global System for Mobile Communication. It is a digital cellular technology used for
transmitting mobile voice and data services. GSM makes use of narrowband Time Division Multiple Access
(TDMA) technique for transmitting signals. GSM digitizes and compresses data, then sends it down through a
channel with two other streams of user data, each in its own timeslot.
2. What are Handover techniques?
Ans: Handover in mobile communication refers to the process of transferring a call from one network cell to another
without breaking the call.
There are two types of handover which are as follows :
Hard Handoff : hard handoff is the process in which the cell connection is disconnected from the previous cell before
it is made with the new one.
Soft Handoff : It is the process in which a new connection is established first before disconnecting the old one. It is
thus more efficient and smart.
4. What is TDMA?
Ans: Time-division multiple access (TDMA) is a channel access method for shared-medium networks. It allows
several users to share the same frequency channel by dividing the signal into different time slots. The users transmit
in rapid succession, one after the other, each using its own time slot.
5. What is FDMA?
Ans: In FDMA, The frequency band is divided into channels of equal bandwidth so that each conversation is carried
on a different frequency
6. What is half duplex and full duplex communication?
Ans: Half Duplex: In half duplex mode, data can be transmitted in both directions on a signal carrier except not at
the same time. At a certain point, it is actually a simplex channel whose transmission direction can be switched.
Walkie-talkie is a typical half duplex device.
Full Duplex: A full duplex communication channel is able to transmit data in both directions on a signal carrier at the
same time. Take telephone as an example, people at both ends of a call can speak and be heard by each other at the
same time because there are two communication paths between them. Thus, using the full duplex mode can greatly
increase the efficiency of communication.
8. What is a deadlock?
Ans: In a database, a deadlock is an unwanted situation in which two or more transactions are waiting indefinitely for
one another to give up locks. Deadlock is said to be one of the most feared complications in DBMS as it brings the
whole system to a Halt.
DBMS RDBMS
DBMS applications store data as file. RDBMS applications store data in a tabular form.
In DBMS, data is generally stored in either a In RDBMS, the tables have an identifier called
hierarchical form or a navigational form. primary key and the data values are stored in the
form of tables.
Normalization is not present in DBMS. Normalization is present in RDBMS.
DBMS does not apply any security with regards to RDBMS defines the integrity constraint for the
data manipulation. purpose of ACID (Atomocity, Consistency,
Isolation and Durability) property
3.Priority scheduling
In this scheduling algorithm the priority is assigned to all the processes and the process with highest priority
executed first. Priority assignment of processes is done on the basis of internal factor such as CPU and memory
requirements or external factor such as user’s choice. The priority scheduling algorithm supports preemptive and non
- preemptive scheduling policy.
6. What is Bootstrap?
Bootstrap is a free and open-source front-end framework for designing websites and web applications. It
contains HTML- and CSS-based design templates for typography, forms, buttons, navigation and other
interface components, as well as optional JavaScript extensions.
Normalization is the process of reorganizing data in a database so that it meets two basic requirements: (1) There is
no redundancy of data (all data is stored in only one place), and (2) data dependencies are logical (all related data
items are stored together). Normalization is important for many reasons, but chiefly because it allows databases to
take up as little disk space as possible, resulting in increased performance. Normalization is also known as data
normalization.
9. About .NET and Its Input Output Operations?
Output functions:
Write()
writeLine(): create new line automatically
Input Functions:
read()
readLine():Reads the whole linea
Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through the use
of servlets, small programs that are specified in the Web page and run on the Web server to modify the Web page
before it is sent to the user who requested it. Sun Microsystems, the developer of Java, also refers to the JSP
technology as the Servlet application program interface (API). JSP is comparable to Microsoft's Active Server Page
(ASP) technology. Whereas a Java Server Page calls a Java program that is executed by the Web server, an Active
Server Page contains a script that is interpreted by a script interpreter (such as VBScript or JScript) before the page is
sent to the user.
IIS, or more specifically its Active Server Page (ASP) environment, contains a core group of classes that
virtually mirror those of the Java Servlet specification. ... You have to adapt (or wrap) the IIS versions of the
objects to make them look and act like servlet versions.
A servlet is a Java programming language class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response programming model. Although servletscan respond to
any type of request, they are commonly used to extend the applications hosted by web servers.
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
An access specifier is a defining code element that can determine which elements of a program are allowed to access
a specific variable or other piece of data. Different programming languages have their own protocols for access
specifiers, as well as defaults for some code elements including both individual variables and classes.they are of 3
types:
14. What is the query of inner Joins ,Outer Join, Constant, Unique Key, Primary key, Inheritance ,Programs
Related to Linked List , In capsulation , Abstraction (there real Life Examples )
INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as the condition
satisfies. This keyword will create the result-set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be same.
Syntax
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
ON table1.matching_column = table2.matching_column;
This query will show the names and age of students enrolled in different courses.
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
OUTER JOIN
when performing an inner join, rows from either table that are unmatched in the other table are not returned. In an
outer join, unmatched rows in one or both tables can be returned. There are a few types of outer joins:
LEFT JOIN returns only unmatched rows from the left table.
RIGHT JOIN returns only unmatched rows from the right table.
FULL OUTER JOIN returns unmatched rows from both tables.
UNIQUE KEY
All tables in your databse should have a PK (although this is not enforced by most dbms), and PK can span
multiple columns. Unique key constraints are used to ensure that data is not duplicated in two rows in the
database. One row in the database is allowed to have null for the value of the unique key constraint
PRIMARY KEY
A primary key is a special relational database table column (or combination of columns) designated to
uniquely identify all table records. A primary key'smain features are: It must contain a unique value for each
row of data. It cannot contain null values.
SQLite is an embedded SQL database engine. Unlike most other SQL databases, SQLite does not have a separate
server process. SQLite reads and writes directly to ordinary disk files. A complete SQL database with multiple
tables, indices, triggers, and views, is contained in a single disk file. The database file format is cross-platform - you
can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.
These features make SQLite a popular choice as an Application File Format. SQLite database files are
a recommended storage format by the US Library of Congress. Think of SQLite not as a replacement for Oracle but
as a replacement for fopen()
SQLite is a compact library. With all features enabled, the library size can be less than 600KiB, depending on the
target platform and compiler optimization settings. (64-bit code is larger. And some compiler optimizations such as
aggressive function inlining and loop unrolling can cause the object code to be much larger.) There is a tradeoff
between memory usage and speed. SQLite generally runs faster the more memory you give it. Nevertheless,
performance is usually quite good even in low-memory environments. Depending on how it is used, SQLite can
be faster than direct filesystem I/O.
SQLite is very carefully tested prior to every release and has a reputation for being very reliable. Most of the SQLite
source code is devoted purely to testing and verification. An automated test suite runs millions and millions of test
cases involving hundreds of millions of individual SQL statements and achieves 100% branch test coverage. SQLite
responds gracefully to memory allocation failures and disk I/O errors. Transactions are ACID even if interrupted by
system crashes or power failures. All of this is verified by the automated tests using special test harnesses which
simulate system failures. Of course, even with all this testing, there are still bugs. But unlike some similar projects
(especially commercial competitors) SQLite is open and honest about all bugs and provides bugs lists and minute-
by-minute chronologies of code changes.
The SQLite code base is supported by an international team of developers who work on SQLite full-time. The
developers continue to expand the capabilities of SQLite and enhance its reliability and performance while
maintaining backwards compatibility with the published interface spec, SQL syntax, and database file format. The
source code is absolutely free to anybody who wants it, but professional support is also available.
Student is “TableName”
Name is the “ColumnName representing names of the student’
Rollno is the “ColumnName”
17. What are the real life examples of Stack and Queue?
DML statements are SQL statements that manipulate data. DML stands for Data Manipulation Language. The SQL
statements that are in the DML class are INSERT, UPDATE and DELETE. Some people also lump the SELECT
statement in the DML classification.
Data Definition Languages (DDL) are used to define the database structure. Any CREATE, DROP and ALTER
commands are examples of DDL SQL statements
Sqlite is embeddable relational database management system. SQL is query language. ... Unlike other
databases (like SQL Server and MySQL) SQLite does not support stored procedures. SQLite is file-based,
unlike other databases, like SQL Server and MySQL which are server-based.
20. Where SQL is used? Give Real Life examples?
Data is stored in databases which in turn stores the data in tables that contains rows and columns. There are
several database applications available to handle the storage and management of data examples include Oracle,
Microsoft SQL and MySQL. ... Adding new record into a database. Deleting records from a database.e.g
Hospital records of patients and doctors.
Null Safety - As already mentioned in above section that Kotlin avoids NullPointerException. Kotlin fails at
compile-time whenever a NullPointerException may be thrown.
Data Classes - In Kotlin there are Data Classes which leads to autogeneration of boilerplate like equals,
hashCode, toString, getters/setters and much more.
Extension Functions - Kotlin allows us to extend the functionality of existing classes without inheriting from
them. Means to say that Kotlin provides the ability to extend a class with new functionality without having to
inherit from the class. This is done by extension functions. To declare an extension function, we need to
prefix its name with a receiver type, i.e. the type being extended.
For the language released in 2003 by McCabe and Clark, see Go! (programming language).
"Google Go" redirects here. For the computer program by Google to play the board game Go, see AlphaGo.
Go (often referred to as Golang[12]) is a programming language designed by Google[13] engineers Robert
Griesemer, Rob Pike, and Ken Thompson.[10] Go is a statically typed, compiled language in the tradition of C, with
the added benefits of memory safety, garbage collection, structural typing,[3] and CSP-style concurrency.
[14]
The compiler, tools, and source code are all free and open source.[15]
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;
Objects:
Objects are the basic run-time entities in an object-oriented programming. They may represents a person, a place, a
bank account, a table of data or any item that the program has to handle. They may also represents user-defined data
such as vector, time and lists. When the program is executed, the object interact by sending message to one another.
Classes:
Objects contain data, and code to manipulate that data. The entire set of data and code of an object can be made a
user-defined data type with the help of class. In fact, objects are variable of the type class. Once a class has been
defined, we can create a number of objects belonging to that class. A class is a collection of objects of similar type.
Data Abstraction:
Abstractions refer to the act of representing essential features without including background details or explanation.
They are commonly known as Abstraction Data Type(ADT).
Encapsulation:
The wrapping up of data and functions into single unit is known as encapsulation. Data encapsulation is a striking
feature of a class. The data is not accessible to the outside world, and only those functions which are wrapped in the
class can access it. These functions provide the interface between the object's data and the program.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of object of another class. The class
whose members are inherited is called the Base class and the class that inherits those members is called Derived
class. It supports class of hierarchical classification.
The concept of inheritance provides the ideas of reusability. This means we can add essential features to an exciting
class without modifying it.
Polymorphism:
Polymorphism is another OOP concept. Polymorphism means the ability to take more than one form. An operation
may exhibit different behaviors at different instances.
27. What is Project Architecture? What kind of Database you have used? Write its Database.
Ans: Ans: Project Architecure means what are the tiers in our project with flow diagram.
supposoe our project contains five tiers like client tier ,presentation tier, Business tier,Integration tier,Data tier. then
we draw the all tiers flow. Project approch is different from project architecure.
Client tier:
IE Browser (default) from which the end user will access the application
The request from the browser will be submitted to the Application Server using HTTP protocol.
The Response from the presentation layer (struts framework) will be interpreted into html pages to view on the
browsers.
Presentation Tier:
Struts Framework with Tiles
On Request from the browser, the appropriate Action Class handles the user request. The Action class then connects
to the business tier via Service Business Delegate.
Tiles have been used to create a set of pages with a consistent user interface (e.g.: the same navigation bar, header,
footer, etc.).
Taglibs are used for displaying tabular data (e.g. search results) in a consistent fashion, with pagination.
Business Tier
The Business Delegate identifies the business service class (the Session EJBs) and delegates client request to the
EJBs. Internally, the session beans are shallow, and delegate all business logic requests to business logic POJOs,
which in turn implement the actual functionality.
The Business Logic POJOs encapsulate the server side business logic. They do not use Hibernate directly, but
instead call upon Data Access Objects (DAO) to work with the model. Parameters and return values are modeled as
Data Transfer Objects (DTO), and hence no Hibernate model classes will ever leave the DAO layer. The business
logic is made available in the business service class, which increases maintainability and easy debugging, if
necessary.
DB Tier
The DAOs encapsulates the database access. For all practical purposes, we are using Hibernate (v 2.1) as the OR
mapping layer. This saves development time to write SQLs for executing insert and update statements, find by
primary key etc. For each value object that directly or compositely represent a table in the database, we have
Hibernate mapping files.
For some complex data retrieval, however we will be using raw SQLs (independent of database) from the DAOs and
populate the Value Object POJOs. In those specific cases, the DAOs will be having direct access to the Databases
using the available connection. The connection properties of the ?DB Manager?, holding the data sources, direct the
request to the appropriate database.
28. What is Cloud Computing? What are its platforms? What are its advantages? What are its
disadvantages? Why it was started? What are its Modules?
Ans: Cloud computing is the the use of various services, such as software development platforms, servers, storage
and software, over the internet, often referred to as the "cloud."
In general, there are three cloud computing characteristics that are common among all cloud-computing vendors:
4. The back-end of the application (especially hardware) is completely managed by a cloud vendor.
5. A user only pays for services used (memory, processing time and bandwidth, etc.).
6. Services are scalable
Many cloud computing advancements are closely related to virtualization. The ability to pay on demand and scale
quickly is largely a result of cloud computing vendors being able to pool resources that may be divided among
multiple clients.
It is common to categorize cloud computing services as infrastructure as a service (IaaS), platform as a service
(PaaS) or software as a service (SaaS).
Cost efficiency – The biggest reason behind shifting to cloud computing is that it takes considerably lesser
cost than an on-premise technology. Now the companies need not store the data in disks anymore as the Cloud
offers enormous space available saving money and resources of the companies.
High Speed – Cloud computing lets you deploy the service quickly in fewer clicks. This quick deployment
lets you get the resources required for your system within fewer minutes.
Excellent accessibility – Storing the information in cloud allows you to access it anywhere, anytime
regardless of the machine making it highly accessible and flexible technology of present times.
Back-up and restore data – Once the data is stored in Cloud, it is easier to get the back-up and recovery of
that, which is quite a time taking process on-premise.
Security issues – At time storing data in cloud may pose serious challenge of information theft in front of
the company. Though advanced security measures are deployed on cloud, still storing a confidential data in cloud
can be a risky affair.
Low bandwidth – At times the bandwidth is low as many users are accessing cloud at the same time which
causes its bandwidth to go down. With less speed the benefits of cloud computing cannot be realized.
Flexibility issues – The cloud services run on remote servers which make it hard for the companies to have
control over software and hardware. The services at times do not run the way it should.
Incompatibility – Since entire infrastructure gets virtualized, incompatibility issues may arise at times that
may pose serious challenges on the way of smooth running of services.
30. If there is a String A, B, C, D, E .Without affecting its elements, how will you reverse it?
Ans: Simple Solution:
1) Create a temporary character array say temp[].
2) Copy alphabetic characters from given array to temp[].
3) Reverse temp[] using standard string reversal algorithm.
4) Now traverse input string and temp in a single loop. Wherever there is alphabetic character is input string,
replace it with current character of temp[].
Efficient Solution:
Time complexity of above solution is O(n), but it requires extra space and it does two traversals of input string.
We can reverse with one traversal and without extra space. Below is algorithm.
Ans: The max() function of PHP is used to find the numerically maximum value in an array or the numerically
maximum value of several specified values. The max() function can take an array or several numbers as an argument
and return the numerically maximum value among the passed parameters. The return type is not fixed, it can be an
integer value or a float value based on input.
Syntax:
max(array_values)
or
Parameters: This function accepts two different types of arguments which are explained below:
3. array_values : It specifies an array containing the values.
4. value1, value2, … : It specifies two or more than two values to be compared.
Return Value: The max() function returns the numerically maximum value.
Drive Name: Brilio Technologies
Book Index: 233 (D)
Technical Interview
1. Define DBMS.
Ans: A database management system (DBMS) is system software for creating and managing databases. The DBMS
provides users and programmers with a systematic way to create, retrieve, update and manage data.
A DBMS makes it possible for end users to create, read, update and delete data in a database. The DBMS essentially
serves as an interface between the database and end users or application programs, ensuring that data is consistently
organized and remains easily accessible.
2. What is SQL?
Ans: SQL stands for Structured Query Language. SQL lets you access and manipulate databases. SQL became a
standard of the American National Standards Institute (ANSI) in 1986, and of the International Organization for
Standardization (ISO) in 1987. SQL can execute queries against a database. SQL can retrieve data from a
database. SQL can insert records in a database. SQL can update records in a database. SQL can delete records
from a database. SQL can create new databases. SQL can create new tables in a database, SQL can create stored
procedures in a database. SQL can create views in a database. SQL can set permissions on tables, procedures,
and views
Ans: There are many basic data structures that can be used to solve application problems. Array is a good static data
structure that can be accessed randomly and is fairly easy to implement. Linked Lists on the other hand is dynamic
and is ideal for application that requires frequent operations such as add, delete, and update. One drawback of linked
list is that data access is sequential. Then there are other specialized data structures like, stacks and queues that
allows us to solve complicated problems (eg: Maze traversal) using these restricted data structures. One other data
structure is the hash table that allows users to program applications that require frequent search and updates. They
can be done in O(1) in a hash table.
One of the disadvantages of using an array or linked list to store data is the time necessary to search for an item.
Since both the arrays and Linked Lists are linear structures the time required to search a “linear” list is proportional
to the size of the data set. For example, if the size of the data set is n, then the number of comparisons needed to find
(or not find) an item may be as bad as some multiple of n. So imagine doing the search on a linked list (or array) with
n = 106 nodes. Even on a machine that can do million comparisons per second, searching for m items will take
roughly m seconds. This not acceptable in today’s world where speed at which we complete operations is extremely
important. Time is money. Therefore it seems that better (more efficient) data structures are needed to store and
search data.
Ans: There are many differences between method overloading and method overriding in java. A list of differences between
method overloading and method overriding are given below:
Basically, an array is a set of similar data objects stored in sequential memory locations under a common heading or
a variable name.
While a linked list is a data structure which contains a sequence of the elements where each element is linked to its
next element. There are two fields in an element of linked list. One is Data field, and other is link field, Data field
contains the actual value to be stored and processed. Furthermore, the link field holds the address of the next data
item in the linked list. The address used to access a particular node is known as a pointer.
Another significant difference between an array and linked list is that Array has a fixed size and required to be
declared prior, but Linked List is not restricted to size and expand and contract during execution.
LAN WAN
Stands For Local Area Network Wide Area Network
Covers Local areas only (e.g., homes, offices, Large geographic areas (e.g.,
schools) cities, states, nations)
Data transfer LANs have a high data transfer rate. WANs have a lower data
rates transfer rate compared to
LANs.
LAN WAN
Fault LANs tend to have fewer problems WANs tend to be less fault
Tolerance associated with them, as there are smaller tolerant as they consist of
number of systems to deal with. large number of systems.
Ownership Typically owned, controlled, and WANs (like the Internet) are
managed by a single person or not owned by any one
organization. organization but rather exist
under collective or distributed
ownership and management
over long distances.
Set-up costs If there is a need to set-up a couple of For WANs since networks in
extra devices on the network, it is not remote areas have to be
very expensive to do that. connected the set-up costs are
higher. However WANs
using public networks can be
setup very cheaply using just
software (VPN etc).
LAN WAN
7. What is Networking?
Ans: A network is defined as a group of two or more computer systemslinked together. There are many types
of computer networks, including the following:
local-area networks (LANs): The computers are geographically close together (that is, in the same
building).
wide-area networks (WANs): The computers are farther apart and are connected by telephone lines or radio
waves.
campus-area networks (CANs): The computers are within a limited geographic area, such as a campus or
military base.
metropolitan-area networks MANs): A data network designed for a town or city.
home-area networks (HANs): A network contained within a user's home that connects a person's digital
devices.
Network Characteristics
In addition to these types, the following characteristics are also used to categorize different types of networks:
topology : The geometric arrangement of a computer system. Common topologies include a bus, star, and
ring. See the Network topology diagrams in the Quick Reference section of Webopedia.
protocol : The protocol defines a common set of rules and signals that computers on the network use to
communicate. One of the most popular protocols for LANs is called Ethernet. Another popular LAN
protocol for PCs is the IBM token-ring network .
architecture : Networks can be broadly classified as using either a peer-to-peer or client/server
architecture.
Computers on a network are sometimes called nodes. Computers and devices that allocate resources for a network
are called servers.
IP Packet Structure
An IP packet consists of header information as well as encapsulated data. An IP header consists of 14 fields and
contains necessary information required to deliver the packet at another end.
IP Packet Structure
Version: Provides the version number of Internet Protocol used (such as IPv4).
IHL: Refers to Internet Header Length which is the length of entire IP header.
DSCP: Differentiated Services Code Point, also called Type of Service and caters to data from emerging
technologies.
ECN: Explicit Congestion Notification provides information about the network congestion seen in the route.
Total Length: Length of entire IP packet which includes IP header and encapsulated data.
Identification: This field is used to uniquely identify a group of fragments in the single IP packet.
Flags: This is a three-bit field that is used to identify and control fragments. In this 3-bit flag, the bit 0 is always set
to '0'.
Fragment Offset: This offset provides the location of the fragment in the original IP Packet.
Time to Live (TTL): Every packet is sent with some TTL value set to avoid looping in the network. TTL tells the
network about the hops it has crossed on the router. With each hop, the TTL value is decremented by one and when
the value reaches zero, the packet is discarded.
Protocol: This field provides the protocol that is used in the data part of the packet.
Header Checksum: This field is used for error-checking of the entire header. The value of the header checksum is
matched at the router and the packet is discarded if values don't match.
Source Address: This field is the 32-bit address of the sender of the packet.
In the video below, we have explained the basic concepts of Object Oriented Programming with help of a very easy
to understand example. If you want to skip the video, everything is covered below as well.
Let us try to understand a little about all these, through a simple example. Human Beings are living forms, broadly
categorized into two types, Male and Female. Right? Its true. Every Human being(Male or Female) has two legs, two
hands, two eyes, one nose, one heart etc. There are body parts that are common for Male and Female, but then there
are some specific body parts, present in a Male which are not present in a Female, and some body parts present in
Female but not in Males.
All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs some common
functions, but there are some specifics to both, which is not valid for the other. For example : A Female can give
birth, while a Male cannot, so this is only for the Female.
Human Anatomy is interesting, isn't it? But let's see how all this is related to C++ and OOPS. Here we will try to
explain all the OOPS concepts through this example and later we will have the technical definitons for all this.
Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its properties
and its functions. Like Human Being, having body parts, and performing various actions.
Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat,
see etc. Male and Female are also classes, but most of the properties and functions are included in HumanBeing,
hence they can inherit everything from class HumanBeing using the concept of Inheritance.
Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being, Male or Female, we
just mean a kind, you, your friend, me we are the forms of these classes. We have a physical existence while a class
is just a logical definition. We are the objects.
Abstraction
Abstraction means, showcasing only the required things to the outside world while hiding the details. Continuing our
example, Human Being's can talk, walk, hear, eat, but the details are hidden from the outside world. We can take our
skin as the Abstraction factor in our case, hiding the inside mechanism.
Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk. Our hands, help us
hold things. This binding of the properties to functions is called Encapsulation.
Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either changing how it is done
or by changing the parts using which it is done. Both the ways have different terms for them.
If we walk using our hands, and not legs, here we will change the parts used to perform something. Hence this is
called Overloading.
And if there is a defined way of walking, but I wish to walk differently, but using my legs, like everyone else. Then I
can walk like I want, this will be called as Overriding.
One of the most useful ideas related to stacks comes from the simple observation of items as they are added and then
removed. Assume you start out with a clean desktop. Now place books one at a time on top of each other. You are
constructing a stack. Consider what happens when you begin removing books. The order that they are removed is
exactly the reverse of the order that they were placed. Stacks are fundamentally important, as they can be used to
reverse the order of items. The order of insertion is the reverse of the order of removal. Figure 3 shows the Python
data object stack as it was created and then again as items are removed. Note the order of the objects.
Considering this reversal property, you can perhaps think of examples of stacks that occur as you use your computer.
For example, every web browser has a Back button. As you navigate from web page to web page, those pages are
placed on a stack (actually it is the URLs that are going on the stack). The current page that you are viewing is on the
top and the first page you looked at is at the base. If you click on the Back button, you begin to move in reverse order
through the pages.
12. Describe Data Structure?
Ans: Data Structure is a way of collecting and organising data in such a way that we can perform operations on these
data in an effective way. Data Structures is about rendering data elements in terms of some relationship, for better
organization and storage. For example, we have some data which has, player's name "Virat" and age 26. Here "Virat"
is of String data type and 26 is of integer data type.
We can organize this data as a record like Player record, which will have both player's name and age in it. Now we
can collect and store player's records in a file or database as a data structure. For example: "Dhoni" 30, "Gambhir"
31, "Sehwag" 33
If you are aware of Object Oriented programming concepts, then a class also does the same thing, it collects different
type of data under one single entity. The only difference being, data structures provides for techniques to access and
manipulate data efficiently.
In simple language, Data Structures are structures programmed to store ordered data, so that various operations can
be performed on it easily. It represents the knowledge of data to be organized in memory. It should be designed and
implemented in such a way that it reduces the complexity and increases the efficiency.
Then we also have some complex Data Structures, which are used to store large and connected data. Some example
of Abstract Data Structure are :
Linked List
Tree
Graph
Stack, Queue etc.
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during declaration (if
necessary).
Constructors:
15. What is the difference between Views Table and Hash Table?
Ans: HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to
store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMapHashtable
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper
synchronization code.Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2) HashMap allows one null key and multiple null values.Hashtable doesn't allow any null key or value.
3) HashMap is a new class introduced in JDK 1.2.Hashtable is a legacy class.
4) HashMap is fast.Hashtable is slow.
5) We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);Hashtable is internally synchronized and can't be unsynchronized.
6) HashMap is traversed by Iterator.Hashtable is traversed by Enumerator and Iterator.
7) Iterator in HashMap is fail-fast.Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class.Hashtable inherits Dictionaryclass.
Drive Name: EASTERN SOFTWARE
Book Index: 235 (D)
Technical Interview
Examples:
Input : arr[] = { 1, 2, 5, 1, 7, 2, 4, 2}
Output : 1 2 5 7 4
Explanation : {1, 2} appear more than one time.
Approach :
Take a hash map, in which will store all the elements which has appeared before.
Traverse the array.
Check if the element is present in the hash map.
If yes, continue traversing the array.
Else Print the element.
4. Shell Sort.
Ans: ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position
ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to
allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing
the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted.
5. Merge Sort.
Ans: Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two
halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges
the two sorted sub-arrays into one.
Examples:
Examples:
A simple solution is to run two loops. For every element, check if it has appeared before. If yes, increment count
of distinct elements.
Examples:
Input:
5
/\
3 6
/\
2 4
Output:
Inorder of original tree: 2 3 4 5 6
Inorder of mirror tree: 6 5 4 3 2
Mirror tree will be:
5
/\
6 3
/\
4 2
Input:
2
/\
1 8
/ \
12 9
Output:
Inorder of original tree: 12 1 2 8 9
Inorder of mirror tree: 9 8 2 1 12
Approach: Write a recursive function that will take two nodes as the argument, one of the original tree and the
other of the newly created tree. Now, for every passed node of the original tree, create a corresponding node in
the mirror tree and then recursively call the same method for the child nodes but passing the left child of the
original tree node with the right child of the mirror tree node and the right child of the original tree node with the
left child of the mirror tree node.
Examples:
Input :
10
/ \
2 3
/ \ / \
7 8 12 15
/
14
Output : 10 3 15 14
The output nodes are the rightmost
nodes of their respective levels.
We have already discussed recursive solution for right view. In this post, level order traversal based solution is
discussed.
If we observe carefully, we will see that our main task is to print the right most node of every level. So, we will
do a level order traversal on the tree and print the rightmost node at every level.
Following is a simple program. For each node, check if left node of it is smaller than the node and right node of it is
greater than the node.
filter_none
edit
play_arrow
brightness_4
int isBST(struct node* node)
{
if (node == NULL)
return 1;
#include <stdio.h>
int main()
{
int i, Number, count;
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %llu", n, factorial);
}
return 0;
}
5. Display a pyramid of
*
*
***
*****
*******
*********
ANS:
while(k != 2 * i - 1) {
System.out.print("* ");
++k;
}
System.out.println();
}
}
}