Apt

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 18

7. What are the advantages of Distributed Processing? a. b. c. e. Security/Encapsulation Distributed database Faster Problem solving.

Security through redundancy Collaborative Processing

8. What are the criteria necessary for an effective and efficient network? a. Performance It can be measured in many ways, including transmit time and response time. b . Reliability It is measured by frequency of failure, the time it takes a link to recover f rom a failure, and the network's robustness. c. Security Security issues includes protecting data from unauthorized access and virues. 9. Name the factors that affect the performance of the network? a. b. c. d. Number of Users Type of transmission medium Hardware Software

10. Name the factors that affect the reliability of the network? a. Frequency of failure b. Recovery time of a network after a failure 11. Name the factors that affect the security of the network? a. Unauthorized Access b. Viruses 12. What is Protocol? A protocol is a set of rules that govern all aspects of information communicatio n. What are the key elements of protocols? The key elements of a. Syntax It refers to the they are presented. b. Semantics It refers to the c. Timing Timing refers to hey can be sent. protocols are structure or format of the data, that is the order in which meaning of each section of bits. two characteristics: When data should be sent and how fast t

14. What are the key design issues of a computer Network? a. b. c. d. Connectivity Cost-effective Resource Sharing Support for common Services Performance

15. Define Bandwidth and Latency? Network performance is measured in Bandwidth (throughput) and Latency (Delay). B andwidth of a network is given by the number of bits that can be transmitted ove

r the network in a certain period of time. Latency corresponds to how long it t5 akes a message to travel from one end off a network to the other. It is strictly measured in terms of time. 16. Define Routing? The process of determining systematically hoe to forward messages toward the des tination nodes based on its address is called routing. 17. What is a peer-peer process? The processes on each machine that communicate at a given layer are called peerpeer process. 18. When a switch is said to be congested? It is possible that a switch receives packets faster than the shared link can ac commodate and stores in its memory, for an extended period of time, then the swi tch will eventually run out of buffer space, and some packets will have to be dr opped and in this state is said to congested state. 19. What is semantic gap? Defining a useful channel involves both understanding the applications requireme nts and recognizing the limitations of the underlying technology. The gap betwee n what applications expects and what the underlying technology can provide is ca lled semantic gap. 20. What is Round Trip Time? The duration of time it takes to send a message from one end of a network to the other and back, is called RTT. 21. Define the terms Unicasting, Multiccasting and Broadcasting? If the message is sent from a source to a single destination node, it is called Unicasting. If the message is sent to some subset of other nodes, it is called Multicasting. If the message is sent to all the m nodes in the network it is called Broadcasti ng. 22. What is Multiplexing? Multiplexing is the set of techniques that allows the simultaneous transmission of multiple signals across a single data link. 23. Name the categories of Multiplexing? a. Frequency Division Multiplexing (FDM) b. Time Division Multiplexing (TDM) i. Synchronous TDM ii. ASynchronous TDM Or Statistical TDM. c. Wave Division Multiplexing (WDM) 24. What is FDM? FDM is an analog technique that can be applied when the bandwidth of a link is g reater than the combined bandwidths of the signals to be transmitted. What is WDM? WDM is conceptually the same as FDM, except that the multiplexing and demultiple xing involve light signals transmitted through fiber optics channel. 26. What is TDM?

TDM is a digital process that can be applied when the data rate capacity of the transmission medium is greater than the data rate required by the sending and re ceiving devices. 27. What is Synchronous TDM? In STDM, the multiplexer allocates exactly the same time slot to each device at all times, whether or not a device has anything to transmit. 28. List the layers of OSI a. b. c. d. e. f. g. Physical Layer Data Link Layer Network Layer Transport Layer Session Layer Presentation Layer Application Layer

29. Which layers are network support layers? a. Physical Layer b. Data link Layer and c. Network Layers 30. Which layers are user support layers? a. Session Layer b. Presentation Layer and c. Application Layer Which layer links the network support layers and user support layers? The Transport layer links the network support layers and user support layers. 32. What are the concerns of the Physical Layer? Physical layer coordinates the functions required to transmit a bit stream over a physical medium. a. Physical characteristics of interfaces and media b. Representation of bits c. Data rate d. Synchronization of bits e. Line configuration f. Physical topology g. Transmission mode 33. What are the responsibilities of Data Link Layer? The Data Link Layer transforms the physical layer, a raw transmission facility, to a reliable link and is responsible for node-node delivery. a. Framing b. Physical Addressing c. Flow Control d. Error Control e. Access Control 34. What are the responsibilities of Network Layer? The Network Layer is responsible for the source-to-destination delivery of packe

t possibly across multiple networks (links). a. Logical Addressing b. Routing 35. What are the responsibilities of Transport Layer? The Transport Layer is responsible for source-to-destination delivery of the ent ire message. a. Service-point Addressing b. Segmentation and reassembly c. Connection Control d. Flow Control e. Error Control 36. What are the responsibilities of Session Layer? The Session layer is the network dialog Controller. It establishes, maintains an d synchronizes the interaction between the communicating systems. a. Dialog control b. Synchronization What are the responsibilities of Presentation Layer? The Presentation layer is concerned with the syntax and semantics of the informa tion exchanged between two systems. a. Translation b. Encryption c. Compression 38. What are the responsibilities of Application Layer? The Application Layer enables the user, whether human or software, to access the network. It provides user interfaces and support for services such as e-mail, s hared database management and other types of distributed information services. a. Network virtual Terminal b. File transfer, access and Management (FTAM) c. Mail services d. Directory Services 39. What are the two classes of hardware building blocks? Nodes and Links. 40. What are the different link types used to build a computer network? a. b. c. d. Cables Leased Lines Last-Mile Links Wireless Links

41. What are the categories of Transmission media? a. Guided Media i. Twisted - Pair cable 1. Shielded TP 2. Unshielded TP ii. Coaxial Cable iii. Fiber-optic cable b. Unguided Media i. Terrestrial microwave ii. Satellite Communication

42. What are the types of errors? a. Single-Bit error In a single-bit error, only one bit in the data unit has changed b. Burst Error A Burst error means that two or more bits in the data have changed. 3. What is Error Detection? What are its methods? Data can be corrupted during transmission. For reliable communication errors mus t be deducted and Corrected. Error Detection uses the concept of redundancy, whi ch means adding extra bits for detecting errors at the destination. The common E rror Detection methods are a. Vertical Redundancy Check (VRC) b. Longitudinal Redundancy Check (VRC) c. Cyclic Redundancy Check (VRC) d. Checksum 44. What is Redundancy? The concept of including extra information in the transmission solely for the pu rpose of comparison. This technique is called redundancy. 45. What is VRC? It is the most common and least expensive mechanism for Error Detection. In VRC, a parity bit is added to every data unit so that the total number of 1s becomes even for even parity. It can detect all single-bit errors. It can detect burst errors only if the total number of errors in each data unit is odd. 46. What is LRC? In LRC, a block of bits is divided into rows and a redundant row of bits is adde d to the whole block. It can detect burst errors. If two bits in one data unit a re damaged and bits in exactly the same positions in another data unit are also damaged, the LRC checker will not detect an error. In LRC a redundant data unit follows n data units. 47. What is CRC? CRC, is the most powerful of the redundancy checking techniques, is based on bin ary division. 48. What is Checksum? Checksum is used by the higher layer protocols (TCP/IP) for error detection. 49. List the steps involved in creating the checksum. a. Divide the data into sections b. Add the sections together using 1's complement arithmetic c. Take the complement of the final sum, this is the checksum. 50. What are the Data link protocols? Data link protocols are sets of specifications used to implement the data link l ayer. The categories of Data Link protocols are 1. Asynchronous Protocols 2. Synchronous Protocols a. Character Oriented Protocols b. Bit Oriented protocols 51. Compare Error Detection and Error Correction:

The correction of errors is more difficult than the detection. In error detectio n, checks only any error has occurred. In error correction, the exact number of bits that are corrupted and location in the message are known. The number of the errors and the size of the message are important factors. 52. What is Forward Error Correction? Forward error correction is the process in which the receiver tries to guess the message by using redundant bits. 53. Define Retransmission? Retransmission is a technique in which the receiver detects the occurrence of an error and asks the sender to resend the message. Resending is repeated until a message arrives that the receiver believes is error-freed. 54. What are Data Words? In block coding, we divide our message into blocks, each of k bits, called dataw ords. The block coding process is one-to-one. The same dataword is always encode d as the same codeword. 5. What are Code Words? "r" redundant bits are added to each block to make the length n = k + r. The res ulting n-bit blocks are called codewords. 2n - 2k codewords that are not used. T hese codewords are invalid or illegal. 56. What is a Linear Block Code? A linear block code is a code in which the exclusive OR (addition modulo-2) of t wo valid codewords creates another valid codeword. 57. What are Cyclic Codes? Cyclic codes are special linear block codes with one extra property. In a cyclic code, if a codeword is cyclically shifted (rotated), the result is another code word. 58. Define Encoder? A device or program that uses predefined algorithms to encode, or compress audio or video data for storage or transmission use. A circuit that is used to conver t between digital video and analog video. 59. Define Decoder? A device or program that translates encoded data into its original format (e.g. it decodes the data). The term is often used in reference to MPEG-2 video and so und data, which must be decoded before it is output. 60. What is Framing? Framing in the data link layer separates a message from one source to a destinat ion, or from other messages to other destinations, by adding a sender address an d a destination address. The destination address defines where the packet has to go and the sender address helps the recipient acknowledge the receipt. What is public IP address? A public IP address is an address leased from an ISP that allows or enables dire ct Internet communication.

What's the benefit of subnetting? Reduce the size of the routing tables. Reduce network traffic. Broadcast traffic can be isolated within a single logica l network. Provide a way to secure network traffic by isolating it from the rest of the net work. What are the differences between static ip addressing and dynamic ip addressing? With static IP addressing, a computer (or other device) is configured to always use the same IP address. With dynamic addressing, the IP address can change peri odically and is managed by a centralized network service What is APIPA? Automatic private IP addressing (APIPA) is a feature mainly found in Microsoft o perating systems. APIPA enables clients to still communicate with other computer s on the same network segment until an IP address can be obtained from a DHCP se rver, allowing the machine to fully participate on the network. The range of the se IP address are the 169.254.0.1 to 169.254.255.254 with a default Class B subn et mask of 255.255.0.0. OPERATING SYSTENS Explain the concept of Reentrancy? It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program cod e cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Ea ch execution instance is called activation. It executes the code in the permanen t part, but has its own copy of local variables/parameters. The temporary part a ssociated with each activation is the activation record. Generally, the activati on record is kept on the stack. Note: A reentrant procedure can be interrupted and called by an interrupting pro gram, and still execute correctly on returning to the procedure. 2. Explain Belady's Anomaly? Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increase s even when more frames are allocated to the process. This is Belady's Anomaly. This is true for certain page reference patterns. 3. What is a binary semaphore? What is its use? A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual exclusion and synchronize concurrent processes. 4. What is thrashing? It is a phenomenon in virtual memory schemes when the processor spends most of i ts time swapping pages, rather than executing instructions. This is due to an in ordinate number of page faults. 5. List the Coffman's conditions that lead to a deadlock. Mutual Exclusion: Only one process may use a critical resource at a time. Hold & Wait: A process may be allocated some resources while waiting for others. No Pre-emption: No resource can be forcible removed from a process holding it. Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain. 6. What are short, long and medium-term scheduling? Long term scheduler determines which programs are admitted to the system for pro

cessing. It controls the degree of multiprogramming. Once admitted, a job become s a process. Medium term scheduling is part of the swapping function. This relates to process es that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memory-ma nagement criteria. Short term scheduler, also know as a dispatcher executes most frequently, and ma kes the finest-grained decision of which process should execute next. This sched uler is invoked whenever an event occurs. It may lead to interruption of one pro cess by preemption. What are turnaround time and response time? Turnaround time is the interval between the submission of a job and its completi on. Response time is the interval between submission of a request, and the first response to that request. 8. What are the typical elements of a process image? User data: Modifiable part of user space. May include program data, user stack a rea, and programs that may be modified. User program: The instructions to be executed. System Stack: Each process has one or more LIFO stacks associated with it. Used to store parameters and calling addresses for procedure and system calls. Process control Block (PCB): Info needed by the OS to control processes. 9. What is the Translation Lookaside Buffer (TLB)? In a cached system, the base addresses of the last few referenced pages is maint ained in registers called the TLB that aids in faster lookup. TLB contains those page-table entries that have been most recently used. Normally, each virtual me mory reference causes 2 physical memory accesses- one to fetch appropriate pagetable entry, and one to fetch the desired data. Using TLB in-between, this is re duced to just one physical memory access in cases of TLB-hit. 10. What is the resident set and working set of a process? Resident set is that portion of the process image that is actually in real-memor y at a particular instant. Working set is that subset of resident set that is ac tually needed for execution. (Relate this to the variable-window size method for swapping techniques.) 11. When is a system in safe state? The set of dispatchable processes is in a safe state if there exists at least on e temporal order in which all processes can be run to completion without resulti ng in a deadlock. 12. What is cycle stealing? We encounter cycle stealing in the context of Direct Memory Access (DMA). Either the DMA controller can use the data bus when the CPU does not need it, or it ma y force the CPU to temporarily suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only at specific break poi nts in an instruction cycle.

What is meant by arm-stickiness? If one or a few processes have a high access rate to data on one track of a stor age disk, then they may monopolize the device by repeated requests to that track . This generally happens with most common device scheduling algorithms (LIFO, SS TF(Shortest seek first (or shortest seek time first) is a secondary storage sche duling algorithm to determine the motion of the disk's arm and head in servicing read and write requests.), C-SCAN(The elevator algorithm (also SCAN) is a disk scheduling algorithm to determine the motion of the disk's arm and head in servi cing read and write requests.), etc). High-density multisurface disks are more l ikely to be affected by this than low density ones. 14. What are the stipulations of C2 level security? C2 level security provides for: Discretionary Access Control Identification and Authentication Auditing Resource reuse 15. What is busy waiting? The repeated execution of a loop of code while waiting for an event to occur is called busy-waiting. The CPU is not engaged in any real productive activity duri ng this period, and the process does not progress toward completion. 16. Explain the popular multiprocessor thread-scheduling strategies. Load Sharing: Processes are not assigned to a particular processor. A global que ue of threads is maintained. Each processor, when idle, selects a thread from th is queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis. Gang Scheduling: A set of related threads is scheduled to run on a set of proces sors at the same time, on a 1-to-1 basis. Closely related threads / processes ma y be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy. Dedicated processor assignment: Provides implicit scheduling defined by assignme nt of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in th e program. Processors are chosen from the available pool. Dynamic scheduling: The number of thread in a program can be altered during the course of execution. 17. When does the condition 'rendezvous' arise? In message passing, it is the condition in which, both, the sender and receiver are blocked until the message is delivered. 18. What is a trap and trapdoor? Trapdoor is a secret undocumented entry point into a program used to grant acces s without normal methods of access authentication. A trap is a software interrup t, usually the result of an error condition. LIVELOCK A real-world example of livelock occurs when two people meet in a narrow corrido r, and each tries to be polite by moving aside to let the other pass, but they e nd up swaying from side to side without making any progress because they both re peatedly move the same way at the same time. . What are local and global page replacements? Local replacement means that an incoming page is brought in only to the relevant process address space. Global replacement policy allows any page frame from any

process to be replaced. The latter is applicable to variable partitions model o nly. 20. Define latency, transfer and seek time with respect to disk I/O. Seek time is the time required to move the disk arm to the required track. Rotat ional delay or latency is the time it takes for the beginning of the required se ctor to reach the head. Sum of seek time (if any) and latency is the access time . Time taken to actually transfer a span of data is transfer time. 21. Describe the Buddy system of memory allocation. Free memory is maintained in linked lists, each of equal sized blocks. Any such block is of size 2^k. When some memory is required by a process, the block size of next higher order is chosen, and broken into two. Note that the two such piec es differ in address only in their kth bit. Such pieces are called buddies. When any used block is freed, the OS checks to see if its buddy is also free. If so, it is rejoined, and put into the original free-block linked-list. 22. What is time-stamping? It is a technique proposed by Lamport, used to order events in a distributed sys tem without the use of clocks. This scheme is intended to order events consistin g of the transmission of messages. Each system 'i' in the network maintains a co unter Ci. Every time a system transmits a message, it increments its counter by 1 and attaches the time-stamp Ti to the message. When a message is received, the receiving system 'j' sets its counter Cj to 1 more than the maximum of its curr ent value and the incoming time-stamp Ti. At each site, the ordering of messages is determined by the following rules: For messages x from site i and y from sit e j, x precedes y if one of the following conditions holds....(a) if Ti<Tj or (b ) if Ti=Tj and i<j. 23. How are the wait/signal operations for monitor different from those for sema phores? If a process in a monitor signal and no task is waiting on the condition variabl e, the signal is lost. So this allows easier program design. Whereas in semaphor es, every operation affects the value of the semaphore, so the wait and signal o perations should be perfectly balanced in the program. 24. In the context of memory management, what are placement and replacement algo rithms? Placement algorithms determine where in available real-memory to load a program. Common methods are first-fit, next-fit, best-fit. Replacement algorithms are us ed when memory is full, and one process (or part of a process) needs to be swapp ed out to accommodate a new program. The replacement algorithm determines which are the partitions to be swapped out. What is page cannibalizing? Page swapping or page replacements are called page cannibalizing. Which cryptography is more CPU intensive? In real world public-key cryptography is not used to exchange secure messages. T he reason is it requires high CPU processing power. Secret-key cryptography is f ast in computation in comparison with public-key cryptography. What is Message Authentication Code (MAC)? Message authentication code is value or checksum attached with original message to provide authenticity and integrity of data. MAC is calculated using a hash fu nction and a secret key. MACs differ from digital signatures as MAC values are both generated and verifie

d using the same secret key. This implies that the sender and receiver of a mess age must agree on the same key before initiating communications, as is the case with symmetric encryption. OPERATING SYSTEM TYPES As computers have progressed and developed so have the types of operating system s. Below is a basic list of the different types of operating systems and a few e xamples of Operating Systems that fall into each of the categories. Many compute r Operating Systems will fall into more than one of the below categories. GUI - Short for Graphical User Interface, a GUI Operating System contains graphi cs and icons and is commonly navigated by using a computer mouse. See our GUI di ctionary definition for a complete definition. Below are some examples of GUI Op erating Systems. System 7.x Windows 98 Windows CE Multi-user - A multi-user Operating System allows for multiple users to use the same computer at the same time and/or different times. See our multi-user dictio nary definition for a complete definition for a complete definition. Below are s ome examples of multi-user Operating Systems. Linux Unix Windows 2000 Windows XP Mac OS X Multiprocessing - An Operating System capable of supporting and utilizing more t han one computer processor. Below are some examples of multiprocessing Operating Systems. Linux Unix Windows 2000 Windows XP Mac OS X Multitasking - An Operating system that is capable of allowing multiple software processes to run at the same time. Below are some examples of multitasking Oper ating Systems. Unix Windows 2000 Windows XP Mac OS X Multithreading - Operating systems that allow different parts of a software prog ram to run concurrently. Operating systems that would fall into this category ar e: Linux Unix Windows 2000 Windows XP Mac OS X Why paging is used? -Paging is solution to external fragmentation problem which is to permit the log ical address space of a process to be noncontiguous, thus allowing a process to

be allocating physical memory wherever the latter is available. While running DOS on a PC, which command would be used to duplicate the entire d iskette? diskcopy What is virtual memory? Virtual memory is hardware technique where the system appears to have more memor y that it actually does. This is done by time-sharing, the physical memory and s torage parts of the memory one disk when they are not actively being used. suppose we have parent class add( int , int) child class add(double, double ) if we call child.add( double, double), is it correct syntax? No it will give compile time error.You can call only static methods using class name like "child.add(...)" here add should be static. rules of calling method: 1) if you create pointer of ll method of base class. 2) if you create pointer of call method of child class 3) if you create pointer of i) if method is non virtual ii) if method is virtual it base class and store object of base class then it ca child class and store object of child class then it base class and store object of child class then it call method of base class call method of child class

CHECKING TH TREE IS BALANCED OR NOT: I'd have given a different algorithm. The recursion you've shown is clumsy and h as a lot more code than needed. The rule for balance: |NO.of levels on left - NO. of levels on right| <= 1 (ABSL T VALUE) We only need two methods, the starting method, and the recursion. I'll be using java here. public boolean isBalanced(Node root) { int left = balance_check(root.left); //CHECK THE LEFT SUBTREE. int right = balance_check(root.right); //CHECK THE RIGHT SUBTREE. return (Math.pow(left - right, 2) <= 1); //RETURNS THE SQUARE OF THEIR DIFFER NCES AND IF <=1 } public int balance_check(Node root){ if(root == null) return 0; return 1 + (Math.max(balance_check(root.left), balance_check(root.right)); }

Assume that you are given a fixed set of floating point numbers. Now given a new floating point number 'x', the goal is to efficiently find the number that is c losest to 'x' from the fixed set. Question is: what data structure will you actu ally use for storing the fixed set of floating point numbers to achieve this?

Edit: I missed to add. The interviewer further mentioned that I can not sort and that I can use any amount of time for creating the data structure (meaning this need not be efficient). Since, I am not allowed to 'sort', I assumed that I can not use BST as I will ha ve to compare numbers while populating the tree. But I didn't clarify it with hi m; I should have in hindsight. void printNearest() { float modulo = -1; //Init to -1 for starter float array[MAX_SIZE]; // MAX_SIZE = total number of floats float x; // Given number loadFloats(array); // Load all the floating point numbers List<float> closestNums = new ArrayList<>(); // Java 7 style for(int i=0; i<array.length; i++) { float num = array[i]; float moduloDiff = (num-x)<=0 ? -(num-x) : (num-x); if(modulo == -1) { modulo = moduloDiff; closestNums.add(num); } else if(modulo > moduloDiff) { modulo = moduloDiff; closestNums.clear(); closestNums.add(num); } else if(modulo == moduloDiff) { closestNums.add(num); } else { continue; //Ignore the number, it is not near } } printAllNums(closetNums); //Print all the numbers } find the duplicate strings in the array a={"IBM","GOOGLE","AMAZON","GOOGLE"} class DuplicateStrings{ public static void main(String[] args){ String[] s = {"IBM","Google","Amazon","Google","HP","IBM","Oracl e","IBM","HP"}; int duplicate = 0; String[] sc = s.clone(); for(int i=0; i<s.length;i++) for (int j=i+1;j<sc.length;j++) if ((s[i]==sc[j])&&(s[i]!="NULL")){

duplicate++; sc[j]="NULL"; } System.out.println("Total duplicates - "+duplicate); } } HOW TO REVERSE STRING IN JAVA? import java.io.FileNotFoundException; import java.io.IOException; /** * *@author Javin / public class StringReverseExample { public static void main(String args[]) throws FileNotFoundException, IOExcep tion { //original string String str = "Sony is going to introduce Internet TV soon"; System.out.println("Original String: " + str); //reversed string using Stringbuffer String reverseStr = new StringBuffer(str).reverse().toString(); System.out.println("Reverse String in Java using StringBuffer: " + rever seStr); //iterative method to reverse String in Java reverseStr = reverse(str); System.out.println("Reverse String in Java using Iteration: " + reverseS tr); //recursive method to reverse String in Java reverseStr = reverseRecursively(str); System.out.println("Reverse String in Java using Recursion: " + reverseS tr); } public static String reverse(String str) { StringBuilder strBuilder = new StringBuilder(); char[] strChars = str.toCharArray(); for (int i = strChars.length - 1; i >= 0; i--) { strBuilder.append(strChars[i]); } return strBuilder.toString(); } public static String reverseRecursively(String str) { //base case to handle one char string and empty string if (str.length() < 2) { return str; } return reverseRecursively(str.substring(1)) + str.charAt(0);

} } Checking Array for duplicate elements Java In this Java tutorial we will see couple of ways to find if array contains dupli cates or not in Java. We will use unique property of Java collection class Set w hich doesn t allow duplicates to check java array for duplicate elements. Here ar e five ways we can check if an array has duplicates or not: 1) brute force method which compares each element of Array to all other elements and return true if it founds duplicates. Though this is not an efficient choice it is the one which first comes in mind. 2) Another quick way of checking if a Java array contains duplicates or not is t o convert that array into Set. Since Set doesn t allow duplicates size of corresp onding Set will be smaller than original Array if Array contains duplicates othe rwise size of both Array and Set will be same. 3) One more way to detect duplication in java array is adding every element of a rray into HashSet which is a Set implementation. Since add(Object obj) method of Set returns false if Set already contains element to be added, it can be used t o find out if array contains duplicates in Java or not. How to find or detect duplicate elements in Array in JavaIn next section we will complete code example of all three ways of duplicate detection on Array in java . Remember this discussion is just confirming whether array contains duplicate o r not , its not finding out actual duplicate elements from Array, though you can easily extend example Java program to accomplish that task based on your requir ement. PGM IN JAVA FOR PALINDROME: import java.util.*; class Palindrome { public static void main(String args[]) { String original, reverse=""; Scanner in = new Scanner(System.in); System.out.println("Enter a string to check if it is a palindrome"); original = in.nextLine(); int length = original.length(); for ( int i = length - 1 ; i >= 0 ; i-- ) reverse = reverse + original.charAt(i); if (original.equals(reverse)) System.out.println("Entered string is a palindrome."); else System.out.println("Entered string is not a palindrome."); } } REMOVE ANY GIVEN CHARACTERB FROM STRING:

Remove any given character from a String. /** * Removes any given character from a String.<br> * This program uses the StringBuilder to avoid un-necessary creation of * immutable String object. * * @author rampravesh, May 28, 2012 */ public class RemoveCharacterFromString { public static void main (String[] args) { System.out.println (removeCharInString ("My name is rampravesh kumara", 'a')); } public static String removeCharInString (String str, char charToBeRemoved) { if (str == null) return ""; StringBuilder strBuild = new StringBuilder (); for (int i = 0; i < str.length (); i++) { char ch = str.charAt (i); if (ch == charToBeRemoved) continue; strBuild.append (ch); } return strBuild.toString (); } } Find all the permutations of a string in Java Now, here is what the Java method would like for our algorithm: void permute( String input) { int inputLength = input.length(); boolean[ ] used = new boolean[ inputLength ]; StringBuffer outputString = new StringBuffer(); char[ ] in = input.toCharArray( ); doPermute ( in, outputString, used, inputLength, 0 ); } void doPermute ( char[ ] in, StringBuffer outputString, boolean[ ] used, int inputlength, int level) { if( level == inputLength) { System.out.println ( outputString.toString()); return; } for( int i = 0; i < inputLength; ++i ) {

if( used[i] ) continue; outputString.append( in[i] ); used[i] = true; doPermute( in, outputString, used, length, level + 1 ); used[i] = false; outputString.setLength( outputString.length() - 1 ); } } Our description of the process that we followed sounds a lot like something that could be solved with recursion. How can we change our description so that it s ea sier to write out in a recursive method? Let s phrase it like this: In order to fi nd all possible combinations for a given string, then start at a position x, the n find and place all possible letters in position x. Every time we put a new let ter in position x, we should then find all the possible combinations at position x+1 this would be the recursive call that we make. How do we know when to print out a string? Well, when we are at a position x that is greater than the number of letters in the input string, then we know that we have found one valid combi nation/permutation of the string and then we can print it out and return to chan ging letters at positions less than x. This would be our base case remember that we always must have a recursive case and a base case when using recursion. TO FIND LONGEST PALINDROME: public class LongestPalindromeFinder { public static void main(String[] args) { System.out.println(longestPalindromeString("1234")); System.out.println(longestPalindromeString("12321")); System.out.println(longestPalindromeString("9912321456")); System.out.println(longestPalindromeString("9912333321456")); System.out.println(longestPalindromeString("12145445499")); } /** * This method returns the longest palindrome in the input String * * @param in * @return */ public static String longestPalindromeString(String in) { char[] input = in.toCharArray(); int longestPalindromeStart = 0; int longestPalindromeEnd = 0; for (int mid = 0; mid < input.length; mid++) { // for odd palindrom case like 12321, 3 will be the mid int left = mid-1; int right = mid+1; // we need to move in the left and right side by 1 place till they r each the end while (left >= 0 && right < input.length) { // below check to find out if its a palindrome if (input[left] == input[right]) { // update global indexes only if this is the longest one til l now if (right - left > longestPalindromeEnd - longestPalindromeStart) { longestPalindromeStart = left; longestPalindromeEnd = right; }

} left--; right++; } // for even palindrome, we need to have similar logic with mid size 2 // for that we will start right from one extra place left = mid-1; right = mid + 2;// for example 12333321 when we choose 33 as mid while (left >= 0 && right < input.length) { if (input[left] == input[right]) { if (right - left > longestPalindromeEnd - longestPalindromeStart) { longestPalindromeStart = left; longestPalindromeEnd = right; } } left--; right++; } } // we have the start and end indexes for longest palindrome now return in.substring(longestPalindromeStart, longestPalindromeEnd + 1); } } Another reason of Why String is immutable in Java is to allow String to cache it s hashcode , being immutable String in Java caches its hashcode, and do not calc ulate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java. This one is also suggested by Jaros lav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation. d reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on c omments is: The absolutely most important reason that String is immutable is tha t it is used by the class loading mechanism, and thus have profound and fundamen tal security aspects. Had String been mutable, a request to load "java.io.Writer " could have been changed to load "mil.vogoon.DiskErasingWriter" Suppose n = least number of bombs that must be dropped so that the probability o f destruction of the bridge is greater than 0.99. Hence the probability that the bridge is NOT destroyed is less than 0.01. If less than two bombs hit the bridge then it is not destroyed and probability o f it is [ nCo + nC1 ] ( 0.5 )^n < 0.01 => ( 0.5 )^n < 0.01 / (n + 1) Putting n = 1, 2, 3, and so on you find that inequality is not satisfied till n = 10 and is satisfied for n = 11. when n = 10, LHS = 0.000976 < RHS = 0.000909 is false when n = 11, LHS = 0.000488 < RHS = 0.000833 is true. Therefore, n = 11.

You might also like