npueyo_hw2.tex 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2. % Short Sectioned Assignment
  3. % LaTeX Template
  4. % Version 1.0 (5/5/12)
  5. %
  6. % This template has been downloaded from:
  7. % http://www.LaTeXTemplates.com
  8. %
  9. % Original author:
  10. % Frits Wenneker (http://www.howtotex.com)
  11. %
  12. % License:
  13. % CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
  14. %
  15. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16. %----------------------------------------------------------------------------------------
  17. % PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
  18. %----------------------------------------------------------------------------------------
  19. \documentclass[paper=a4, fontsize=11pt]{scrartcl} % A4 paper and 11pt font size
  20. \usepackage[colorlinks=true, allcolors=red]{hyperref}
  21. \usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs
  22. %\usepackage{fourier} % Use the Adobe Utopia font for the document - comment this line to return to the LaTeX default
  23. \usepackage[english]{babel} % English language/hyphenation
  24. \usepackage{mathtools} % More complete math support in Latex than amsthm
  25. \usepackage{amsmath,amsfonts,amsthm} % Math packages
  26. \usepackage{amssymb} % Additional math symbols.
  27. \usepackage{graphicx} % Graphics with e.g. \includegraphics{file.png}.
  28. %\usepackage{subfigures} % Have multiple figures in one.
  29. \usepackage{caption} % Customize caption formatting.
  30. \usepackage{subcaption} % Subfigures.
  31. \usepackage{tabularx} % Width controlled tabulars.
  32. \usepackage{enumerate} % change appearance of enumerate
  33. \usepackage{sectsty} % Allows customizing section commands
  34. \allsectionsfont{\centering \normalfont\scshape} % Make all sections centered, the default font and small caps
  35. \usepackage{tikz}
  36. \usetikzlibrary{automata,positioning}
  37. \usepackage{fancyhdr} % Custom headers and footers
  38. \pagestyle{fancyplain} % Makes all pages in the document conform to the custom headers and footers
  39. \fancyhead{} % No page header - if you want one, create it in the same way as the footers below
  40. \fancyfoot[L]{} % Empty left footer
  41. \fancyfoot[C]{} % Empty center footer
  42. \fancyfoot[R]{\thepage} % Page numbering for right footer
  43. \renewcommand{\headrulewidth}{0pt} % Remove header underlines
  44. \renewcommand{\footrulewidth}{0pt} % Remove footer underlines
  45. \setlength{\headheight}{13.6pt} % Customize the height of the header
  46. \numberwithin{equation}{section} % Number equations within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
  47. \numberwithin{figure}{section} % Number figures within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
  48. \numberwithin{table}{section} % Number tables within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
  49. \setlength\parindent{0pt} % Removes all indentation from paragraphs - comment this line for an assignment with lots of text
  50. %\usepackage{mathtools}
  51. %\DeclarePairedDe\limiter{\ceil}{\lceil}{\rceil}
  52. %\DeclarePairedDe\limiter{\floor}{\lfloor}{\rfloor}
  53. \newcommand{\heads}{\textsc{h}}
  54. \newcommand{\tails}{\textsc{t}}
  55. \newcommand{\logten}{\log}%\mathrm{\log}\hspace{0.05in}}
  56. \newcommand{\logtwo}{\lg}%\mathrm{lg}\hspace{0.05in}}
  57. \newcommand{\loge}{\ln}%\mathrm{ln}\hspace{0.05in}}
  58. \theoremstyle{definition}
  59. \newtheorem*{solution}{Solution}
  60. \usepackage{algpseudocode, algorithm}
  61. %----------------------------------------------------------------------------------------
  62. % TIKZ SECTION
  63. %----------------------------------------------------------------------------------------
  64. \usetikzlibrary{arrows}
  65. \tikzset{
  66. treenode/.style = {align=center, inner sep=0pt, text centered,
  67. font=\sffamily},
  68. arn_n/.style = {treenode, circle, black, font=\sffamily\bfseries, draw=black,
  69. text width=1.5em, very thick},% arbre rouge noir, noeud noir
  70. %arn_r/.style = {treenode, circle, red, draw=red,
  71. % text width=1.5em, very thick},% arbre rouge noir, noeud rouge
  72. arn_x/.style = {treenode, rectangle, draw=white,
  73. minimum width=0.5em, minimum height=0.5em}% arbre rouge noir, nil
  74. }
  75. %----------------------------------------------------------------------------------------
  76. % TITLE SECTION
  77. %----------------------------------------------------------------------------------------
  78. \newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height
  79. \title{
  80. \normalfont \normalsize
  81. \textsc{ECS 60 \hfill Dept. of Computer Science, UC Davis \hfill Winter 2018} % Your university, school and/or department name(s)
  82. \horrule{0.5pt} \\[0.4cm] % Thin top horizontal rule
  83. \huge Homework \#2 Due 2/4/18 by 11:59pm\footnote{Last updated \today} \\ % The assignment title
  84. \horrule{2pt} \\[0.5cm] % Thick bottom horizontal rule
  85. }
  86. \author{Natalie Pueyo Svoboda, 997466498} % Put your name here
  87. \date{\today}
  88. \begin{document}
  89. \maketitle
  90. Homeworks are to be submitted to Gradescope by the above due date. List your classmate collaborators on the front page. The quiz will occur in-class on Wednesday, 2/7/18. Problems come from:
  91. \begin{description}
  92. \item[Weiss] "Data Structures and Algorithm Analysis in C++"
  93. \item[Sedgewick \& Wayne] "Algorithms"
  94. \end{description}
  95. \begin{itemize}
  96. \item (Weiss) We are given an array that contains N numbers. We want to determine if there are two numbers whose sum equals a given number K. For instance, if the input is 8, 4, 1, 6, and K is 10, then the answer is yes (4 and 6). A number may be used twice. First, give an $O(n^2)$ algorithm to solve this problem. Then give the pseudocode of an $O(n \log n)$ algorithm to solve this problem (Hint: sort first).
  97. \item (Weiss) Give the pseudocode of a data structure that supports the stack \texttt{push} and \texttt{pop} operations, and a third operation \texttt{findMin}, which returns the smallest element in the data structure, all in $O(1)$ worst-case time.
  98. \item (Sedgewick \& Wayne) Inserting the keys in the order $A X C S E R H$ into an initially empty binary search tree gives a worst-case tree where every node has one null link, except one at the bottom, which has two null links. Give five other orderings of these keys that produce worst-case trees.
  99. \item (Sedgewick \& Wayne) Suppose that a certain binary search tree has keys that are integers between 1 and 10, and we search for 5. Which sequence below cannot be the sequence of keys examined?
  100. \begin{itemize}
  101. \item[a.] 10, 9, 8, 7, 6, 5
  102. \item[b.] 4, 10, 8, 7, 5
  103. \item[c.] 1, 10, 2, 9, 3, 8, 4, 7, 6, 5
  104. \item[d.] 2, 7, 3, 8, 4, 5
  105. \item[e.] 1, 2, 10, 4, 8, 5
  106. \end{itemize}
  107. \item (Sedgewick \& Wayne) Give pseudocode for a binary search tree method \texttt{height()} that computes the height of the tree. Develop two implementations: the first, a recursive method (which takes linear time and space proportional to the height), and the second, a method that adds a field to each node in the tree (and takes linear space and constant time per query).
  108. \end{itemize}
  109. \section{First Problem}
  110. \begin{solution}
  111. \begin{enumerate}[a)]
  112. \item A $\mathcal{O}(n^2)$ algorithm that could be used to solve this problem would involve two \texttt{for} loops with an \texttt{if} statement.
  113. The first \texttt{for} loop would be used to through the array one element at a time to get the first number in the sum.
  114. The second \texttt{for} loop would be nested in the first \texttt{for} loop and would also go through each element in the array to provide the second number in the sum.
  115. Lastly, there would be an \texttt{if} statement inside the second for loop that would check if each sum is equal to the given $K$ value.
  116. \item On the other hand, a $\mathcal{O}(n \cdotp log(n))$ algorithm in pseudocode to do the same thing could be:
  117. \begin{verbatim}
  118. low := 0;
  119. high := N - 1;
  120. sort(array);
  121. for(i := 0; j < N; j := j + 1)
  122. mid = floor((low + high) / 2);
  123. if(array[mid] = (K - array[i]))
  124. print("A match was found");
  125. break;
  126. else if(array[mid] < (K - array[i]))
  127. low := mid + 1;
  128. else
  129. high := mid - 1;
  130. \end{verbatim}
  131. % https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/a/implementing-binary-search-of-an-array
  132. %for (j = 0; j < N; j++)
  133. % perform binary search for (K – array[j]) (O(logN)
  134. % if found print Yes, stop
  135. % if no search is successful, print No
  136. \end{enumerate}
  137. \end{solution}
  138. \section{Second Problem}
  139. \begin{solution}
  140. The way to implement a data structure that supports the stack \texttt{push()},\texttt{pop()}, and \texttt{findMin()} is to use to stacks.
  141. The first is used as the 'normal' stack which saves each new value.
  142. The second stack, \texttt{minStack}, is used to save the history of the minimum values as they are pushed onto the stack.
  143. \begin{verbatim}
  144. class stackWithMin{
  145. Stack stack;
  146. Stack minStack;
  147. void listPrepend(Stack, item);
  148. void listRemoveAfter(Stack, int);
  149. void push(item);
  150. int pop();
  151. int findMin();
  152. }swm;
  153. push(newItem){
  154. swm.listPrepend(swm.stack, newItem);
  155. if newItem <= swm.minStack->head then
  156. swm.listPrepend(swm.minStack, newItem);
  157. }
  158. pop(){
  159. poppedItem := swm.stack->head;
  160. swm.listRemoveAfter(swm.stack, 0);
  161. if poppedItem = swm.minStack->head then
  162. swm.listRemoveAfter(swm.minStack, 0);
  163. return PoppedItem;
  164. }
  165. findMin(){
  166. minValue := swm.minStack->head;
  167. return minValue;
  168. }
  169. \end{verbatim}
  170. % zybooks 2.11
  171. % https://www.geeksforgeeks.org/design-and-implement-special-stack-data-structure/
  172. \end{solution}
  173. \section{Third Problem}
  174. \begin{solution}
  175. The following are five ways to order the keys $A X C S E R H$ so as to give worst-case BST:
  176. \begin{enumerate}[a)]
  177. \item $A C E H R S X$
  178. \item $A C E X S R H$
  179. \item $A C X E S H R$
  180. \item $X S R H E C A$
  181. \item $X A S C R E H$
  182. \end{enumerate}
  183. \end{solution}
  184. \section{Fourth Problem}
  185. \begin{solution}
  186. Out of the following sequences, only \textbf{(d)} would not be a possible sequence of examining a BST.
  187. This is because in case \textbf{(d)}, at the second level node 7 would be parent node to \textbf{both} nodes 3 and 8 according to BST rules.
  188. In this case, when searching for the value 5, by BST rules, the search would not traverse to another branch (see figure).
  189. \begin{enumerate}[a)]
  190. \item 10, 9, 8, 7, 6, 5
  191. \item 4, 10, 8, 7, 5
  192. \item 1, 10, 2, 9, 3, 8, 4, 7, 6, 5
  193. \item 2, 7, 3, 8, 4, 5 (Does not work)
  194. \item 1, 2, 10, 4, 8, 5
  195. \end{enumerate}
  196. \begin{tikzpicture}[->,>=stealth',level/.style={sibling distance = 5cm/#1,
  197. level distance = 1.5cm}]
  198. \node [arn_n] {2}
  199. child{ node [arn_x] {}
  200. child{ node [arn_x] {}
  201. child{ node [arn_x] {}}
  202. child{ node [arn_x] {}}
  203. }
  204. child{ node [arn_x] {}
  205. child{ node [arn_x] {}}
  206. child{ node [arn_x] {}}
  207. }
  208. }
  209. child{ node [arn_n] {7}
  210. child{ node [arn_n] {3}
  211. child{ node [arn_x] {}}
  212. child{ node [arn_n] {4}
  213. child{ node [arn_x] {}}
  214. child{ node [arn_n] {5}
  215. }
  216. } %for a named pointer
  217. }
  218. child{ node [arn_n] {8}
  219. child{ node [arn_x] {}}
  220. child{ node [arn_x] {}}
  221. }
  222. };
  223. \end{tikzpicture}
  224. \end{solution}
  225. \section{Fifth Problem}
  226. \begin{solution}
  227. The first implementation with linear time and space proportional to the height:
  228. \begin{verbatim}
  229. int height(tree){
  230. left, right := 0;
  231. if tree = null then
  232. return -1;
  233. else
  234. if tree.leftbranch != null then
  235. left = height(tree.leftbranch);
  236. if tree.rightbranch != null then
  237. right = height(tree.rightbranch);
  238. return max(left, right) + 1;
  239. }
  240. \end{verbatim}
  241. The second implementation with linear space and constant time per query.
  242. This one requires that I also implement a way to add a field to a node.
  243. In this case, the \texttt{insert()} method recalculates each node height value using recursion after a new node is inserted.
  244. When the \texttt{height()} method is called, the method returns the value found at the pointer to the height of the root calculated in \texttt{insert()}.
  245. \begin{verbatim}
  246. node* insert(node* root, node* newNode){
  247. if root = null then
  248. newNode->height := 1;
  249. return newNode;
  250. if root->value < newNode->value then
  251. root->right := insert(root->right, newNode);
  252. else
  253. root->left := insert(root->left, newNode);
  254. // height at root starts at 1 so add that to calculation
  255. root->height := max(root->left->height, root->right->height) + 1;
  256. return root;
  257. }
  258. height(tree){
  259. heightOfTree->root;
  260. return heightOfTree;
  261. }
  262. \end{verbatim}
  263. \end{solution}
  264. \end{document}