├── .gitignore
├── InterviewPrep.sln
├── InterviewPrep
├── App.config
├── InterviewPrep.csproj
├── Properties
│ └── AssemblyInfo.cs
├── TODO.txt
├── Util.cs
├── chapter01
│ ├── question0101.cs
│ ├── question0103.cs
│ ├── question0104.cs
│ ├── question0105.cs
│ ├── question0106.cs
│ ├── question0107.cs
│ └── question0108.cs
├── chapter02
│ ├── Node.cs
│ ├── question0201.cs
│ ├── question0202.cs
│ ├── question0203.cs
│ ├── question0204.cs
│ ├── question0205.cs
│ ├── question0206.cs
│ └── question0207.cs
├── chapter03
│ ├── Queue.cs
│ ├── Stack.cs
│ ├── question0301.cs
│ ├── question0302.cs
│ ├── question0303.cs
│ ├── question0304.cs
│ ├── question0305.cs
│ ├── question0306.cs
│ └── question0307.cs
├── chapter04
│ ├── Tree.cs
│ ├── question0401.cs
│ ├── question0402.cs
│ ├── question0403.cs
│ ├── question0404.cs
│ ├── question0405.cs
│ ├── question0407.cs
│ ├── question0409.cs
│ └── qusetion0406.cs
├── chapter05
│ ├── BitUtil.cs
│ ├── question0501.cs
│ ├── question0502.cs
│ ├── question0503.cs
│ ├── question0505.cs
│ ├── question0506.cs
│ └── question0507.cs
├── chapter09
│ ├── question0901.cs
│ ├── question0902.cs
│ ├── question0903.cs
│ ├── question0904.cs
│ ├── question0905.cs
│ ├── question0906.cs
│ ├── question0907.cs
│ ├── question0908.cs
│ ├── question0909.cs
│ └── question0910.cs
├── chapter11
│ ├── question1101.cs
│ ├── question1102.cs
│ ├── question1103.cs
│ ├── question1105.cs
│ └── question1107.cs
├── chapter17
│ ├── question1701.cs
│ ├── question1702.cs
│ ├── question1703.cs
│ ├── question1704.cs
│ ├── question1705.cs
│ ├── question1706.cs
│ ├── question1708.cs
│ ├── question1711.cs
│ └── question1712.cs
├── chapter18
│ ├── question1801.cs
│ ├── question1802.cs
│ └── question1806.cs
└── common
│ ├── CombinationPermutation.cs
│ ├── LowestCommonAncestor .cs
│ ├── MaxSubarray.cs
│ ├── MergeSort.cs
│ ├── PriorityQueue.cs
│ ├── QuickSort.cs
│ └── ReverseWords.cs
└── Test
├── Properties
└── AssemblyInfo.cs
├── Test.csproj
└── UnitTest1.cs
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.sln.docstates
8 |
9 | # Build results
10 |
11 | [Dd]ebug/
12 | [Rr]elease/
13 | x64/
14 | build/
15 | [Bb]in/
16 | [Oo]bj/
17 |
18 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
19 | !packages/*/build/
20 |
21 | # MSTest test Results
22 | [Tt]est[Rr]esult*/
23 | [Bb]uild[Ll]og.*
24 |
25 | *_i.c
26 | *_p.c
27 | *.ilk
28 | *.meta
29 | *.obj
30 | *.pch
31 | *.pdb
32 | *.pgc
33 | *.pgd
34 | *.rsp
35 | *.sbr
36 | *.tlb
37 | *.tli
38 | *.tlh
39 | *.tmp
40 | *.tmp_proj
41 | *.log
42 | *.vspscc
43 | *.vssscc
44 | .builds
45 | *.pidb
46 | *.log
47 | *.scc
48 |
49 | # Visual C++ cache files
50 | ipch/
51 | *.aps
52 | *.ncb
53 | *.opensdf
54 | *.sdf
55 | *.cachefile
56 |
57 | # Visual Studio profiler
58 | *.psess
59 | *.vsp
60 | *.vspx
61 |
62 | # Guidance Automation Toolkit
63 | *.gpState
64 |
65 | # ReSharper is a .NET coding add-in
66 | _ReSharper*/
67 | *.[Rr]e[Ss]harper
68 |
69 | # TeamCity is a build add-in
70 | _TeamCity*
71 |
72 | # DotCover is a Code Coverage Tool
73 | *.dotCover
74 |
75 | # NCrunch
76 | *.ncrunch*
77 | .*crunch*.local.xml
78 |
79 | # Installshield output folder
80 | [Ee]xpress/
81 |
82 | # DocProject is a documentation generator add-in
83 | DocProject/buildhelp/
84 | DocProject/Help/*.HxT
85 | DocProject/Help/*.HxC
86 | DocProject/Help/*.hhc
87 | DocProject/Help/*.hhk
88 | DocProject/Help/*.hhp
89 | DocProject/Help/Html2
90 | DocProject/Help/html
91 |
92 | # Click-Once directory
93 | publish/
94 |
95 | # Publish Web Output
96 | *.Publish.xml
97 | *.pubxml
98 |
99 | # NuGet Packages Directory
100 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line
101 | #packages/
102 |
103 | # Windows Azure Build Output
104 | csx
105 | *.build.csdef
106 |
107 | # Windows Store app package directory
108 | AppPackages/
109 |
110 | # Others
111 | sql/
112 | *.Cache
113 | ClientBin/
114 | [Ss]tyle[Cc]op.*
115 | ~$*
116 | *~
117 | *.dbmdl
118 | *.[Pp]ublish.xml
119 | *.pfx
120 | *.publishsettings
121 |
122 | # RIA/Silverlight projects
123 | Generated_Code/
124 |
125 | # Backup & report files from converting an old project file to a newer
126 | # Visual Studio version. Backup files are not needed, because we have git ;-)
127 | _UpgradeReport_Files/
128 | Backup*/
129 | UpgradeLog*.XML
130 | UpgradeLog*.htm
131 |
132 | # SQL Server files
133 | App_Data/*.mdf
134 | App_Data/*.ldf
135 |
136 | # =========================
137 | # Windows detritus
138 | # =========================
139 |
140 | # Windows image file caches
141 | Thumbs.db
142 | ehthumbs.db
143 |
144 | # Folder config file
145 | Desktop.ini
146 |
147 | # Recycle Bin used on file shares
148 | $RECYCLE.BIN/
149 |
150 | # Mac crap
151 | .DS_Store
152 |
--------------------------------------------------------------------------------
/InterviewPrep.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2012
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InterviewPrep", "InterviewPrep\InterviewPrep.csproj", "{698DBB7D-CD16-4A01-BBC3-20167D7A714B}"
5 | EndProject
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test", "Test\Test.csproj", "{61FAF64B-22CF-4A48-A6F5-178E4E022F2A}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {698DBB7D-CD16-4A01-BBC3-20167D7A714B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {698DBB7D-CD16-4A01-BBC3-20167D7A714B}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {698DBB7D-CD16-4A01-BBC3-20167D7A714B}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {698DBB7D-CD16-4A01-BBC3-20167D7A714B}.Release|Any CPU.Build.0 = Release|Any CPU
18 | {61FAF64B-22CF-4A48-A6F5-178E4E022F2A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {61FAF64B-22CF-4A48-A6F5-178E4E022F2A}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {61FAF64B-22CF-4A48-A6F5-178E4E022F2A}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {61FAF64B-22CF-4A48-A6F5-178E4E022F2A}.Release|Any CPU.Build.0 = Release|Any CPU
22 | EndGlobalSection
23 | GlobalSection(SolutionProperties) = preSolution
24 | HideSolutionNode = FALSE
25 | EndGlobalSection
26 | EndGlobal
27 |
--------------------------------------------------------------------------------
/InterviewPrep/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/InterviewPrep/InterviewPrep.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {698DBB7D-CD16-4A01-BBC3-20167D7A714B}
8 | Exe
9 | Properties
10 | InterviewPrep
11 | InterviewPrep
12 | v4.5
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
136 |
--------------------------------------------------------------------------------
/InterviewPrep/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("InterviewPrep")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("InterviewPrep")]
13 | [assembly: AssemblyCopyright("Copyright © 2013")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("4666da79-15bc-4a1e-b308-300f0137744d")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/InterviewPrep/TODO.txt:
--------------------------------------------------------------------------------
1 | question 0206
2 | question 0409
3 | question 0507
4 | question 0508
5 | question 0704
6 | question 0705
7 | question 0706
8 | question 0707
9 | chapter 8
10 | question 0906
11 | question 0911
12 | question 1106
13 | question 1108
14 | question 1704
15 | question 1714
16 | question 1804
17 | question 1806//selection rank
18 | question 1807
19 |
20 |
21 | 0205
22 | 0206
23 | 0207
24 | 0306
25 | 0409*
26 | 0704*
27 | 0705*
28 | 0706*
29 | 0707*
30 |
--------------------------------------------------------------------------------
/InterviewPrep/Util.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep
8 | {
9 | public class Util
10 | {
11 | public static void Print2DArray(int[][] a)
12 | {
13 | for (int i = 0; i < a.Length; i++)
14 | {
15 | for (int j = 0; j < a[i].Length; j++)
16 | Console.Write((a[i][j]) + " ");
17 | Console.WriteLine();
18 | }
19 | }
20 |
21 | public static void Print2DArray(int[,] a)
22 | {
23 | for (int i = 0; i < a.GetLength(0); i++)
24 | {
25 | for (int j = 0; j < a.GetLength(1); j++)
26 | Console.Write((a[i,j]) + " ");
27 | Console.WriteLine();
28 | }
29 | }
30 |
31 |
32 |
33 | public static void PrintArray(T[] a)
34 | {
35 | for (int i = 0; i < a.Length; i++)
36 | {
37 | Console.WriteLine(a[i]);
38 | }
39 | }
40 |
41 | public static void PrintArray(List a)
42 | {
43 | for (int i = 0; i < a.Count; i++)
44 | {
45 | Console.WriteLine(a.ElementAt(i));
46 | }
47 | }
48 |
49 | public static void PrintSet(HashSet s)
50 | {
51 | Console.Write("{ ");
52 | foreach(int i in s)
53 | {
54 | Console.Write(i+" ");
55 | }
56 | Console.WriteLine("}");
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter01/question0101.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter01
8 | {
9 | class question0101
10 | {
11 | static void NotMain(string[] args)
12 | {
13 | Console.WriteLine(HasUniqueCharactersSpaceEfficient("haha"));
14 | Console.WriteLine(HasUniqueCharactersSpaceEfficient("helo wd"));
15 |
16 | Console.Read();
17 | }
18 |
19 | static bool HasUniqueCharacters(String s)
20 | {
21 | if (s.Length > 256)
22 | return false;
23 | char[] cArray = s.ToCharArray();
24 | char[] count = new char[256];
25 | for (int i = 0; i < cArray.Length; i++)
26 | {
27 | count[cArray[i]]++;
28 | if (count[cArray[i]] == 2)
29 | return false;
30 | }
31 | return true;
32 | }
33 |
34 | static bool HasUniqueCharactersSpaceEfficient(String s)
35 | {
36 | if (s.Length > 256)
37 | return false;
38 | char[] cArray = s.ToCharArray();
39 | for(int i = 0;i s.Length)
40 | return s;
41 | return sb.ToString();
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter01/question0106.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter01
8 | {
9 | class question0106
10 | {
11 |
12 | static void NotMain(String[] args)
13 | {
14 | int[][] image = new int[][] {new int[]{1,2,3},new int[]{8,-1,4},new int[]{7,6,5}};
15 | RotateImage(image);
16 | Util.Print2DArray(image);
17 |
18 | Console.Read();
19 |
20 | }
21 |
22 | static int[][] RotateImage(int[][] image)
23 | {
24 | int size = image.Length;
25 | int start = 0;
26 | int end = size - 1;
27 | int level = 0;
28 | while (start < end)
29 | {
30 | for (int i = start; i < end; i++)
31 | {
32 | int[] r1 = GetRotatedXY(i, level,size);
33 | int temp = image[r1[1]][r1[0]];
34 | image[r1[1]][r1[0]] = image[level][i];
35 | Console.WriteLine("r1: " + r1[0]+" "+r1[1]);
36 |
37 | int[] r2 = GetRotatedXY(r1[0], r1[1],size);
38 | int temp2 = image[r2[1]][r2[0]];
39 | image[r2[1]][r2[0]] = temp;
40 | temp = temp2;
41 |
42 | int[] r3 = GetRotatedXY(r2[0], r2[1],size);
43 | image[level][i] = image[r3[1]][r3[0]];
44 | image[r3[1]][r3[0]] = temp;
45 | }
46 | level++;
47 | start++;
48 | end--;
49 | }
50 | return image;
51 | }
52 |
53 | static int[] GetRotatedXY(int x, int y, int size)
54 | {
55 | return new int[] { size - y-1, x };
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter01/question0107.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter01
8 | {
9 | class question0107
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | int[][] a = new int[][] {new int[]{0,0,3},new int[]{8,0,4},new int[]{7,6,5}};
14 | SetZero(a);
15 | Util.Print2DArray(a);
16 |
17 | Console.Read();
18 | }
19 |
20 | static void SetZero(int[][] m)
21 | {
22 | bool[] row = new bool[m.Length];
23 | bool[] col = new bool[m[0].Length];
24 | for (int i = 0; i < m.Length; i++)
25 | for (int j = 0; j < m[i].Length; j++)
26 | if (m[i][j] == 0)
27 | {
28 | row[i] = true;
29 | col[j] = true;
30 | }
31 | for (int i = 0; i < row.Length; i++)
32 | if (row[i])
33 | for (int j = 0; j < m[i].Length; j++)
34 | m[i][j] = 0;
35 | for (int i = 0; i < col.Length; i++)
36 | if (col[i])
37 | for (int j = 0; j < m.Length; j++)
38 | m[j][i] = 0;
39 | }
40 | }
41 |
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter01/question0108.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter01
8 | {
9 | class question0108
10 | {
11 | //Solution is trivial.
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter02/Node.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter02
8 | {
9 | class Node
10 | {
11 | public Node next = null;
12 | public int data;
13 |
14 | public Node(int d)
15 | {
16 | data = d;
17 | }
18 |
19 | void appendToTail(int d)
20 | {
21 | Node end = new Node(d);
22 | Node n = this;
23 | while (n.next != null)
24 | n = n.next;
25 | n.next = end;
26 | }
27 |
28 | public static Node createLinkedList(int[] nums)
29 | {
30 | Node n = new Node(nums[0]);
31 | Node head = n;
32 | for (int i = 1; i < nums.Length; i++)
33 | {
34 | Node next = new Node(nums[i]);
35 | n.next = next;
36 | n = next;
37 | }
38 | return head;
39 | }
40 |
41 | public static void printNodes(Node head)
42 | {
43 | while (head != null)
44 | {
45 | Console.Write(head.data);
46 | Console.Write(" -> ");
47 | head = head.next;
48 | }
49 | Console.Write("null\n");
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter02/question0201.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter02
8 | {
9 | class question0201
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | Node t = Node.createLinkedList(new int[] { 1, 2, 3, 4,4,2,4,1,2,4 });
14 | Node.printNodes(t);
15 | removeDuplicateNoStorage(t);
16 | Node.printNodes(t);
17 | Console.Read();
18 | }
19 |
20 | static void removeDuplicate(Node n)
21 | {
22 | HashSet set = new HashSet();
23 | Node next = n.next;
24 | if(next == null)
25 | return;
26 | set.Add(n.data);
27 |
28 | while (next != null)
29 | {
30 | if (set.Contains(next.data))
31 | {
32 | n.next = next.next;
33 | }
34 | else
35 | {
36 | set.Add(next.data);
37 | n = n.next;
38 | }
39 | next = next.next;
40 | }
41 | }
42 |
43 | static void removeDuplicateNoStorage(Node n)
44 | {
45 | Node current = n;
46 | while (current != null)
47 | {
48 | Node runner = current;
49 | while (runner.next != null)
50 | {
51 | if (current.data == runner.next.data)
52 | runner.next = runner.next.next;
53 | else
54 | runner = runner.next;
55 | }
56 | current = current.next;
57 | }
58 | }
59 |
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter02/question0202.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter02
8 | {
9 | class question0202
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | Node t = Node.createLinkedList(new int[] {0 });
14 | Node.printNodes(t);
15 | Console.WriteLine(kthToLast(1,t));
16 | Console.Read();
17 | }
18 |
19 | static int kthToLast(int k, Node head)
20 | {
21 | Node current = head;
22 | Node runner = head;
23 | for (int i = 0; i < k; i++)
24 | {
25 | if (runner == null)
26 | return -1;
27 | runner = runner.next;
28 | }
29 | if (runner == null)
30 | return -1;
31 | while (runner.next != null)
32 | {
33 | runner = runner.next;
34 | current = current.next;
35 | }
36 | return current.data;
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter02/question0203.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter02
8 | {
9 | class question0203
10 | {
11 |
12 | static void delete(Node n)
13 | {
14 | if (n == null || n.next == null)
15 | return;
16 | n.data = n.next.data;
17 | n.next = n.next.next;
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter02/question0204.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter02
8 | {
9 | class question0204
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | Node l = Node.createLinkedList(new int[] { 3, 1, 2, 4, 5, 9, 7, 8, 6 });
14 | Node.printNodes(partition(9, l));
15 | Console.Read();
16 | }
17 |
18 | static Node partition(int n, Node head)
19 | {
20 | Node pointer = head;
21 | Node sHead = new Node(-1);
22 | Node bHead = new Node(-1);
23 | Node sPointer = sHead;
24 | Node bPointer = bHead;
25 | while (pointer != null)
26 | {
27 | if (pointer.data >= n)
28 | {
29 | bPointer.next = pointer;
30 | bPointer = bPointer.next;
31 | }
32 | else
33 | {
34 | sPointer.next = pointer;
35 | sPointer = sPointer.next;
36 | }
37 | pointer = pointer.next;
38 | }
39 | bPointer.next = null;//Important!
40 | sPointer.next = bHead.next;
41 | return sHead.next;
42 | }
43 |
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter02/question0205.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter02
8 | {
9 | class question0205
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | Node l = Node.createLinkedList(new int[] { 9,8, 1, 7 });
14 | Node r = Node.createLinkedList(new int[] { 2, 9, 5 });
15 | Node.printNodes(addListsReverse(l, r));
16 | Console.Read();
17 | }
18 |
19 | static Node addLists(Node n1, Node n2, bool carry)
20 | {
21 | if (n1 == null && n2 == null && !carry)
22 | return null;
23 |
24 | int result = 0;
25 | if (n1 != null)
26 | result += n1.data;
27 | if (n2 != null)
28 | result += n2.data;
29 | if (carry)
30 | result++;
31 |
32 | if (result >= 10)
33 | {
34 | carry = true;
35 | result -= 10;
36 | }
37 | else
38 | carry = false;
39 |
40 | Node n = new Node(result);
41 |
42 | n.next = addLists(n1 == null ? null : n1.next, n2 == null ? null : n2.next, carry);
43 | return n;
44 | }
45 |
46 |
47 |
48 | static Node addListsReverse(Node n1, Node n2)
49 | {
50 | int length1 = 0;
51 | int length2 = 0;
52 | Node r1 = n1;
53 | Node r2 = n2;
54 | while (r1 != null)
55 | {
56 | length1++;
57 | r1 = r1.next;
58 | }
59 | while (r2 != null)
60 | {
61 | length2++;
62 | r2 = r2.next;
63 | }
64 | n2 = pad(length1, length2, n1, n2);
65 | n1 = pad(length2, length1, n2, n1);
66 | NodeWrapper result = addReverseRecur(n1, n2);
67 | if (result.carry == 1)
68 | {
69 | Node nn = new Node(1);
70 | nn.next = result.n;
71 | return nn;
72 | }
73 | else
74 | {
75 | return result.n;
76 | }
77 | }
78 |
79 | static NodeWrapper addReverseRecur(Node n1, Node n2)
80 | {
81 | if (n1 == null && n2 == null)
82 | return new NodeWrapper(0, null);
83 |
84 | NodeWrapper wrapper = addReverseRecur(n1.next, n2.next);
85 | int result = wrapper.carry + n1.data + n2.data;
86 | int carry = 0;
87 | if (result >= 10)
88 | {
89 | result -= 10;
90 | carry = 1;
91 | }
92 | Node current = new Node(result);
93 | current.next = wrapper.n;
94 | return new NodeWrapper(carry, current);
95 | }
96 |
97 |
98 |
99 | static Node pad(int r1, int r2, Node n1, Node n2)
100 | {
101 | if (r1 <= r2)
102 | return n2;
103 | int diff = r1 - r2;
104 | Node padding = new Node(0);
105 | Node paddingHead = padding;
106 | for (int i = 1; i < diff; i++)
107 | {
108 | padding.next = new Node(0);
109 | padding = padding.next;
110 | }
111 | padding.next = n2;
112 | return paddingHead;
113 | }
114 |
115 | class NodeWrapper
116 | {
117 | public int carry;
118 | public Node n;
119 | public NodeWrapper(int carry, Node n)
120 | {
121 | this.carry = carry;
122 | this.n = n;
123 | }
124 | }
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter02/question0206.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter02
8 | {
9 | class question0206
10 | {
11 | static Node getLoopBeginning(Node head)
12 | {
13 | Node fast = head;
14 | Node slow = head;
15 |
16 | while (fast != null && fast.next != null)
17 | {
18 | slow = slow.next;
19 | fast = fast.next.next;
20 | if (slow == fast)
21 | break;
22 | }
23 |
24 | if (fast == null || fast.next == null)
25 | return null;
26 |
27 | slow = head;
28 | while (slow != fast)
29 | {
30 | slow = slow.next;
31 | fast = fast.next;
32 | }
33 | return fast;
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter02/question0207.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter02
8 | {
9 | class question0207
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | Node n = Node.createLinkedList(new int[]{1,2,3,1,1});
14 | Console.WriteLine(isPalindrome(n));
15 | Console.Read();
16 | }
17 |
18 | static Boolean isPalindrome(Node n)
19 | {
20 | Node fastRunner = n;
21 | Node slowRunner = n;
22 | Stack stack = new Stack();
23 | while (fastRunner != null && fastRunner.next != null)
24 | {
25 | fastRunner = fastRunner.next.next;
26 | stack.Push(slowRunner.data);
27 | slowRunner = slowRunner.next;
28 | }
29 | if (fastRunner != null && fastRunner.next == null)//Odd number of nodes
30 | if (stack.Count > 0)//Check case of only one node
31 | stack.Pop();
32 |
33 | while (stack.Count > 0)
34 | {
35 | int num = stack.Pop();
36 | if (num != slowRunner.data)
37 | return false;
38 | slowRunner = slowRunner.next;
39 | }
40 | return true;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter03/Queue.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter03
8 | {
9 | class Queue
10 | {
11 | Node first = null;
12 | Node last = null;
13 |
14 | public void enqueue(int i)
15 | {
16 | Node n = new Node(i);
17 | if(last == null)
18 | {
19 | last = n;
20 | first = n;
21 | return;
22 | }
23 | last.next = n;
24 | last = last.next;
25 | }
26 |
27 | public Node dequeue()
28 | {
29 | if (first == null)
30 | return null;
31 | Node n = first;
32 | first = first.next;
33 | if (first == null)
34 | last = null;
35 | return n;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter03/Stack.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter03
8 | {
9 |
10 | public class Stack
11 | {
12 | public Node top = null;
13 | public virtual void Push(int i)
14 | {
15 | Node n = new Node(i);
16 | n.next = top;
17 | top = n;
18 | }
19 |
20 | public virtual void Push(Node n)
21 | {
22 | n.next = top;
23 | top = n;
24 | }
25 |
26 | public virtual Node Pop()
27 | {
28 | if (top == null)
29 | return null;
30 | Node n = top;
31 | top = top.next;
32 | return n;
33 | }
34 |
35 | public override string ToString()
36 | {
37 | StringBuilder s = new StringBuilder();
38 | Node temp = top;
39 | while (temp != null)
40 | {
41 | s.Append(temp.data + " ");
42 | temp = temp.next;
43 | }
44 | return s.ToString();
45 | }
46 |
47 | public bool IsEmpty()
48 | {
49 | return top == null;
50 | }
51 |
52 | public Node Peek()
53 | {
54 | return top;
55 | }
56 |
57 | public int GetSize()
58 | {
59 | int count = 0;
60 | Node temp = top;
61 | while (temp != null)
62 | {
63 | count++;
64 | temp = temp.next;
65 | }
66 | return count;
67 | }
68 | }
69 |
70 | public class Node
71 | {
72 | public int data;
73 | public Node next;
74 | public Node(int i)
75 | {
76 | data = i;
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter03/question0301.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter03
8 | {
9 | class question0301
10 | {
11 | //This implementation allows the stacks to have different sizes.
12 | //The size of each stack expands when the stack is full and there is extra space in the array.
13 | //Shrinking of stack size is not yet implemented.
14 | static void NotMain(String[] args)
15 | {
16 | MultipleStack s = new MultipleStack(3, 20);
17 | s.Push(10, 1);
18 | s.Push(111, 0);
19 | s.Push(11, 1);
20 | s.Push(1, 2);
21 | s.Push(2, 2);
22 | s.Push(12, 1);
23 | s.Push(13, 1);
24 | s.Push(3, 2);
25 | s.Push(14, 1);
26 | s.Push(15, 1);
27 | s.Push(16, 1);
28 | s.Push(17, 1);
29 | s.Push(18, 1);
30 | s.Push(4, 2);
31 | s.Pop(2);
32 | s.Push(19, 1);
33 | Console.WriteLine(s);
34 |
35 | Console.Read();
36 | }
37 |
38 | public class MultipleStack
39 | {
40 | int numOfStack;
41 | public int[] array;
42 | public SingleStack[] stacks;
43 |
44 |
45 | public override string ToString()
46 | {
47 | string s = "";
48 | for (int i = 0; i < stacks.Length; i++)
49 | {
50 | s += stacks[i] + "\n";
51 | }
52 | return s;
53 | }
54 |
55 | public MultipleStack(int numOfStack, int totalSize)
56 | {
57 | this.numOfStack = numOfStack;
58 | if (totalSize < numOfStack)
59 | throw new Exception("Total size is too small.");
60 |
61 | array = new int[totalSize];
62 | stacks = new SingleStack[numOfStack];
63 |
64 | for (int i = 0; i < numOfStack; i++)
65 | {
66 | //initialize each stack to the size of 1.
67 | stacks[i] = new SingleStack(array, i, i + 1);
68 | }
69 | }
70 |
71 | public int Pop(int stackIndex)
72 | {
73 | SingleStack s = stacks[stackIndex];
74 | return s.Pop();
75 | //Need to implement stack size shrinking here.
76 | }
77 |
78 | public void Push(int num, int stackIndex)
79 | {
80 | SingleStack s = stacks[stackIndex];
81 | if (s.Push(num))
82 | return;
83 | int totalSize = GetTotalSize();
84 | if (totalSize >= array.Length)
85 | throw new Exception("Array is full!");
86 | //Expand the current stack;
87 | int extension = Math.Min(s.GetSize(), array.Length - totalSize);
88 | Shift(s.pointer, totalSize, extension);
89 | //Shift bound of the arrays following the current one.
90 | for (int i = stackIndex + 1; i < stacks.Length; i++)
91 | {
92 | stacks[i].start += extension;
93 | stacks[i].end += extension;
94 | stacks[i].pointer += extension;
95 | }
96 | s.end += extension;//Expand the current array.
97 | if (!s.Push(num))
98 | throw new Exception("Shift operation failed...check your code.");
99 | }
100 |
101 | public void Shift(int start,int end, int count)
102 | {
103 | for (int i = end - 1; i >= start; i--)
104 | array[i + count] = array[i];
105 | }
106 |
107 | public int GetTotalSize()
108 | {
109 | int total = 0;
110 | for (int i = 0; i < stacks.Length; i++)
111 | total += stacks[i].GetSize();
112 | return total;
113 | }
114 | }
115 |
116 | public class SingleStack
117 | {
118 | public int start;
119 | public int end;
120 | public int[] array;
121 | public int pointer;
122 |
123 | public SingleStack(int[] array, int start,int end)
124 | {
125 | this.start = start;
126 | this.end = end;
127 | this.array = array;
128 | this.pointer = start;
129 | }
130 |
131 | public override string ToString()
132 | {
133 | String s = "";
134 | for (int i = start; i < pointer; i++)
135 | {
136 | s += array[i] + " ";
137 | }
138 | for (int i = pointer; i < end; i++)
139 | {
140 | s += "* ";
141 | }
142 | return s;
143 | }
144 |
145 | public Boolean Push(int n)
146 | {
147 | if (pointer < end)
148 | {
149 | array[pointer] = n;
150 | pointer++;
151 | return true;
152 | }
153 | return false;
154 | }
155 |
156 | public int Pop()
157 | {
158 | if (pointer == start)
159 | throw new Exception("Stack is empty");
160 | pointer--;
161 | return array[pointer];
162 | }
163 |
164 | public int GetSize()
165 | {
166 | return end - start;
167 | }
168 |
169 | public int GetUsedSize()
170 | {
171 | return start - pointer;
172 | }
173 | }
174 | }
175 | }
176 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter03/question0302.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter03
8 | {
9 | class question0302
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | MinStack ms = new MinStack();
14 | Console.WriteLine(ms);
15 | ms.Push(5);
16 | Console.WriteLine(ms);
17 | ms.Push(6);
18 | Console.WriteLine(ms);
19 | ms.Push(3);
20 | Console.WriteLine(ms);
21 | ms.Push(7);
22 | Console.WriteLine(ms);
23 | ms.Pop();
24 | Console.WriteLine(ms);
25 | ms.Pop();
26 | Console.WriteLine(ms);
27 |
28 | Console.Read();
29 | }
30 |
31 | }
32 |
33 | public class MinStack : Stack
34 | {
35 | Stack mins;
36 |
37 | public MinStack()
38 | {
39 | mins = new Stack();
40 | }
41 |
42 | public override void Push(int n)
43 | {
44 | if (mins.top == null || mins.top.data>=n)
45 | mins.Push(new Node(n));
46 | base.Push(n);
47 | }
48 |
49 | public override void Push(Node n)
50 | {
51 | if (mins.top == null || mins.top.data >= n.data)
52 | mins.Push(new Node(n.data));
53 | base.Push(n);
54 | }
55 |
56 | public override Node Pop()
57 | {
58 | Node n = base.Pop();
59 | if (n == null)
60 | return n;
61 | if (mins.top.data == n.data)
62 | mins.Pop();
63 | return n;
64 | }
65 |
66 | public override string ToString()
67 | {
68 |
69 | return "{ " + base.ToString() + "} min: " + ((mins.top==null)?"null":""+mins.top.data);
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter03/question0303.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter03
8 | {
9 | class question0303
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | SetOfStacks s = new SetOfStacks();
14 | s.Push(1);
15 | s.Push(2);
16 | s.Push(3);
17 | s.Push(4);
18 | s.Push(5);
19 | s.Push(6);
20 | s.PopAt(0);
21 | s.PopAt(1);
22 | s.PopAt(1);
23 | s.PopAt(0);
24 | Console.Read();
25 | }
26 | }
27 |
28 | class SetOfStacks
29 | {
30 | List stacks;
31 | int stackLimit = 2;
32 |
33 | public SetOfStacks()
34 | {
35 | stacks = new List();
36 | }
37 |
38 | public int PopAt(int index)
39 | {
40 | if (index >= stacks.Count)
41 | throw new Exception("Index too big");
42 | int num = stacks.ElementAt(index).Pop().data;
43 | Shift(index);
44 | //PrintStacks();
45 | return num;
46 | }
47 |
48 | public void Shift(int index)
49 | {
50 | Stack s = stacks.ElementAt(index);
51 | if (s.top == null)//If it's empty, remove the stack from the list
52 | {
53 | stacks.Remove(s);
54 | return;
55 | }
56 | index++;
57 | while (index < stacks.Count)
58 | {
59 | Stack next = stacks.ElementAt(index);
60 | Stack current = stacks.ElementAt(index-1);
61 | Node n = TakeOne(next);
62 | current.Push(n);
63 | index++;
64 | }
65 | if (stacks.Last().top == null)
66 | stacks.Remove(stacks.Last());
67 | }
68 |
69 | public Node TakeOne(Stack s)
70 | {
71 | //Assume s has as least one element.
72 | Node bottom = s.top;
73 |
74 | //If there is only one element.
75 | if (bottom.next == null)
76 | {
77 | s.top = null;
78 | return bottom;
79 | }
80 |
81 | while (bottom.next.next != null)
82 | {
83 | bottom = bottom.next;
84 | }
85 | Node temp = bottom.next;
86 | bottom.next = null;
87 | return temp;
88 | }
89 |
90 | public void Push(int n)
91 | {
92 | Node node = new Node(n);
93 | Stack last;
94 | if (stacks.Count == 0)
95 | {
96 | last = new Stack();
97 | stacks.Add(last);
98 | }
99 | else last = stacks.ElementAt(stacks.Count - 1);
100 | if (last.GetSize() == stackLimit)
101 | {
102 | last = new Stack();
103 | stacks.Add(last);
104 | }
105 | last.Push(n);
106 | //PrintStacks();
107 | }
108 |
109 | public void PrintStacks()
110 | {
111 | Util.PrintArray(stacks);
112 | Console.WriteLine("-");
113 | }
114 |
115 | }
116 |
117 |
118 | }
119 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter03/question0304.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter03
8 | {
9 | class question0304
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | }
14 | public static void MoveDisk(int n, int origin, int dest, int buffer)
15 | {
16 | if(n == 1)
17 | Console.WriteLine(origin+" -> "+dest);
18 | if (n <= 0)
19 | return;
20 | MoveDisk(n - 1, origin, buffer, dest);
21 | MoveDisk(1, origin, dest, buffer);
22 | MoveDisk(n - 1, buffer,dest, origin);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter03/question0305.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter03
8 | {
9 | class question0305
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | MyQueue q = new MyQueue();
14 | q.Dequeue();
15 | q.Enqueue(1);
16 | q.Enqueue(2);
17 | q.Dequeue();
18 | q.Enqueue(3);
19 | q.Enqueue(4);
20 | q.Dequeue();
21 | q.Dequeue();
22 | q.Enqueue(5);
23 | q.Dequeue();
24 | q.Enqueue(6);
25 | q.Dequeue();
26 | Console.Read();
27 | }
28 | }
29 |
30 | public class MyQueue
31 | {
32 | Stack inStack;
33 | Stack outStack;
34 |
35 | public MyQueue()
36 | {
37 | inStack = new Stack();
38 | outStack = new Stack();
39 | }
40 |
41 | public void Enqueue(int n)
42 | {
43 | inStack.Push(n);
44 | }
45 |
46 | public Node Dequeue()
47 | {
48 | Node popped = outStack.Pop();
49 | if (popped == null)
50 | {
51 | while (inStack.top != null)
52 | {
53 | outStack.Push(inStack.Pop());
54 | }
55 | popped = outStack.Pop();
56 | }
57 | if (popped == null)
58 | Console.WriteLine("null");
59 | else
60 | Console.WriteLine(popped.data);
61 | return popped;
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter03/question0306.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter03
8 | {
9 | class question0306
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | Stack s = new Stack();
14 | s.Push(5);
15 | s.Push(1);
16 | s.Push(2);
17 | s.Push(3);
18 | s.Push(4);
19 | Console.WriteLine(s);
20 | s = Sort(s);
21 | Console.WriteLine(s);
22 | Console.Read();
23 | }
24 |
25 | public static Stack Sort(Stack s)
26 | {
27 | Stack r = new Stack();
28 | while (!s.IsEmpty())
29 | {
30 | Node temp = s.Pop();
31 | while(!r.IsEmpty() && r.Peek().data > temp.data)
32 | {
33 | s.Push(r.Pop());
34 | }
35 | r.Push(temp);
36 | }
37 | return r;
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter03/question0307.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter03
8 | {
9 | class question0307
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | AnimalQueues q = new AnimalQueues();
14 | Console.WriteLine();
15 | }
16 | }
17 |
18 | public class AnimalQueues
19 | {
20 | AnimalQueue dogQ;
21 | AnimalQueue catQ;
22 |
23 | public AnimalQueues()
24 | {
25 | dogQ = new AnimalQueue();
26 | catQ = new AnimalQueue();
27 | }
28 |
29 | public Cat DequeueCats()
30 | {
31 | return catQ.Dequeue() as Cat;
32 | }
33 |
34 | public void EnqueueCat(Cat c)
35 | {
36 | catQ.Enqueue(c);
37 | }
38 |
39 | public void EnqueueDog(Dog d)
40 | {
41 | dogQ.Enqueue(d);
42 | }
43 |
44 | public Dog DequeueDogs()
45 | {
46 | return dogQ.Dequeue() as Dog;
47 | }
48 |
49 | public Animal DequeueAny()
50 | {
51 | Animal oldDog = dogQ.Peek();
52 | Animal oldCat = catQ.Peek();
53 | if (oldDog == null)
54 | return catQ.Dequeue();
55 | if (oldCat == null)
56 | return dogQ.Dequeue();
57 | if (oldDog.timeArrived < oldCat.timeArrived)
58 | return dogQ.Dequeue();
59 | return catQ.Dequeue();
60 | }
61 |
62 | }
63 |
64 | public class AnimalQueue
65 | {
66 | Animal first;
67 | Animal last;
68 | public AnimalQueue()
69 | {
70 | first = null;
71 | last = null;
72 | }
73 |
74 | public Animal Peek()
75 | {
76 | return first;
77 | }
78 |
79 | public void Enqueue(Animal a)
80 | {
81 | if (last == null)
82 | {
83 | last = a;
84 | first = a;
85 | return;
86 | }
87 | last.next = a;
88 | last = last.next;
89 | }
90 |
91 | public Animal Dequeue()
92 | {
93 | if (first == null)
94 | return null;
95 | Animal returned = first;
96 | first = first.next;
97 | if (first == null)
98 | last = null;
99 | return returned;
100 | }
101 | }
102 |
103 | public class Animal
104 | {
105 | public DateTime timeArrived;
106 | public Animal next;
107 | public Animal()
108 | {
109 | timeArrived = DateTime.Now;
110 | next = null;
111 | }
112 | }
113 |
114 | public class Cat : Animal
115 | {
116 | }
117 |
118 | public class Dog : Animal
119 | {
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter04/Tree.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter04
8 | {
9 | class Tree
10 | {
11 | }
12 | class Node
13 | {
14 | public Node left;
15 | public Node right;
16 | public Node parent;
17 |
18 | public int data;
19 |
20 | public Node(int data)
21 | {
22 | left = new Node();
23 | right = new Node();
24 | parent = new Node();
25 | this.data = data;
26 | }
27 |
28 | public Node():this(-1)
29 | {
30 |
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter04/question0401.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter04
8 | {
9 | class question0401
10 | {
11 | public static int CheckHeight(Node root)
12 | {
13 | if (root == null)
14 | return 0;
15 | int leftHeight = CheckHeight(root.left);
16 | int rightHeight = CheckHeight(root.right);
17 | if (Math.Abs(leftHeight - rightHeight) >= 1)
18 | return -1;
19 | return Math.Max(leftHeight, rightHeight) + 1;
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter04/question0402.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter04
8 | {
9 | class question0402
10 | {
11 | public static bool ContainsPath(List[] adjList, int first, int second)
12 | {
13 | Queue unvisited = new Queue();
14 | int[] visited = new int[adjList.Length];
15 | for (int i = 0; i < visited.Length; i++)
16 | visited[i] = 0;
17 | unvisited.Enqueue(first);
18 | while (unvisited.Count > 0)
19 | {
20 | int current = unvisited.Dequeue();
21 | if (visited[current]==1)
22 | continue;
23 | List paths = adjList[current];
24 | foreach (int i in paths)
25 | {
26 | if (i == second)
27 | return true;
28 | if (visited[i] == 0)
29 | unvisited.Enqueue(i);
30 | }
31 | visited[current] = 1;
32 | }
33 | return false;
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter04/question0403.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter04
8 | {
9 | class question0403
10 | {
11 | public Node CreateMinBST(int[] array, int start, int end)
12 | {
13 | if (end < start)
14 | return null;
15 | int middle = (start + end) / 2;
16 | Node mNode = new Node(array[middle]);
17 | Node left = CreateMinBST(array, start, middle - 1);
18 | Node right = CreateMinBST(array, middle + 1, end);
19 | mNode.left = left;
20 | mNode.right = right;
21 | return mNode;
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter04/question0404.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter04
8 | {
9 | class question0404
10 | {
11 | List> CreateLevelLinkedList(Node root)
12 | {
13 | List> result = new List>();
14 | Queue levelQ = new Queue();
15 | Queue nextQ = new Queue();
16 | levelQ.Enqueue(root);
17 | result.Add(new List());
18 | while (levelQ.Count > 0)
19 | {
20 | Node current = levelQ.Dequeue();
21 | result.Last().Add(current);
22 | if (current.left != null)
23 | nextQ.Enqueue(current.left);
24 | if (current.right != null)
25 | nextQ.Enqueue(current.right);
26 | if (levelQ.Count == 0)
27 | {
28 | levelQ = nextQ;
29 | result.Add(new List());
30 | }
31 | }
32 | return result;
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter04/question0405.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter04
8 | {
9 | class question0405
10 | {
11 | public static bool IsBST(Node root)
12 | {
13 | return CheckMinMax(root, Int32.MinValue, Int32.MaxValue);
14 | }
15 |
16 | public static bool CheckMinMax(Node root, int min, int max)
17 | {
18 | if (root == null)
19 | return true;
20 | if (root.data < min || root.data > max)
21 | return false;
22 | bool checkLeft = CheckMinMax(root.left, min, root.data);
23 | bool checkRight = CheckMinMax(root.right, root.data, max);
24 | return checkLeft && checkRight;
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter04/question0407.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter04
8 | {
9 | class question0407
10 | {
11 | //Not tested.
12 | public Node CommonAnce(Node root, Node first, Node second)
13 | {
14 | if (root == null)
15 | return null;
16 | if (root == first)
17 | return first;
18 | if (root == second)
19 | return second;
20 | Node left = CommonAnce(root.left, first, second);
21 | Node right = CommonAnce(root.right, first, second);
22 | if (left == null)
23 | return right;
24 | else if (right == null)
25 | return left;
26 | return root;
27 | }
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter04/question0409.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter04
8 | {
9 | class question0409
10 | {
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter04/qusetion0406.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter04
8 | {
9 | class qusetion0406
10 | {
11 | public static Node NextNode(Node n)
12 | {
13 | Node next;
14 | if (n.right != null)
15 | {
16 | next = n.right;
17 | while (next.left != null)
18 | next = next.left;
19 | return next;
20 | }
21 | next = n.parent;
22 | Node current = n;
23 | while (next != null && next.right == n)
24 | {
25 | next = next.parent;
26 | n = n.parent;
27 | }
28 | if (next == null)
29 | return null;
30 | return next;
31 |
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter05/BitUtil.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter05
8 | {
9 | class BitUtil
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | int n = 1;
14 | Console.WriteLine(Convert.ToString(n, 2));
15 | Console.WriteLine(GetBit(n, 0));
16 | Console.Read();
17 | }
18 |
19 | public static Boolean GetBit(int num, int i)
20 | {
21 | return ((num >> i) & 1) == 1;
22 | }
23 |
24 | public static int SetBit(int num, int i)
25 | {
26 | return num | (1 << i);
27 | }
28 |
29 | public static int ClearBit(int num, int i)
30 | {
31 | return num & (~(1 << i));
32 | }
33 |
34 | public static void PrintNumBinary(int n)
35 | {
36 | Console.WriteLine(Convert.ToString(n, 2));
37 | }
38 |
39 | public static int ToInt(String s)
40 | {
41 | return Convert.ToInt32(s, 2);
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter05/question0501.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter05
8 | {
9 | class question0501
10 | {
11 | static void NotMain(string[] args)
12 | {
13 | int n = BitUtil.ToInt("100000000000");
14 | int m = BitUtil.ToInt("10011");
15 | BitUtil.PrintNumBinary(n);
16 | BitUtil.PrintNumBinary(m);
17 | BitUtil.PrintNumBinary(insert(n, m, 2, 6));
18 | Console.Read();
19 | }
20 |
21 | static int insert(int n, int m, int start, int end)
22 | {
23 | int mask = 1 << (end-start+1);
24 | mask -= 1;
25 | mask = mask << start;
26 | n = (~mask) & n;
27 | m = m << start;
28 | return m | n;
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter05/question0502.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter05
8 | {
9 | class question0502
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | Console.WriteLine(PrintBinary(0.75));
14 | Console.Read();
15 | }
16 |
17 | static String PrintBinary(double num)
18 | {
19 | StringBuilder builder = new StringBuilder();
20 | builder.Append(".");
21 |
22 | while (num > 0)
23 | {
24 |
25 | if (builder.Length >= 32)
26 | return "ERROR";
27 |
28 | num *= 2;
29 | if (num >= 1)
30 | {
31 | builder.Append("1");
32 | num -= 1;
33 | }
34 | else
35 | builder.Append("0");
36 | }
37 | return builder.ToString();
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter05/question0503.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter05
8 | {
9 | class question0503
10 | {
11 |
12 | static void NotMain(String[] args)
13 | {
14 | int n = BitUtil.ToInt("101001101");
15 | BitUtil.PrintNumBinary(getNext(n));
16 | Console.Read();
17 | }
18 |
19 | static int getNext(int n)
20 | {
21 | int copy = n;
22 | int trailingZeroCount = 0;
23 | while ((copy & 1) != 1)
24 | {
25 | trailingZeroCount++;
26 | copy >>= 1;
27 | }
28 | int oneCount = 0;
29 | while ((copy & 1) != 0)
30 | {
31 | oneCount++;
32 | copy >>= 1;
33 | }
34 | copy++;
35 | copy = copy << (trailingZeroCount + oneCount);
36 | copy |= (1 << (oneCount - 1)) - 1;
37 | return copy;
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter05/question0505.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter05
8 | {
9 | class question0505
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | int a = 31;
14 | int b = 14;
15 | BitUtil.PrintNumBinary(a);
16 | BitUtil.PrintNumBinary(b);
17 | Console.WriteLine(getDiff(a, b));
18 | Console.Read();
19 | }
20 |
21 | static int getDiff(int a, int b)
22 | {
23 | int c = a ^ b;
24 | int count = 0;
25 | while (c != 0)
26 | {
27 | c &= (c - 1);
28 | count++;
29 | }
30 | return count;
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter05/question0506.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter05
8 | {
9 | class question0506
10 | {
11 | static int swapOddEventBits(int x)
12 | {
13 | int a =(int)((x & 0xaaaaaaaa)>>1);
14 | return a|((x&0x55555555)<<1);
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter05/question0507.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter05
8 | {
9 | class question0507
10 | {
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0901.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter08
8 | {
9 | class question0801
10 | {
11 | static int countPossibility(int n)
12 | {
13 | int[] possibilities = new int[n];
14 | possibilities[0] = 1;
15 | possibilities[1] = 1;
16 | possibilities[2] = 2;
17 | for (int i = 3; i < possibilities.Length; i++)
18 | {
19 | possibilities[i] = possibilities[i - 3] + possibilities[i - 2] + possibilities[i - 1];
20 | }
21 | return possibilities[n - 1];
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0902.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace InterviewPrep.chapter08
9 | {
10 | public enum Direction { down, right, both, impossible };
11 |
12 | class question0902
13 | {
14 |
15 | static void NotMain(String[] args)
16 | {
17 | bool[,] map = new bool [10,12] ;
18 | for(int i = 0;i result = findPath(map);
27 | for (int i = 0; i < result.Count; i++)
28 | Console.Write(result.ElementAt(i)+" -> ");
29 | Console.Read();
30 | }
31 |
32 | static List findPath(bool[,] map)
33 | {
34 | Dir[,] dirMap = new Dir[map.GetLength(0), map.GetLength(1)];
35 | bool stuck = false;
36 | for (int i = 0; i < dirMap.GetLength(0); i++)
37 | {
38 | if (stuck)
39 | dirMap[i, 0] = new Dir(0, Direction.impossible);
40 | else if (map[0, i])
41 | dirMap[i, 0] = new Dir(1, Direction.down);
42 | else
43 | {
44 | stuck = true;
45 | dirMap[i, 0] = new Dir(0, Direction.impossible);
46 | }
47 | }
48 | stuck = false;
49 | for (int i = 0; i < dirMap.GetLength(1); i++)
50 | {
51 | if (stuck)
52 | dirMap[0, i] = new Dir(0, Direction.impossible);
53 | else if (map[0, i])
54 | dirMap[0, i] = new Dir(1, Direction.right);
55 | else
56 | {
57 | stuck = true;
58 | dirMap[0, i] = new Dir(0, Direction.impossible);
59 | }
60 | }
61 | //Build the map bottom up.
62 | for (int i = 1; i < map.GetLength(0); i++)
63 | {
64 | for (int j = 1; j < map.GetLength(1); j++)
65 | {
66 | if (!map[i, j])
67 | {
68 | dirMap[i, j] = new Dir(0, Direction.impossible);
69 | continue;
70 | }
71 | Dir up = dirMap[i - 1, j];
72 | Dir left = dirMap[i, j - 1];
73 | if (up.directions != Direction.impossible && left.directions != Direction.impossible)
74 | dirMap[i, j] = new Dir(up.count + left.count, Direction.both);
75 | else if (left.directions != Direction.impossible)
76 | dirMap[i, j] = new Dir(left.count, Direction.right);
77 | else if (up.directions != Direction.impossible)
78 | dirMap[i, j] = new Dir(up.count, Direction.down);
79 | else
80 | dirMap[i, j] = new Dir(0, Direction.impossible);
81 | }
82 | }
83 | //Trace back.
84 | int possibilities = dirMap[dirMap.GetLength(0) - 1, dirMap.GetLength(1) - 1].count;
85 | List path = new List();
86 | int x = dirMap.GetLength(0) - 1;
87 | int y = dirMap.GetLength(0) - 1;
88 | while (x != 0 || y != 0)
89 | {
90 | path.Add(new Pair(x, y));
91 | Dir current = dirMap[x, y];
92 | if (current.directions == Direction.down)
93 | x--;
94 | else if (current.directions == Direction.right)
95 | y--;
96 | else if (current.directions == Direction.both)
97 | x--;//It can be y-- here as well because both ways work
98 | else
99 | return null;//Impossible to reach.
100 | }
101 | path.Reverse();
102 | return path;
103 | }
104 | }
105 |
106 | class Dir
107 | {
108 | public int count;
109 | public Direction directions;
110 | public Dir(int count, Direction directions)
111 | {
112 | this.count = count;
113 | this.directions = directions;
114 | }
115 | }
116 |
117 | class Pair
118 | {
119 | public int x;
120 | public int y;
121 | public Pair(int x, int y)
122 | {
123 | this.x = x;
124 | this.y = y;
125 | }
126 |
127 | public override string ToString()
128 | {
129 | return "("+x + " " + y+")";
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0903.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter08
8 | {
9 | class question0903
10 | {
11 | static int BinarySearchForMIndex(int[] a, int start, int end)
12 | {
13 | if (start >= end)
14 | return -1;
15 | int middle = (start + end) / 2;
16 | if (middle == a[middle])
17 | return middle;
18 | if (middle > a[middle])
19 | return BinarySearchForMIndex(a, middle + 1, end);
20 | return BinarySearchForMIndex(a, start, middle - 1);
21 | }
22 |
23 |
24 | static int BinarySearchMIndexNonDistinct(int[] a, int start, int end)
25 | {
26 | if (end < start)
27 | return -1;
28 | int mid = (end + start) / 2;
29 | int midNum = a[mid];
30 |
31 | if (mid == midNum)
32 | return mid;
33 |
34 | int leftIndex = Math.Min(mid - 1, midNum);
35 | int left = BinarySearchMIndexNonDistinct(a, start, leftIndex);
36 | if (left >= 0)
37 | return left;
38 | int rightIndex = Math.Max(mid + 1, midNum);
39 | int right = BinarySearchMIndexNonDistinct(a, rightIndex, end);
40 | return right;
41 |
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0904.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter08
8 | {
9 | class question0904
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | HashSet original = new HashSet();
14 | original.Add(0);
15 | original.Add(1);
16 | original.Add(2);
17 | original.Add(3);
18 | List> result = GetAllSubsets(original);
19 | foreach (HashSet s in result)
20 | {
21 | Util.PrintSet(s);
22 | }
23 | Console.Read();
24 | }
25 |
26 | static List> GetAllSubsets(HashSet s)
27 | {
28 | if (s.Count == 0)
29 | return null;
30 | s = new HashSet(s);//Copy the set so the original one will not be modified.
31 | int element = s.ElementAt(0);
32 | s.Remove(element);
33 | List> list = GetAllSubsetsHelper(element, s);
34 | return list;
35 | }
36 |
37 | static List> GetAllSubsetsHelper(int n, HashSet s)
38 | {
39 | List> list = new List>();
40 | if (s.Count == 0)
41 | {
42 | list.Add(new HashSet());
43 | HashSet withN = new HashSet();
44 | withN.Add(n);
45 | list.Add(withN);
46 | return list;
47 | }
48 | int element = s.ElementAt(0);
49 | s.Remove(element);
50 | list = GetAllSubsetsHelper(element,s);
51 | List> secondList = new List>();
52 | for(int i = 0;i newSet = new HashSet(list.ElementAt>(i));
55 | newSet.Add(n);
56 | secondList.Add(newSet);
57 | }
58 | list.AddRange(secondList);
59 | return list;
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0905.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter08
8 | {
9 | class question0905
10 | {
11 |
12 | static void NotMain(String[] args)
13 | {
14 | Util.PrintArray(GetPermutation("ab"));
15 | Console.Read();
16 | }
17 |
18 | static List GetPermutation(string original)
19 | {
20 | if (original == null)
21 | return null;
22 |
23 | List perm = new List();
24 | if (original.Length == 0)
25 | {
26 | perm.Add(" ");
27 | return perm;
28 | }
29 |
30 | char first = original[0];
31 | String remainder = original.Substring(1);
32 | List result = GetPermutation(remainder);
33 | foreach (string word in result)
34 | {
35 | for (int i = 0; i < word.Length; i++)
36 | {
37 | String start = word.Substring(0, i);
38 | String end = word.Substring(i);
39 | perm.Add(start + first + end);
40 | }
41 | }
42 | return perm;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0906.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter08
8 | {
9 | class question0906
10 | {
11 | //Not done.
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0907.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter08
8 | {
9 | class question0907
10 | {
11 | static void fillColor(int[,] map, int x, int y, int originalColor, int color)
12 | {
13 | if (x < 0 || y < 0 || x >= map.GetLength(0) || y >= map.GetLength(1))
14 | return;
15 | if (map[x, y] != originalColor)
16 | return;
17 | map[x, y] = color;
18 | fillColor(map, x + 1, y, originalColor, color);
19 | fillColor(map, x + 1, y + 1, originalColor, color);
20 | fillColor(map, x - 1, y, originalColor, color);
21 | fillColor(map, x - 1, y - 1, originalColor, color);
22 | return;
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0908.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter09
8 | {
9 | class question0908
10 | {
11 |
12 | static void NotMain(String[] args)
13 | {
14 | Console.WriteLine(countWays(5, 5));
15 | Console.Read();
16 | }
17 |
18 | static int countWays(int n, int denom)
19 | {
20 | int nextDenom = -1;
21 | if (n == 0)
22 | return 1;
23 | switch (denom)
24 | {
25 | case 25:
26 | nextDenom = 10;
27 | break;
28 | case 10:
29 | nextDenom = 5;
30 | break;
31 | case 5:
32 | nextDenom = 1;
33 | break;
34 | case 1:
35 | return 1;//Only one way when only using 1.
36 | }
37 | int count = 0;
38 | for (int i = 0; i <= n / denom; i++)
39 | {
40 | count += countWays(denom * i, nextDenom);
41 | }
42 | return count;
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0909.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter09
8 | {
9 | class question0909
10 | {
11 |
12 | static void NotMain(String[] args)
13 | {
14 | int[] cols = new int[GRID_SIZE];
15 | for (int i = 0; i < cols.Length; i++)
16 | cols[i] = -1;
17 | List results = new List();
18 | placeQueens(0, cols, results);
19 | printQueens(results.ElementAt(0));
20 | Console.Read();
21 | }
22 |
23 | static void printQueens(int[] cols)
24 | {
25 | for (int i = 0; i < cols.Length; i++)
26 | {
27 | int queenPos = cols[i];
28 | for (int j = 0; j < queenPos; j++)
29 | {
30 | Console.Write("o ");
31 | }
32 | Console.Write("+ ");
33 | for (int j = queenPos + 1; j < GRID_SIZE; j++)
34 | Console.Write("o ");
35 | Console.WriteLine();
36 | }
37 | }
38 |
39 | static int GRID_SIZE = 8;
40 |
41 | static void placeQueens(int row, int[] cols, List results)
42 | {
43 | int[] temp = new int[GRID_SIZE];
44 | for (int i = 0; i < temp.Length; i++)
45 | temp[i] = cols[i];
46 | cols = temp;
47 | if (row == GRID_SIZE)
48 | {
49 | Console.WriteLine("Added");
50 | results.Add(cols);
51 | return;
52 | }
53 | for (int col = 0; col < GRID_SIZE; col++)
54 | {
55 | if (checkPossible(row, col, cols))
56 | {
57 | cols[row] = col;
58 | placeQueens(row+1, cols, results);
59 | }
60 | }
61 | }
62 |
63 | static bool checkPossible(int row1, int col1, int[] cols)
64 | {
65 | for (int row2 = 0; row2 < row1; row2++)
66 | {
67 | int col2 = cols[row2];
68 | if (cols[row2] == -1)
69 | continue;
70 | if (col2 == col1)
71 | return false;
72 | int rowDiff = row1 - row2;//Row is always greater because new rows are added later.
73 | int colDiff = Math.Abs(col2 - col1);
74 | if (rowDiff == colDiff)//Check diag
75 | return false;
76 | }
77 | return true;
78 |
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter09/question0910.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter09
8 | {
9 | class question0910
10 | {
11 |
12 | static void NotMain(String[] args)
13 | {
14 | List boxes = new List();
15 | boxes.Add(new int[] { 1, 2, 3 });
16 | boxes.Add(new int[] { 4, 5, 6 });
17 | boxes.Add(new int[] { 5, 7, 10 });
18 | boxes.Add(new int[] { 5, 6, 7 });
19 | boxes.Add(new int[] { 6, 8, 9 });
20 | Util.PrintArray(StackBoxes(boxes));
21 | Console.Read();
22 | }
23 |
24 | static List StackBoxes(List original)
25 | {
26 | Dictionary> map = new Dictionary>();
27 | int max = -1;
28 | int bottomBox = -1;
29 | for (int i = 0; i < original.Count; i++)
30 | {
31 | int current = GetMax(i, map,original);
32 | if (current > max)
33 | {
34 | max = current;
35 | bottomBox = i;
36 | }
37 | }
38 | //Print map for debugging
39 | Console.WriteLine("Debugging info start: ");
40 | foreach (int key in map.Keys)
41 | {
42 | Console.Write(key + " -> ");
43 | List l = map[key];
44 | for (int i = 0; i < l.Count; i++)
45 | Console.Write(l.ElementAt(i) + " ");
46 | Console.WriteLine();
47 | }
48 | Console.WriteLine("Debugging info end.");
49 | //End printing map.
50 | if (bottomBox != -1)
51 | return map[bottomBox];
52 | else
53 | return null;
54 | }
55 |
56 | static int GetMax(int bottomBox, Dictionary> map, List original)
57 | {
58 | if (map.ContainsKey(bottomBox))
59 | return map[bottomBox].Count;
60 | int[] box1 = original.ElementAt(bottomBox);
61 | int secondBottomBox = -1;
62 | int max = -1;
63 | for (int i = 0; i < original.Count; i++)
64 | {
65 | if (i == bottomBox)
66 | continue;
67 | int[] box2 = original.ElementAt(i);
68 | if (!(box1[0] > box2[0] && box1[1] > box2[1] && box1[2] > box2[2]))
69 | continue;
70 | int lastStack = GetMax(i, map, original);
71 | if (lastStack > max)
72 | {
73 | secondBottomBox = i;
74 | max = lastStack;
75 | }
76 | }
77 | List stack = new List();
78 | if (secondBottomBox != -1)
79 | {
80 | stack = new List(map[secondBottomBox]);
81 | }
82 | stack.Add(bottomBox);
83 | map.Add(bottomBox, stack);
84 | return stack.Count;
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter11/question1101.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter11
8 | {
9 | class question1101
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | int[] a = new int[] { 0, 2, 4, 6, 8, -1, -1, -1, -1, -1, -1 };
14 | int[] b = new int[] { 1, 3, 5, 7, 9, 11 };
15 | Insert(a, b, 5, 6);
16 | Util.PrintArray(a);
17 | Console.Read();
18 | }
19 |
20 | static void Insert(int[] a, int[] b, int aSize, int bSize)
21 | {
22 | int lastB = bSize - 1;
23 | int lastA = aSize - 1;
24 | int lastFinal = aSize + bSize - 1;
25 | while (lastB != -1)
26 | {
27 | while (a[lastA] > b[lastB])
28 | {
29 | a[lastFinal] = a[lastA];
30 | lastFinal--;
31 | lastA--;
32 | }
33 | a[lastFinal] = b[lastB];
34 | lastFinal--;
35 | lastB--;
36 | }
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter11/question1102.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter11
8 | {
9 | class question1102
10 | {
11 |
12 | static void Main(String[] args)
13 | {
14 | String[] s = new String[] { "aaa", "bbb", "aaa", "abab", "babaa", "baba", "bbaaa", "bbaaaa", "bbb" };
15 | SortByAnagramsEfficient(s);
16 | Util.PrintArray(s);
17 | Console.Read();
18 | }
19 |
20 | public static void SortByAnagramsEfficient(String[] a)
21 | {
22 | Dictionary> map = new Dictionary>();
23 | for (int i = 0; i < a.Length; i++)
24 | {
25 | String anagram = getAnagram(a[i]);
26 | if (!map.ContainsKey(anagram))
27 | map[anagram] = new LinkedList();
28 | map[anagram].AddLast(a[i]);
29 | }
30 | int counter = 0;
31 | foreach(LinkedList l in map.Values)
32 | {
33 | foreach (String s in l)
34 | {
35 | a[counter] = s;
36 | counter++;
37 | }
38 | }
39 | }
40 |
41 | public static String getAnagram(String s)
42 | {
43 | char[] a = s.ToCharArray();
44 | Array.Sort(a);
45 | return new String(a);
46 | }
47 |
48 | public static void SortByAnagrams(String[] a)
49 | {
50 | Array.Sort(a, new AnagramComparer());
51 | }
52 |
53 | public class AnagramComparer : Comparer
54 | {
55 | public override int Compare(string x, string y)
56 | {
57 | int[] charVec = new int[26];
58 | for (int i = 0; i < charVec.Length; i++)
59 | charVec[i] = 0;
60 | if (x.Length != y.Length)
61 | return x.CompareTo(y);
62 | for (int i = 0; i < x.Length; i++)
63 | {
64 | int c = x[i];
65 | if (c >= 'a')
66 | c -= 32;
67 | c -= 'A';
68 | charVec[c]++;
69 | }
70 | for (int i = 0; i < y.Length; i++)
71 | {
72 | int c = y[i];
73 | if (c >= 'a')
74 | c -= 32;
75 | c -= 'A';
76 | charVec[c]--;
77 | if (charVec[c] < 0)
78 | return x.CompareTo(y);
79 | }
80 | return 0;
81 | }
82 | }
83 |
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter11/question1103.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter11
8 | {
9 | class question1103
10 | {
11 |
12 | static void NotMain(String[] args)
13 | {
14 | int[] a = new int[]{50,5,20,30,40};
15 | Console.WriteLine(BinarySearchRotated(a,50));
16 | Console.Read();
17 | }
18 |
19 | static int BinarySearchRotated(int[] rotated, int n)
20 | {
21 | int rotationPoint = FindRotation(rotated);
22 | if (n == rotated[rotationPoint])
23 | return rotationPoint;
24 | if (n > rotated[rotationPoint])
25 | {
26 | int[] newA = new int[rotated.Length-rotationPoint];
27 | for(int i = rotationPoint;i end)
45 | return -1;
46 | int mid = (start + end) / 2;
47 | if (a[mid] == n)
48 | return mid;
49 | if (a[mid] > n)
50 | end = mid - 1;
51 | else if (a[mid] < n)
52 | start = mid + 1;
53 | }
54 | return -1;
55 | }
56 |
57 | static int FindRotation(int[] a)
58 | {
59 | int start = 0;
60 | int end = a.Length - 1;
61 |
62 | while (true)
63 | {
64 | if (start == end)
65 | return start;
66 | int mid = (start + end) / 2;
67 | if (mid < a.Length && a[mid] > a[mid + 1])
68 | return mid+1;
69 | if (mid > 0 && a[mid] < a[mid - 1])
70 | return mid;
71 | if (a[start] <= a[mid])
72 | start = mid + 1;
73 | else if (a[mid] <= a[end])
74 | end = mid - 1;
75 | }
76 | return -1;
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter11/question1105.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter11
8 | {
9 | class question1105
10 | {
11 | static int FindString(String[] a, String s, int first, int last)
12 | {
13 | int mid = (first + last) / 2;
14 | if (a[mid] == "")
15 | {
16 | int left = mid - 1;
17 | int right = mid + 1;
18 | while (true)
19 | {
20 | if (left < first && right > last)
21 | return -1;
22 | else if (right <= last && a[right] != "")
23 | {
24 | mid = right;
25 | break;
26 | }
27 | else if (left >= first && a[left] != "")
28 | {
29 | mid = left;
30 | break;
31 | }
32 | right++;
33 | left--;
34 | }
35 | }
36 |
37 | if (a[mid] == s)
38 | return mid;
39 | else if (a[mid].CompareTo(s) < 0)
40 | return FindString(a, s, mid + 1, last);
41 | else
42 | return FindString(a, s, first, mid - 1);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter11/question1107.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter11
8 | {
9 | class question1107
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | List people = new List ();
14 | people.Add(new int[] { 65,100});
15 | people.Add(new int[] { 70,150});
16 | people.Add(new int[] { 56, 90 });
17 | people.Add(new int[] { 75, 190 });
18 | people.Add(new int[] { 60, 95 });
19 | people.Add(new int[] { 68, 110 });
20 | List list = StackPeople(people);
21 | Util.PrintArray(list);
22 | Console.Read();
23 | }
24 |
25 | static List StackPeople(List people)
26 | {
27 | people.OrderBy(item => item[0]);
28 | List[] maxList = new List[people.Count];
29 | int max = 0;
30 | int bottomPerson = -1;
31 | for (int i = 0; i < maxList.Length; i++)
32 | {
33 | int current = GetMax(maxList, i, people);
34 | if (current > max)
35 | {
36 | max = current;
37 | bottomPerson = i;
38 | }
39 | }
40 | return maxList[bottomPerson];
41 | }
42 |
43 | static int GetMax(List[] maxList, int bottomPerson, List people)
44 | {
45 | if (maxList[bottomPerson] != null)
46 | return maxList[bottomPerson].Count;
47 | int max = -1;
48 | int nextPerson = -1;
49 | for (int i = 0; i < people.Count; i++)
50 | {
51 | if (i == bottomPerson)
52 | continue;
53 | if (people.ElementAt(bottomPerson)[1] <= people.ElementAt(i)[1])
54 | continue;
55 | int current = GetMax(maxList, i, people);
56 | if (current > max)
57 | {
58 | max = current;
59 | nextPerson = i;
60 | }
61 | }
62 | List seq = new List();
63 | if (nextPerson != -1)
64 | seq = new List(maxList[nextPerson]);
65 | seq.Add(bottomPerson);
66 | maxList[bottomPerson] = seq;
67 | return seq.Count;
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter17/question1701.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter17
8 | {
9 | class question1701
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | SwapWithBit(1, 2);
14 | Console.Read();
15 | }
16 |
17 | public static void Swap(int a, int b)
18 | {
19 | a = a - b;
20 | b = a + b;
21 | a = b - a;
22 | Console.WriteLine("a = " + a);
23 | Console.WriteLine("b = " + b);
24 | }
25 |
26 | public static void SwapWithBit(int a, int b)
27 | {
28 | a = a ^ b;
29 | b = a ^ b;
30 | a = a ^ b;
31 | Console.WriteLine("a = " + a);
32 | Console.WriteLine("b = " + b);
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter17/question1702.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter17
8 | {
9 | class question1702
10 | {
11 | enum Piece { EMPTY,RED,BLUE};
12 |
13 | static Piece CheckWinner(Piece[,] board)
14 | {
15 | for (int i = 0; i < board.Length; i++)
16 | {
17 | if (board[0, i] != Piece.EMPTY)
18 | {
19 | if (board[0, i] == board[1, i] &&
20 | board[1, i] == board[2, i])
21 | return board[0, i];
22 | }
23 | if (board[i, 0] != Piece.EMPTY)
24 | {
25 | if (board[i, 0] == board[i, 1] &&
26 | board[i, 1] == board[i, 2])
27 | return board[i, 0];
28 | }
29 | }
30 | Piece leftDiag = board[0, 0];
31 | Piece rightDiag = board[0,board.Length - 1];
32 | if (leftDiag != Piece.EMPTY)
33 | {
34 | Boolean leftWin = true;
35 | for (int i = 1; i < board.Length; i++)
36 | {
37 | if (board[i, i] != leftDiag)
38 | {
39 | leftWin = false;
40 | break;
41 | }
42 | }
43 | if (leftWin)
44 | return leftDiag;
45 | }
46 |
47 | if (rightDiag != Piece.EMPTY)
48 | {
49 | Boolean rightWin = true;
50 | for (int i = 0; i < board.Length; i++)
51 | {
52 | if (board[i, board.Length - i] != rightDiag)
53 | {
54 | rightWin = false;
55 | break;
56 | }
57 | }
58 | if (rightWin)
59 | return rightDiag;
60 | }
61 | return Piece.EMPTY;
62 | }
63 |
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter17/question1703.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter17
8 | {
9 | class question1703
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | Console.WriteLine(GetTrailingZero(19));
14 | Console.Read();
15 | }
16 |
17 | public static int GetTrailingZero(int n)
18 | {
19 | //Only consider five because there are definitely
20 | //more twos.
21 | int fiveCount= 0;
22 | while (n > 1)
23 | {
24 | n /= 5;
25 | fiveCount += n;
26 | }
27 | return fiveCount;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter17/question1704.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter17
8 | {
9 | class question1704
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | Console.WriteLine(Max(2,-3));
14 | Console.Read();
15 | }
16 |
17 | static int Sign(int n)
18 | {
19 | return 1^(n >> 31)&0x1;
20 | }
21 |
22 | static int Max(int a,int b)
23 | {
24 | int sa = Sign(a);
25 | int sb = Sign(b);
26 | int sd = Sign(a-b);
27 |
28 | int useSignOfA = sa ^ sb;
29 |
30 | int useSignOfD = 1^(useSignOfA);
31 |
32 | //if a and b are of different signs, m = sa, otherwise, m = sd
33 | int m = useSignOfA * sa + useSignOfD * sd;
34 | int n = 1 ^ m;
35 | return m * a + n * b;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter17/question1705.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter17
8 | {
9 | class question1705
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | Console.WriteLine(GetResult("GGRR", "RGBY"));
14 | Console.Read();
15 | }
16 |
17 | class Result
18 | {
19 | int hits;
20 | int pseudohits;
21 | public Result(int hits, int pseudohits)
22 | {
23 | this.hits = hits;
24 | this.pseudohits = pseudohits;
25 | }
26 |
27 |
28 | public override String ToString()
29 | {
30 | return "hits: " + hits + ", pseodo hits: " + pseudohits;
31 | }
32 | }
33 |
34 | static Result GetResult(String correct, String guess)
35 | {
36 | if (correct.Length != guess.Length || correct.Length != 4)
37 | return null;
38 | int hits = 0;
39 | for (int i = 0; i < correct.Length; i++)
40 | if (correct[i] == guess[i])
41 | hits++;
42 | int[] correctV = new int[128];
43 | int[] guessV = new int[128];
44 | for (int i = 0; i < guess.Length; i++)
45 | {
46 | correctV[correct[i]]++;
47 | guessV[guess[i]]++;
48 | }
49 | int pseudohits = 0;
50 | for (int i = 0; i < correctV.Length; i++)
51 | {
52 | pseudohits += Math.Min(correctV[i], guessV[i]);
53 | }
54 | pseudohits -= hits;
55 | return new Result(hits, pseudohits);
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter17/question1706.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter17
8 | {
9 | class question1706
10 | {
11 |
12 | public static void NotMain(String[] args)
13 | {
14 | int[] result = GetResult(new int[] { 0,1,2,3,4});
15 | Console.WriteLine("m: " + result[0] + ",n: " + result[1]);
16 | Console.Read();
17 | }
18 |
19 | public static int[] GetResult(int[] a)
20 | {
21 | int roughM = 0;
22 | for (int i = 1; i < a.Length; i++)
23 | {
24 | if (a[i] < a[i - 1])
25 | {
26 | roughM = i - 1;
27 | break;
28 | }
29 | if (i == a.Length - 1)
30 | return new int[] { 0, 0 };//Already soreted
31 | }
32 | int roughN = a.Length - 1;
33 | for (int i = a.Length - 2; i > -1; i--)
34 | {
35 | if (a[i + 1] < a[i])
36 | {
37 | roughN = i + 1;
38 | break;
39 | }
40 | }
41 | int min = Int32.MaxValue;
42 | int max = Int32.MinValue;
43 | for (int i = roughM; i <= roughN; i++)
44 | {
45 | min = Math.Min(min, a[i]);
46 | max = Math.Max(max, a[i]);
47 | }
48 | Console.WriteLine(roughM+" "+roughN);
49 | int m = 0;
50 | for (int i = roughM ; i >= 0; i--)
51 | {
52 | if (a[i] <= min)
53 | {
54 | m = i + 1;
55 | break;
56 | }
57 | }
58 | int n = a.Length - 1;
59 | for (int i = roughN; i < a.Length; i++)
60 | {
61 | if (a[i] >= max)
62 | {
63 | n = i - 1;
64 | break;
65 | }
66 | }
67 | return new int[] { m, n };
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter17/question1708.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter17
8 | {
9 | class question1708
10 | {
11 |
12 | public static void NotMain(String[] args)
13 | {
14 | Console.WriteLine(MaxSubarray(new int[] { 2, -8, 3, -2, 4, -10 }));
15 | Console.Read();
16 | }
17 |
18 | public static int MaxSubarray(int[] a)
19 | {
20 | int maxEnding = 0;
21 | int max = 0;
22 | for (int i = 0; i < a.Length; i++)
23 | {
24 | maxEnding = Math.Max(maxEnding + a[i], 0);
25 | max = Math.Max(maxEnding, max);
26 | }
27 | return max;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter17/question1711.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter17
8 | {
9 | class question1711
10 | {
11 | public static int Rand5()
12 | {
13 | Random r = new Random();
14 | return r.Next(5);
15 | }
16 |
17 | public static int Rand7()
18 | {
19 | int n = Rand5() * 5 + Rand5();
20 | if (n >= 21)
21 | return Rand7();
22 | return n % 7;
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter17/question1712.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter17
8 | {
9 | class question1712
10 | {
11 | public static void GetAllPairs(int[] list,int n)
12 | {
13 | HashSet set = new HashSet();
14 | for (int i = 0; i < list.Length; i++)
15 | set.Add(i);
16 | int halfN = n/2;
17 | for (int i = 0; i < list.Length; i++)
18 | {
19 | if (list[i] > halfN)
20 | {
21 | int diff = n-list[i];
22 | if (set.Contains(diff))
23 | Console.WriteLine(diff + " " + list[i]);
24 | }
25 | }
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter18/question1801.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter18
8 | {
9 | class question1801
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | Console.WriteLine(Add(10, 11));
14 | Console.Read();
15 | }
16 |
17 | public static int Add(int a, int b)
18 | {
19 | if (b == 0)
20 | return a;
21 | int sum = a ^ b;
22 | int carry = (a & b) << 1;
23 | return Add(sum, carry);
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter18/question1802.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter18
8 | {
9 | class question1802
10 | {
11 | public static void Shuffle(int[] cards)
12 | {
13 | Random r = new Random();
14 | for (int i = 0; i < cards.Length; i++)
15 | {
16 | int index = r.Next(cards.Length - i) + i;
17 | int temp = cards[i];
18 | cards[i] = cards[index];
19 | cards[index] = temp;
20 | }
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/InterviewPrep/chapter18/question1806.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.chapter18
8 | {
9 | class question1806
10 | {
11 | public static int Select(int[] array, int left, int right, int rank)
12 | {
13 | Random r = new Random();
14 | int pivot = array[r.Next(left, right + 1)];
15 |
16 | int leftEnd = Parition(array, left, right, pivot);
17 |
18 | int leftSize = leftEnd - left + 1;
19 | if (leftSize == rank + 1)
20 | {
21 | int max = Int32.MinValue;
22 | for (int i = left; i <= leftEnd; i++)
23 | if (array[i] > max)
24 | max = array[i];
25 | return max;
26 | }
27 | else if (rank < leftSize)
28 | return Select(array, left, leftEnd, rank);
29 | else
30 | return Select(array, leftEnd + 1, right, rank - leftSize);
31 | }
32 |
33 | public static int Parition(int[] array, int left, int right, int pivot)
34 | {
35 | while (true)
36 | {
37 | while (left <= right && array[left] <= pivot)
38 | left++;
39 | while (left <= right && array[right] > pivot)
40 | right--;
41 | if (left > right)
42 | return left - 1;
43 | Swap(array, left, right);
44 | }
45 | }
46 |
47 | public static void Swap(int[] array, int first, int second)
48 | {
49 | int temp = array[first];
50 | array[first] = array[second];
51 | array[second]= temp;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/InterviewPrep/common/CombinationPermutation.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.common
8 | {
9 | class CombinationPermutation
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | List test = GetPermutation("abcd");
14 | foreach (String s in test)
15 | {
16 | Console.WriteLine("["+s+"]");
17 | }
18 | Console.Read();
19 | }
20 |
21 | static List GetCombination(String s)
22 | {
23 | List newList = new List();
24 | if (s.Length <= 1)
25 | {
26 | newList.Add(s);
27 | return newList;
28 | }
29 | List sub = GetCombination(s.Substring(1, s.Length - 1));
30 | foreach (String ss in sub)
31 | {
32 | for (int i = 0; i < ss.Length + 1; i++)
33 | {
34 | String next = ss.Substring(0, i) + s[0] + ss.Substring(i, ss.Length - i);
35 | newList.Add(next);
36 | }
37 | }
38 | return newList;
39 | }
40 |
41 | static List GetPermutation(String s)
42 | {
43 | List result = new List();
44 | if (s.Length == 0)
45 | {
46 | result.Add(s);
47 | return result;
48 | }
49 | List last = GetPermutation(s.Substring(1, s.Length - 1));
50 | foreach (String ss in last)
51 | {
52 | result.Add(s[0] + ss);
53 | result.Add(ss);
54 | }
55 | return result;
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/InterviewPrep/common/LowestCommonAncestor .cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.common
8 | {
9 | class LowestCommonAncestor
10 | {
11 | //See 0407
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/InterviewPrep/common/MaxSubarray.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.common
8 | {
9 | class MaxSubarray
10 | {
11 | public static int MaxSubArray(int[] a)
12 | {
13 | int max = 0;
14 | int maxEnding = 0;
15 | for (int i = 0; i < a.Length; i++)
16 | {
17 | int currentEnding = maxEnding + a[i];
18 | maxEnding = Math.Max(0, currentEnding);
19 | max = Math.Max(maxEnding, max);
20 | }
21 | return max;
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/InterviewPrep/common/MergeSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.common
8 | {
9 | class MergeSort
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | int[] a = new int[] { 1, 3, 2, 5, 3, 2, 3, 4, 5, 3, 2 };
14 | int[] a2 = new int[a.Length];
15 | for (int i = 0; i < a.Length; i++)
16 | a2[i] = a[i];
17 | MSort(a, 0, a.Length - 1);
18 | Array.Sort(a2);
19 | Console.WriteLine("Completed");
20 | Console.Read();
21 | }
22 |
23 | public static void MSort(int[] a, int low, int high)
24 | {
25 | if (low < high)
26 | {
27 | int middle = (low + high) / 2;
28 | MSort(a,low, middle);
29 | MSort(a,middle + 1, high);
30 | Merge(a, low,middle, high);
31 | }
32 | }
33 |
34 | public static void Merge(int[] a, int low, int middle, int high)
35 | {
36 | int[] helper = new int[a.Length];
37 | for (int i = low; i <= high; i++)
38 | helper[i] = a[i];
39 |
40 | int leftP = low;
41 | int rightP = middle + 1;
42 | int p = low;
43 | while (leftP <= middle && rightP <= high)
44 | {
45 | if (helper[leftP] <= helper[rightP])
46 | {
47 | a[p] = helper[leftP];
48 | leftP++;
49 | }
50 | else
51 | {
52 | a[p] = helper[rightP];
53 | rightP++;
54 | }
55 | p++;
56 | }
57 |
58 |
59 | for (int i = leftP ; i <= middle; i++, p++)
60 | {
61 | a[p] = helper[i];
62 | }
63 |
64 | }
65 |
66 |
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/InterviewPrep/common/PriorityQueue.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.common
8 | {
9 | class PriorityQueue
10 | {
11 | static void NotMain(String[] args)
12 | {
13 | PriorityQueue q = new PriorityQueue(new int[] { 5, 6, 8, 1 });
14 | //q.Debug();
15 | Console.WriteLine(q.GetMax());
16 | //q.Debug();
17 | Console.WriteLine(q.GetMax());
18 | Console.WriteLine(q.GetMax());
19 | Console.WriteLine(q.GetMax());
20 | Console.Read();
21 | }
22 |
23 | int[] a;
24 | int heapSize;
25 | public PriorityQueue(int[] a)
26 | {
27 | this.a = a;
28 | heapSize = a.Length;
29 | BuildMaxHeap();
30 | }
31 |
32 | public void Debug()
33 | {
34 | for (int i = 0; i < heapSize;i++ )
35 | Console.Write(a[i] + " ");
36 | Console.WriteLine();
37 | }
38 |
39 | public int GetMax()
40 | {
41 | if (heapSize == 0)
42 | throw new Exception("Queue is empty");
43 | int result = a[0];
44 | Swap(0, heapSize-1);
45 | heapSize--;
46 | MaxHeapify(0);
47 | return result;
48 | }
49 |
50 | private void MaxHeapify(int i)
51 | {
52 | int l = LeftChild(i);
53 | int r = RightChild(i);
54 | int max = i;
55 | int maxValue = a[i];
56 | if (l < heapSize && a[l] > maxValue)
57 | {
58 | max = l;
59 | maxValue = a[l];
60 | }
61 | if (r < heapSize && a[r] > maxValue)
62 | max = r;
63 | if (max != i)
64 | {
65 | Swap(max, i);
66 | MaxHeapify(max);
67 | }
68 | }
69 |
70 | private void BuildMaxHeap()
71 | {
72 | int middle = (a.Length+1)/ 2-1;
73 | for (int i = middle; i >= 0; i--)
74 | MaxHeapify(i);
75 | }
76 |
77 | private void Swap(int m, int n)
78 | {
79 | int temp = a[m];
80 | a[m] = a[n];
81 | a[n] = temp;
82 | }
83 |
84 | private static int Parent(int i)
85 | {
86 | return (i + 1) / 2 - 1;
87 | }
88 |
89 | private static int LeftChild(int i)
90 | {
91 | return 2 * i + 1;
92 | }
93 |
94 | private static int RightChild(int i)
95 | {
96 | return 2 * i + 2;
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/InterviewPrep/common/QuickSort.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.common
8 | {
9 | class QuickSort
10 | {
11 | public static void NotMain(String[] args)
12 | {
13 | int[] a = new int[] { 1, 3, 2, 5, 3, 2, 3, 4, 5, 3, 2 };
14 | int[] a2 = new int[a.Length];
15 | for (int i = 0; i < a.Length; i++)
16 | a2[i] = a[i];
17 | QSort(a, 0, a.Length-1);
18 | Array.Sort(a2);
19 | for (int i = 0; i < a.Length; i++)
20 | if (a[i] != a2[i])
21 | Console.WriteLine("false");
22 | Console.WriteLine("Completed");
23 | Console.Read();
24 | }
25 |
26 | public static void QSort(int[] a, int left, int right)
27 | {
28 | int index = Parition(a, left, right);
29 | if (left < index - 1)
30 | QSort(a, left, index - 1);
31 | if (index < right)
32 | QSort(a, index, right);
33 | }
34 |
35 | public static int Parition(int[] a,int left, int right)
36 | {
37 | int pivot = (left + right) / 2;
38 |
39 | while (left <= right)
40 | {
41 | while (a[left] < a[pivot])
42 | left++;
43 | while (a[right] > a[pivot])
44 | right--;
45 | if (left <= right)
46 | {
47 | Swap(a, left, right);
48 | left++;
49 | right--;
50 | }
51 | }
52 | return left;
53 | }
54 |
55 |
56 | public static void Swap(int[] a, int first, int second)
57 | {
58 | int temp = a[first];
59 | a[first] = a[second];
60 | a[second] = temp;
61 | }
62 |
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/InterviewPrep/common/ReverseWords.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace InterviewPrep.common
8 | {
9 | class ReverseWords
10 | {
11 |
12 | static void NotMain(String[] args)
13 | {
14 | String s = "abc def zcc";
15 | Console.WriteLine("[]");
16 | Console.WriteLine("["+ReverseWord(s)+"]");
17 | Console.Read();
18 | }
19 |
20 | static String ReverseWord(String s)
21 | {
22 |
23 | StringBuilder result = new StringBuilder();
24 | s = s + " ";
25 | int begin = 0;
26 | int end = 0;
27 | for (int i = 0; i < s.Length; i++)
28 | {
29 | if (s[i] == ' ')
30 | {
31 | for (int j = end - 1; j >= begin; j--)
32 | {
33 | result.Append(s[j]);
34 | }
35 | end += 1;
36 | begin = end;
37 | result.Append(" ");
38 | }
39 | else
40 | {
41 | end++;
42 | }
43 | }
44 | return result.ToString(0,result.Length-1);
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Test/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("Test")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("Test")]
13 | [assembly: AssemblyCopyright("Copyright © 2013")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("a8e7104b-ba04-4336-ac58-61b10bfc198c")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Test/Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | {61FAF64B-22CF-4A48-A6F5-178E4E022F2A}
7 | Library
8 | Properties
9 | Test
10 | Test
11 | v4.5
12 | 512
13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
14 | 10.0
15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages
17 | False
18 | UnitTest
19 |
20 |
21 | true
22 | full
23 | false
24 | bin\Debug\
25 | DEBUG;TRACE
26 | prompt
27 | 4
28 |
29 |
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 | {698dbb7d-cd16-4a01-bbc3-20167d7a714b}
59 | InterviewPrep
60 |
61 |
62 |
63 |
64 |
65 |
66 | False
67 |
68 |
69 | False
70 |
71 |
72 | False
73 |
74 |
75 | False
76 |
77 |
78 |
79 |
80 |
81 |
82 |
89 |
--------------------------------------------------------------------------------
/Test/UnitTest1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using InterviewPrep;
3 | using Microsoft.VisualStudio.TestTools.UnitTesting;
4 |
5 | namespace Test
6 | {
7 | [TestClass]
8 | public class UnitTest1
9 | {
10 | [TestMethod]
11 | public void TestMethod1()
12 | {
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------