Dr. Robert Owor’s Internet Collection of 100 Coding Challenges

Waiver This of Coding Challenges was collected from Public Internet Sources. The intention is to teach Computer Science Students how to become great coders. I thank all the various authors of these problems who posted them on the Internet – Dr. Robert Steven Owor Instructions Here are 100 Coding problems. Write a running Computer program in one of the following 3 languages (Java, C++ or Python) to solve the problems listed below, and submit your solutions to me by email at [email protected]

You have 21 Days beginning May 6th 2020. If you start after May 5th, that’s your problem. I expect the solution to all 100 Problems emailed to me by May 27th 2020, 11.55pm. If you would like to make another arrangement, please contact me at [email protected] Your Solutions for each number must consist of the following: (i) A Working Program which runs on https://www.tutorialspoint.com/codingground.htm

(ii) Test Input Data (iii) Test Output Data which addresses, the zero input, wrong data type input, array boundaries, set values if any. I will grade your answers and give you a score out of 100 by May 30th 2020. If you score 80% or above, you will be invited to sit for an IBM Hackathon. There are possibilities for Internships and jobs if you score above 80% in both my 100-Problem Coding Challenge and the IBM Hackathon.

Problems 1) Write code to check if a String is palindrome or not?

2) Write a method which will remove any given character from a String?

3) Print all permutation of a String both iterative and Recursive way?

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 1

4) Write a function to find out longest palindrome in a given string?

5) Write a Program which finds all unique substrings of length 2 or greater in a string 6) Write a Program which finds all vowels in a string.

7) In an array 1-100 numbers are stored, one number is missing how do you find it?

8) In an array 1-100 exactly one number is duplicate how do you find it?

9) In an array 1-100 multiple numbers there are duplicates, how do you find all duplicates?

10) Given two arrays, 1,2,3,4,5 and 2,3,1,0,5 find which number is not present in the second array.

11) How do you find the second highest number in an integer array?

12) Find all unique pairs of numbers in an array of integers whose sum is the same?

13) Remove all duplicate elements from an Array?

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 2 14) How do you find middle element of a linked list in a single pass?

15) How do you find the 3rd element from last in a single pass?

16) How do you find if there is a cycle in a singly linked list? How do you find the start of the cycle?

17) Reverse a singly linked list?

18) Delete the pth element in a linked list using two implementations: Links and array data structure?

19) Find the largest and smallest number in an array?

20) Find the two maximum numbers in an array?

21) Find and print the depth of a binary ?

22) Write code to print In-Order traversal of a ?

23) Write code to print Post-Order traversal of a binary tree?

24) Write code to print Pre-Order traversal of a binary tree?

25) Print out all leaf node of a binary tree?

26) Write a program to check if a tree is a binary or not

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 3 27) Write a Program to check if a tree is balanced or not.

28) Print all leaves of a 29) Count the number of leaf nodes in a given binary tree 30) Perform a binary search in a given array

31) Write a program to sort numbers in place using quick sort

32) Write a program to implement a binary search/sort algorithm

33) Write code to implement Insertion Sort

34) Write code to implement Bubble Sort

35) Write Code to implement MergeSort

36) Write Code to implement HeapSort

37) Write Code to implement RadixSort

38) Write code to check whether a number is a power of two or not?

39) Write a program to check whether a number is a palindrome or not

40) Write code to check whether an integer is an Armstrong number or not?

41) Write a program to find all prime number up to a given number?

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 4

42) Write a function to compute Nth Fibonacci number? Both iterative and recursive?

43) Write a Program which checks if a number is binary? I.e. contains only 0s and 1s.

44) Write a Program to count the number of 1s in given binary integer?

45) Write a recursive program to find the sum of digits of a binary number?

46) Write a Program to swap two numbers without using temp

47) Write a Program to find the largest of three integers

48) Write a program to find prime factors of an integer

49) Write a Program to add two integers without using arithmetic operator

50) Implement a Stack of Integers using Arrays and then Linked Lists?

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 5 51) Convert an Arithmetic Expression into Postfix using a Stack

52) Evaluate a Postfix Arithmetic Expression using Stacks

53) Implement Bucket Sort

54) Implement the Subtraction of Two Binary Numbers

55) Print Floyd's triangle up to the 10th row

56) Print Pascal’s Triangle up to the 10th row

57) Calculate the Square root of a given number without using the Square Root function

58) Write a Program which converts a Decimal Number into Binary and a Binary Number into Decimal. 59) Write a Program to solve this problem:

We are given strings containing brackets of 4 types - round (), square [], curly {} and angle <> ones. The goal is to check, whether brackets are in correct sequence. I.e. any opening bracket should have closing bracket of the same type somewhere further by the string, and bracket pairs should not overlap, though they could be nested:

(a+[b*c] - {d/3}) - here square and curly brackets are nested in the round ones

(a+[b*c) - 17] - here square brackets overlap with round ones which does not make sense

60) Here is the classical programming puzzle though it came from ancient times when there are no computers at all. We can see that practicing math and logic can sometimes save one's life!

About 2000 years ago there was some war, and during one of its battles defendants were blocked by attackers in the cave.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 6

To avoid capture they decided to stand in a circle and kill each third person until only one person remains - who was supposed to commit suicide - though he eventually preferred to surrender to enemies. The problem is called after this person - you may read the full story of Josephus and get math explanation of the problem in Wikipedia article.

Your task is to determine for given number of people N and constant step K the position of a person who remains the last - i.e. the safe position. For example if there are 10 people and they eliminate each third:

N = 10, K = 3 sequence of counting looks like this (brackets show persons who are eliminated):

1st round: 1 2 (3) 4 5 (6) 7 8 (9) 10 2nd round: 1 (2) 4 5 (7) 8 10 3rd round: (1) 4 5 (8) 10 4th round: 4 (5) 10 5th round: 4 (10) so the "winner" is one who was #4 at initial standing.

Input data will contain number of people N and the counting step K.

Answer should contain the number of person who will remain at the end. Initial numbering starts from 1.

Example: initial data:

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 7 10 3 answer: 4 ------

61) Write a Program to solve this problem: Two bicyclists start moving from different cities heading to meet each other somewhere in the middle (not exactly since they travel with different speed).

The road is laid in straight line between two cities.

You will be given the distance between cities S (in kilometers) and speed values for two bicyclists (A and B in kilometers per hour). Your task is to find their meeting point (its distance from the first of cities).

Input data will have the number of test-cases in the first line. Next lines will contain three values each S A B. Answer should contain the distances between first city and rendezvous point (i.e. distance travelled by first cyclist before they meet), separated with spaces.

Example: input data: 2 10 1 1 20 1 2 answer: 5 6.66666667

62. Cryptography is one of most interesting branches of programming. Studying its algorithms usually begins with the simple method named after famous Roman emperor Julius Caesar who used it for communicating his military secrets (and perhaps for love letters to Cleopatra).

We will practice deciphering encrypted messages in this problem.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 8 The idea of the algorithm is simple. Each letter of the original text is substituted by another, by the following rule:

find the letter (which should be encrypted) in the alphabet; move K positions further (down the alphabet); take the new letter from here; if "shifting" encountered the end of the algorithm, continue from its start.

For example, if K = 3 (shift value used by Caesar himself), then A becomes D, B becomes E, W becomes Z and Z becomes C and so on, according to the following table:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

| | | | | | | | | | | | | | | | | | | | | | | | | | V V V V V V V V V V V V V V V V V V V V V V V V V V

D E F G H I J K L M N O P Q R S T U V W X Y Z A B C

So if the source message was VENI VIDI VICI then after encoding it becomes YHQL YLGL YLFL.

On the other hand encrypted message should be "shifted back" to decode it - or shifted by 26 - K which is the same.

So if we have encoded message HYHQ BRX EUXWXV, we can apply shift of 26 - K = 26 - 3 = 23 and find the original text to be EVEN YOU BRUTUS.

Input data will contain two integers - the number of lines of encrypted text and the value of K.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 9 The following lines will contain encrypted text, consisting of capital Latin letters A ... Z, each line is terminated with a dot. which should not be decoded. Answer should contain the decrypted message (in a single line, no line splitting is needed).

Example: input data: 2 3 YHQL YLGL YLFL. HYHQ BRX EUXWXV. answer: VENI VIDI VICI. EVEN YOU BRUTUS.

63. Write a Program to solve this problem:

Being able to calculate area of triangle is quite important since many more complex tasks are often easily reduced to this (and we will use it too later).

One of the oldest known methods is Heron's Formula which takes as inputs the lengths of the triangle's sides.

In this problem you however is to write a program which uses X and Y coordinates of the triangle's vertices instead. So you can use either this formula somehow or find another one.

Input data will contain the number of triangles to process. Next lines will contain 6 values each, in order X1 Y1 X2 Y2 X3 Y3, describing three vertices of a triangle. Answer should give areas of triangles separated by space (precision about 1e-7 is expected).

Example: data: 3 1 3 9 5 6 0

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 10 1 0 0 1 10000 10000 7886 5954 9953 2425 6250 2108 answer: 17 9999.5 6861563

64. Write a Program to solve this problem:

Ali-Baba found a secret cave with treasures, stored by The Forty Thieves. However, famous magical phrase Open Sesame obviously does not work.

Instead there is a long and strange text inscribed on the stone wall - and Ali-Baba guessed that one should find matching words in this inscription (i.e. ones which are encountered more than once) and pronounce them in alphabetical order.

We are to help the poor craftsman to access the thieves' treasury. Let's write a program that sieves necessary words from the given text, and prints them in the proper order.

Input data consist of about 300 words, each made of 3 Latin letters. The end is signaled by the word end. Answer should contain all the words which are encountered more than once in lexicographic order.

Example: input data: nun lam mip tex bal pif sot bal bod tex end answer: bal tex

65. Write a Program to solve this problem:

Fundamental Theorem of Arithmetic states that any integer could be represented as product of one or more primes and such representation is unique, for example:

1000 = 2 * 2 * 2 * 5 * 5 * 5 1001 = 7 * 11 * 13 1002 = 2 * 3 * 167 1003 = 17 * 59 1009 = 1009

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 11 Here we regard 1009 as a singular case of product of only one prime value - itself!

It is still unknown whether factorization could be done efficiently, i.e. fast enough for big numbers. For example a number built as product of two 200-digit primes (i.e. having only 400 digits itself) will require many thousand years to decompose it back into original pair of primes on modern computers.

Of course this precious fact has great significance in cryptography. If a fast algorithm is ever found, many crypto methods popular nowadays will become insecure! The classic example is an RSA algorithm.

Problem Statement

You will be given several numbers (not very large, so do not be afraid) to decompose them into products of primes.

Input data will contain amount of integers to factorize in the first line. Next lines will contain one integer each (not exceeding 13 digits in length). Answer should contain product representation for each of these integers, written like p1*p2*p3 where p1 ... p3 are some primes sorted in non-decreasing order. Products should be separated with spaces.

Example: input data: 5 1000 1001 1002 1003 1009 answer: 2*2*2*5*5*5 7*11*13 2*3*167 17*59 1009

66. Write a Program to solve the following problem.

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value I 1

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 12 V 5 X 10 L 50 C 100 D 500 M 1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

 I can be placed before V (5) and X (10) to make 4 and 9.  X can be placed before L (50) and C (100) to make 40 and 90.  C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III" Output: 3

Example 2:

Input: "IV" Output: 4

Example 3:

Input: "IX" Output: 9

Example 4:

Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 13 Example 5:

Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

67. Write Code to solve the following Problem:

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

'.' Matches any single character. '*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

Note:

 s could be empty and contains only lowercase letters a-z.  p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa".

Example 2:

Input: s = "aa" p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 14 Example 3:

Input: s = "ab" p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input: s = "aab" p = "c*a*b" Output: true Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".

Example 5:

Input: s = "mississippi" p = "mis*is*p*." Output: false

68. Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 15

69) Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0] Output: 3

Example 2:

Input: [3,4,-1,1] Output: 2

Example 3:

Input: [7,8,9,11,12] Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

------

70) Given a collection of distinct integers, return all possible permutations. Example:

Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]

71) Say you have an array prices for which the ith element is the price of a given stock on day i.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 16

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.

Constraints:

1 <= prices.length <= 3 * 10 ^ 4 0 <= prices[i] <= 10 ^ 4

72) Another example of the parentheses matching problem comes from hypertext markup language (HTML). In HTML, tags exist in both opening and closing forms and must be balanced to properly describe a web document. This very simple HTML document:

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 17 Example

Hello, world

is intended only to show the matching and nesting structure for tags in the language. Write a program that can check an HTML document for proper opening and closing tags.

73) To implement the length method, we counted the number of nodes in the list. An alternative strategy would be to store the number of nodes in the list as an additional piece of data in the head of the list. Modify the UnorderedList class to include this information and rewrite the length method.

Implement the remove method so that it works correctly in the case where the item is not in the list.

74) Implement a deque using linked lists.

The head reference also contains two references, one to the first node in the linked list and one to the last. Code this implementation in Python.

Create an implementation of a queue that would have an average performance of O(1) for enqueue and dequeue operations.

75) Implement BFS in a Graph

76) Implement DFS in a Graph

77) Implement Djikstra’s Shortest Path Algorithm

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 18 78) Implement Kruskal’s Algorithm

79) Implement Prim’s Algorithm

80) Implement a Minimum Spanning Tree Algorithm

81) Find the longest path in a DAG

82) Given an array of distinct integers, find if there are two pairs (a, b) and (c, d) such that a+b = c+d, and a, b, c and d are distinct elements. If there are multiple answers, then print any of them. Use hash Functions.

83) Given an array containing only 0s and 1s, find the largest subarray which contain equal no of 0s and 1s. Expected time complexity is O(n). Use Hash Functions

84) You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

85) Below are the two lists convert it into the dictionary keys = ['Ten', 'Twenty', 'Thirty'] values = [10, 20, 30]

Expected output:

{'Ten': 10, 'Twenty': 20, 'Thirty': 30} ------

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 19

SQL Questions We'll be going through six questions covering topics like query performance, joins, and SQL injection. They'll refer to the same database for cakes, customers, and orders at a bakery. Here's the schema:

CREATE TABLE cakes ( cake_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, flavor VARCHAR(100) NOT NULL );

CREATE TABLE customers ( customer_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(100) NOT NULL, last_name VARCHAR(100) NOT NULL, phone VARCHAR(15), street_address VARCHAR(255), city VARCHAR(255), zip_code VARCHAR(5), referrer_id INT, FOREIGN KEY (referrer_id) REFERENCES customers (customer_id) );

CREATE TABLE orders ( order_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, cake_id INT NOT NULL, customer_id INT, pickup_date DATE NOT NULL,

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 20 FOREIGN KEY (cake_id) REFERENCES cakes (cake_id), FOREIGN KEY (customer_id) REFERENCES customers (customer_id) );

SQL

We'll be using MySQL for consistency.

In the MySQL shell, use the bakery database: USE BAKERY;

86) How can we get the nth highest number of orders a single customer has?

We made a view ↴ of the number of orders each customer has:

CREATE VIEW customer_order_counts AS SELECT customers.customer_id, first_name, count(orders.customer_id) AS order_count FROM customers LEFT OUTER JOIN orders ON (customers.customer_id = orders.customer_id) GROUP BY customers.customer_id;

SQL

So for example, Nancy has 3 orders:

SELECT * FROM customer_order_counts ORDER BY RAND() LIMIT 1;

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 21 87) What ways can we use wildcard characters in LIKE clauses? 88) Now how can we make this query faster?

We're mailing a promotion to all our customers named Sam who live in Dover. Since some customers go by names that aren't exactly Sam, like Samuel or Sammy, we use names like Sam. Here's how we find them:

SELECT first_name, last_name, street_address, city, zip_code FROM customers WHERE first_name LIKE '%sam%' AND city = 'Dover'; -- 1072 rows in set (0.42 sec)

89) What are SQL joins? Tell us about the different kinds of Joins.

90) What’s an example of SQL injection and how can we prevent it?

91) Map Routing https://www.cs.princeton.edu/courses/archive/spring04/cos226/assignments/map.html

Implement the classic Dijkstra's shortest path algorithm and optimize it for maps. Such algorithms are widely used in geographic information systems (GIS) including MapQuest and GPS-based car navigation systems.

Maps. For this assignment we will be working with maps, or graphs whose vertices are points in the plane and are connected by edges whose weights are Euclidean distances. Think of the vertices as cities and the edges as roads connected to them. To represent a map in a file, we list the number of vertices and edges, then list the vertices (index followed by its x and y coordinates), then list the edges (pairs of vertices), and finally the source and sink vertices. For example, input6.txt represents the map below:

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 22 Dijkstra's algorithm. Dijkstra's algorithm is a classic solution to the shortest path problem. It is described in Sedgewick, Chapter 21. The basic idea is not difficult to understand. We maintain, for every vertex in the graph, the length of the shortest known path from the source to that vertex, and we maintain these lengths in a priority queue. Initially, we put all the vertices on the queue with an artificially high priority and then assign priority 0.0 to the source. The algorithm proceeds by taking the lowest-priority vertex off the PQ, then checking all the vertices that can be reached from that vertex by one edge to see whether that edge gives a shorter path to the vertex from the source than the shortest previously-known path. If so, it lowers the priority to reflect this new information.

Here is a step-by-step description that shows how Dijkstra's algorithm finds the shortest path 0- 1-2-5 from 0 to 5 in the example above.

process 0 (0.0) lower 3 to 3841.9 lower 1 to 1897.4 process 1 (1897.4) lower 4 to 3776.2 lower 2 to 2537.7 process 2 (2537.7) lower 5 to 6274.0 process 4 (3776.2) process 3 (3841.9) process 5 (6274.0)

This method computes the length of the shortest path. To keep track of the path, we also maintain for each vertex, its predecessor on the shortest path from the source to that vertex. The files EuclideanGraph.java, Point.java, IndexPQ.java, IntIterator.java, and Dijkstra.java provide a bare bones implementation of Dijkstra's algorithm for maps, and you should use this as a starting point. The client program ShortestPath.java solves a single shortest path problem and plots the results using turtle graphics. The client program Paths.java solves many shortest path problems and prints the shortest paths to standard output. The client program

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 23 Distances.java solves many shortest path problems and prints only the distances to standard output.

Your goal. Optimize Dijkstra's algorithm so that it can process thousands of shortest path queries for a given map. Once you read in (and optionally preprocess) the map, your program should solve shortest path problems in sublinear time. One method would be to precompute the shortest path for all pairs of vertices; however you cannot afford the quadratic space required to store all of this information. Your goal is to reduce the amount of work involved per shortest path computation, without using excessive space. We suggest a number of potential ideas below which you may choose to implement. Or you can develop and implement your own ideas.

Idea 1. The naive implementation of Dijkstra's algorithm examines all V vertices in the graph. An obvious strategy to reduce the number of vertices examined is to stop the search as soon as you discover the shortest path to the destination. With this approach, you can make the running time per shortest path query proportional to E' log V' where E' and V' are the number of edges and vertices examined by Dijkstra's algorithm. However, this requires some care because just re-initializing all of the distances to ∞ would take time proportional to V. Since you are doing repeated queries, you can speed things up dramatically by only re-initializing those values that changed in the previous query.

Idea 2. You can cut down on the search time further by exploiting the Euclidean geometry of the problem, as described in Sedgewick 21.5. For general graphs, Dijkstra's relaxes edge v-w by updating wt[w] to the sum of wt[v] plus the distance from v to w. For maps, we instead update wt[w] to be the sum of wt[v] plus the distance from v to w plus the Euclidean distance from w to d minus the Euclidean distance from v to d. This is known as the A* algorithm. This heuristics affects performance, but not correctness. (See Sedgewick 21.5 for a proof of correctness.)

Idea 3. Use a faster priority queue. There is some room for optimization in the supplied priority queue. You could also consider using a multiway as in Sedgewick Program 20.10.

Testing. The file usa.txt contains 87,575 intersections and 121,961 roads in the continental United States. The graph is very sparse - the average degree is 2.8. Your main goal should be to answer shortest path queries quickly for pairs of vertices on this network. Your algorithm will likely perform differently depending on whether the two vertices are nearby or far apart. We

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 24 provide input files that test both cases. You may assume that all of the x and y coordinates are integers between 0 and 10,000.

Deliverables. Improve the bare bones implementation by using some of the ideas described above together with your ingenuity. You may modify Dijkstra.java, EuclideanGraph.java, Point.java, and IndexPQ.java. However, your code should work with any of our three client programs. Submit all of the files needed to compile your program, except Turtle.java, StdIn.java, and In.java. Also, submit a readme.txt file. Describe and justify your approach. Compare your approach to the bare bones implementation. In particular give the average number of vertices examined.

92) Write a program to solve word searching puzzles, where words from a dictionary are to be found in a two-dimensional array of letters. For example, you might be given the following array: https://www.cs.princeton.edu/courses/archive/spring04/cos226/assignments/puzzle.html

m v j l i x a p e j h b x e e n p p h k t t h b s w y r w a i n u y z h p p f x r d z k q t p n l q o y j y a n h a p f g b g h x m s h w y l y u j f j h r s o a

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 25 Your program is to find words from the dictionary that can be spelled out in the puzzle by starting at any character, then moving in a straight line up, down, left, right, or on any of the four diagonals. For example, the above array contains the word algorithm because it can be spelled out by starting the lower right corner and moving up and to the left; and it contains the word syzygy because it can be spelled out by starting at the s on the third row and moving down.

The purpose of this assignment is to give you more experience working with strings and to give you an opportunity to put to work the algorithms design skills that you are learning.

Input format. From standard input, read the integer N, then N lines of N characters each (with each characters separated by one space), followed by the word list (one per line). You may assume that the list of dictionary words is in lexicographic order. You may also assume that both the puzzle and the dictionary consist of only lowercase letters. Finally, you may assume that all of the words in the dictionary are at least four letters long.

Output format. Print out every dictionary word (one per line) that is contained somewhere in the puzzle. If a word appears in the puzzle more than once, print it only once.

Approach. We have covered a number of different algorithms that can be used effectively to solve this problem. Your task is to study the problem; come up with a strategy for solving it using some of the algorithms and data structures that you have learned; implement and test your solution; and then explain and defend your design in the writeup. A good writeup is particularly important for this assignment, because we expect to see a variety of solution strategies. You need to clearly explain not just what you did, but also why you did it, backed up with estimates of resource costs. Also, you should clearly explain whatever limitations you need to place on the puzzle size N and the dictionary size M. As usual, your goal is to find a decent method which works within reasonable bounds. You need not waste effort squeezing time and space out of a bad algorithm or implementing complex or highly tuned code. This problem can be solved efficiently with 200 or so lines of code (including comments and basic error checking).

93) Write a program to factor huge integers. Read an integer N from the command line, then print it as the product of two integers (or note that it is prime) as in the following brute-force solution: You may use Java, Python or C/C++.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 26 #include #include main(int argc, char *argv[]) { int d; int N = atoi(argv[1]); for (d = 2; d < N/d; d++) { if (N % d == 0) break; } if (N % d == 0) printf("%d = %d*%d\n", N, d, N/d); else printf("%d is prime\n", N); }

This code simply checks each integer greater than 1 to see whether it divides evenly into N. The header limits.h gives access to constants like INT_MAX that are not used by this program, but which you may need to avoid overflow in your own code.

We stop after finding any factor since we know that we could find all factors, if desired, by using the same method for the factors.

The solution just given is not quite a brute-force solution because it already contains a test that improves performance by a substantial amount: If we do not find a factor by the time that we reach the square root of N, then we certainly will not find a factor larger than that value, and we can declare N to be prime. A truly naive brute-force implementation might use time proportional to N (try every integer less than N; this improvement improves the running time to be proportional to the square root of N, so we can use it to factor any 32-bit integer in a fraction of a second. In this assignment, we explore the problem of factoring larger integers.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 27 There are two reasons that the above code is not useful for factoring huge integers. First, the standard int data type supports 32-bit integers, so we would get overflow and/or incorrect results if we were to try to use it for larger numbers. Second, it is too slow. Even if we could deal with (say) 128-bit integers, we could never afford to try 2^64 divide operations to check for factors.

For this assignment, you will develop an implementation of a faster algorithm for factoring that is known as Pollard's rho method. The method is brought to us by the magic of number theory that is beyond the scope of this course, but it is an easy computation, based on iterating the function f(x) = x*x + c (mod N). Specifically, we start at some value x = x0 and maintain, for i = 1, 2, 3, ... , one variable a that tracks the result of i iterations of f and another variable b that tracks the result of 2i iterations of f, computing the greatest common divisor d of |a - b| and N. It turns out that whenever we find that d is not 1, we can infer that it is a factor of N, so we are done.

94) Write a program that can create an H-tree pattern, as illustrated below. Then develop a program that prints recursive patterns of your own design. https://introcs.cs.princeton.edu/java/assignments/htree.html The H-tree is another example of a fractal pattern like the Koch snowflake and Sierpinski triangle. It also of practical interest in circuit design. For example, imagine that we want to lay out circuit components on a microprocessor chip so that the length of wire connecting each component to the clock is the same. This property is desirable to achieve uniform wiring delay. The H-tree pattern is an elegant solution: position the clock in the center of the biggest H, and put each circuit component at one of the exposed endpoints of the smallest H's.

Part 1. Though the H-tree pattern looks complex, it can be generated with a short recursive program. Your task is to write a program HTree.java with a recursive function htree and a main driver that calls the recursive function once, and animates the results using StdDraw. Think recursively: your function should draw an H and calls itself 4 times (with an appropriate stopping condition).

Your program will read in a command line parameter N to control the depth of the recursion. First, make sure that your program can draw a single H, with N set to 1. Then, check that it draws five H's with N set to 2. Your program will be nearly (or completely) debugged when you

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 28 get to this point. Below are the target H-tree patterns with N set to 1, 2, 3, 4, 5 and 6, respectively.

Part 2. In this part you will create your own recursive design. First, do something different for your basic graphic design. For example, you can have the regions represented by the recursive calls be rectangles of varying size, or you can have them overlap. Or, work with X's or S's instead of H's. Or, use StdDraw.spot to produce filled circles, filled squares, images, or text. Or, use five recursive calls and pentagons, or whatever. Try using color or introducing some randomness.

95) Write a program to decipher messages encoded using a prefix code, given the encoding tree. Such codes are widely used in applications that compress data, including JPEG for images, MP3 for music, and DivX for video.

Prefix codes. A prefix code is most easily represented by a binary tree in which the external nodes are labeled with single characters that are combined to form the message. The encoding for a character is determined by following the path down from the root of the tree to the external node that holds that character: a 0 bit identifies a left branch in the path, and a 1 bit identifies a right branch. In the following tree, black circles are internal nodes and gray squares are external nodes. The code for b is 111, because the external node holding b is reached from the root by taking 3 consecutive right branches. The other codes are given in the table below. Prefix Tree

character encoding ------a 0 b 111 c 1011 d 1010 r 110 ! 100

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 29

Note that each character can be encoded with a different number of bits. In the example above, the character 'a' is encoded with a single bit, while the character 'd' is encoded with 4 bits. This is a fundamental property of prefix codes. In order for this encoding scheme to reduce the number of bits in a message, we use short encodings for frequently used characters, and long encodings for infrequent ones. A second fundamental property of prefix codes is that messages can be formed by simply stringing together the code bits from left to right. For example, the bitstring

0111110010110101001111100100 encodes the message "abracadabra!". The first 0 must encode 'a', then the next three 1's must encode 'b', then 110 must encode r, and so on as follows:

|0|111|110|0|1011|0|1010|0|111|110|0|100 a b r a c a d a b r a !

The codes can be run together because no encoding is a prefix of another one. This property defines a prefix code, and it allows us to represent the character encodings with a binary tree, as shown above. To decode a given bit string:

Start at the root of the tree. Repeat until you reach an external leaf node. Read one message bit. Take the left branch in the tree if the bit is 0; take the right branch if it is 1. Print the character in that external node.

This whole process is repeated, starting over at the root, until all of the bits in the compressed message are exhausted. Your main task is to parse the binary tree and implement this procedure.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 30 Representing the binary tree. To decode a bit string, you need the binary tree that stores the character encodings. We use the preorder traversal of the binary tree to represent the tree itself. Internal nodes are labeled with the special character '*'. (For convenience, we artificially restrict ourselves to messages that do not contain this special character.) The preorder traversal of the above tree is:

* a * * ! * d c * r b

Input format. The input will consist of the preorder traversal of the binary tree, followed immediately on a new line by the compressed message. For the example above, the input file is abra.pre:

*a**!*dc*rb 0111110010110101001111100100

In order to read the input one character at a time, use the library CharStdIn.java.

Part 1: Building the tree. Design a class PrefixTree to represent prefix trees. A PrefixTree should store a character (either an input symbol or the special character '*') and references to two subtrees. The beginning of your class might look like:

public class PrefixTree { private char character; private PrefixTree left; private PrefixTree right;

Design the constructor so that it reads in the preorder traversal of a tree from standard input, and reconstructs it.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 31 Part 2: Tree traversal. Include a method preorder that traverses the binary tree in preorder, and prints a list of characters in the tree, the length (number of bits) of their encoding, and the encoding. For the example above, your program should produce the following output.

character bits encoding ------a 1 0 ! 3 100 d 4 1010 c 4 1011 r 3 110 b 3 111

Part 3: Uncompressing. Now, write a method uncompress that reads the compressed message from standard input, and writes the uncompressed message to standard output. It should also display the number of bits read in, the number of characters in the original message, and the compression factor.

For example, the original message above contains 12 characters which would normally requires 96 bits of storage (8 bits per character). The compressed message uses only 28 bits, or 29% of the space required without compression. The compression factor depends on the frequency of characters in the message, but ratios around 50% are common for English text. Note that for large messages the amount of space needed to store the description of the tree is negligible compared to storing the message itself, so we have ignored this quantity in the calculation. Also, for simplicity, the compressed message is a sequence of the characters '0' and '1'. In an actual application, these bits would be packed eight to the byte, thus using 1/8th the space. For this input, your program should produce the following output:

character bits encoding ------a 1 0

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 32 ! 3 100 d 4 1010 c 4 1011 r 3 110 b 3 111

abracadabra! Number of bits = 28 Number of characters = 12 Compression ratio = 29.166666666666668%

96) Write a program to predict the performance of various stocks. https://www.cs.princeton.edu/courses/archive/fall10/cos126/assignments/stock.html Write the Program in Java, C/C++ or Python. Part 0: read in the data. The following program reads in a sequence of stock prices and prints them out.

#include int main(void) { float price; while (scanf("%f", &price) != EOF) printf("%7.3f\n", price); return 0; }

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 33

Type the program exactly as is; save as input.c; and compile with "gcc input.c". To read in the data from a file named stock15.txt, type "a.out < stock15.txt". You can also test your program on stock1000.txt, a larger file that contains real data.

Part 1: plot. Write a program plot.c to display the stock values graphically instead of just printing the values. Round the stock price down to the nearest integer, and print that number of *'s. The correct output is:

************************** ************************* ************************* ************************* ************************* *************************** **************************** ************************** ************************* ************************* ************************* ************************* ************************** ************************* *************************

Part 2: detect a pattern. Write a program to identify specific trends in the data. Dilbert the Day Trader believes that if the stock goes up 3 (or more) consecutive time periods and then down in the next period, then it is a good time to sell the stock. Analogously, Dilbert believes that if the stock goes down 3 consecutive time periods and then up in the next period, then it is a good time to buy the stock. Write a program pattern.c that prints out the time period and stock

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 34 price, along with the word buy or sell according to Dilbert's rule. The output should look like this:

1 26.375 2 25.500 3 25.125 4 25.000 5 25.250 buy 6 27.125 7 28.250 8 26.000 sell 9 25.500 10 25.000 11 25.125 buy 12 25.250 13 26.375 14 25.500 sell 15 25.500

Part 3: invest. Write a program invest.c to determine how much money you would have won or lost using Dilbert's rule. You start with $10,000.00 cash. Assume that you will convert all of your cash to stock when Dilbert's rule signals you to buy, and that you will convert all of your stock to cash when Dilbert's rule signals you to sell. For each time period, print out the price, cash, shares owned, and portfolio value. The value of your portfolio is cash plus the number of shares multiplied by the price per share. (For simplicity, assume that you can buy fractional amounts of stock, and there are no transaction fees.) For stock15.txt, the correct output is:

period price cash shares value

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 35 ------1 26.375 10000.00 0.00 10000.00 2 25.500 10000.00 0.00 10000.00 3 25.125 10000.00 0.00 10000.00 4 25.000 10000.00 0.00 10000.00 5 25.250 0.00 396.04 10000.00 6 27.125 0.00 396.04 10742.57 7 28.250 0.00 396.04 11188.12 8 26.000 10297.03 0.00 10297.03 9 25.500 10297.03 0.00 10297.03 10 25.000 10297.03 0.00 10297.03 11 25.125 0.00 409.83 10297.03 12 25.250 0.00 409.83 10348.26 13 26.375 0.00 409.83 10809.32 14 25.500 10450.72 0.00 10450.72 15 25.500 10450.72 0.00 10450.72

97) Implement the MD5 Message Digest Algorithm

98) Implement an Algorithm which detects an infinite loop in a linked list.

99) Implement AES Encryption and Decryption

100) Write a Program to convert a sorted array into a Binary Search tree.

This Set of Coding Problems was collected from Internet Public Sources for Teaching Purposes. - pg. 36