Friday, August 25, 2017

Codility - Lesson 3 Time complexity - 3. TapeEquilibrium

Source Link: 
https://codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/

Question: 
A non-empty zero-indexed array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 We can split this tape in four places:
  • P = 1, difference = |3 − 10| = 7
  • P = 2, difference = |4 − 9| = 5
  • P = 3, difference = |6 − 7| = 1
  • P = 4, difference = |10 − 3| = 7
Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.
For example, given:
A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 the function should return 1, as explained above.
Assume that:
  • N is an integer within the range [2..100,000];
  • each element of array A is an integer within the range [−1,000..1,000].
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

My Solution: 
Notes: 
1. Using the concept of Sum
    (sum of the 2nd part) = Sum - (sum of the 1st part)

    importantly, difference = |(sum of the 2nd part) - (sum of the 1st part)|
2. First, compute the sum (will be used for several times)
int sum =0; // initial
for(int i=0; i< A.length; i++){
sum = sum + A[i];

3. then, find the minimum difference
initial setting: Integer.MAX_VALUE
int min_diff = Integer.MAX_VALUE
4.  try to compute the above values in "one pass"!
no need to use the second for loop (important)
sum_part_one = sum_part_one + A[p-1]; // the sum of part one
sum_part_two = sum - sum_part_one; // the sum of part two
diff = sum_part_one - sum_part_two; // the difference
if(diff <0) // absolute value
diff = -diff; // all the values can be computed (one pass)
min_diff = Math.min(min_diff, diff); // min difference
5. return the min difference 
return min_diff;        

Codility - Lesson 3 Time complexity - 2. FrogJmp

Source Link:
https://codility.com/programmers/lessons/3-time_complexity/frog_jmp/

Question:
A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
Count the minimal number of jumps that the small frog must perform to reach its target.
Write a function:
class Solution { public int solution(int X, int Y, int D); }
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example, given:
X = 10 Y = 85 D = 30 the function should return 3, because the frog will be positioned as follows:
  • after the first jump, at position 10 + 30 = 40
  • after the second jump, at position 10 + 30 + 30 = 70
  • after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that:
  • X, Y and D are integers within the range [1..1,000,000,000];
  • X ≤ Y.
Complexity:
  • expected worst-case time complexity is O(1);
  • expected worst-case space complexity is O(1).
My Solution:
Notes:
1.  need to decide if to "plus one" or not
long plus =0;
2. using "mod" to decide
if( difference % D !=0
plus =1; // if not "perfectly Divisible", then plus one  
3. number of hops the frog needs to jump
hop = difference / D;
hop = hop + plus;  

Codility - Lesson 3 Time complexity - 1. PermMissingElem

Source Link:
https://codility.com/programmers/lessons/3-time_complexity/perm_missing_elem/

Question:
A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
Your goal is to find that missing element.
Write a function:

class Solution { public int solution(int[] A); }
that, given a zero-indexed array A, returns the value of the missing element.
For example, given array A such that:
A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5 the function should return 4, as it is the missing element.
Assume that:

  • N is an integer within the range [0..100,000];
  • the elements of A are all distinct;
  • each element of array A is an integer within the range [1..(N + 1)].
Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

My Solution:
Notes:
1.  Using the concept of "Sum = (ceiling + floor) * height /2"
     So---> Sum = (1 + N+1) * N /2
     the missing element can be found by minus other elements
2.  Need to use "long" to avoid potential bugs (large numbers)
3. Because there is one element "missing" , need to plus extra "1" (be careful about this) 
long height = A.length + 1
4. Minus other elements 
for(int i=0; i<A.length; i++){
missing_number = missing_number - A[i]; // minus other elements
}
5. return the missing element (long->int)
return (int)missing_number;   

Codility - Lesson 3 Time complexity

Source Link: 
https://codility.com/programmers/lessons/3-time_complexity/ 

Some Notes: 
Use of time complexity makes it easy to estimate the running time of a program.

 3.1: Which is the dominant operation? 
1 def dominant(n): 
2 result = 0 
3 for i in xrange(n): 
4 result += 1 
5 return result

The operation in line 4 is dominant and will be executed n times. The complexity is described in Big-O notation: in this case O(n) — linear complexity.

3.3: Logarithmic time — O(log n).
1 def logarithmic(n):
2 result = 0
3 while n > 1:
4 n //= 2
5 result += 1
6 return result 


The value of n is halved on each iteration of the loop.


3.4. Exercise

Problem: You are given an integer n. Count the total of 1 + 2+. . . + n.

Solution: The task can be solved in several ways. 


The third person’s solution is even quicker.

3.9: Model solution — time complexity O(1).
1 def model_solution(n):
2 result = n * (n + 1) // 2
3 return result


Very Important: 
Sum = (ceiling + floor) * height / 2
(with low time complexity~~~)

Thursday, August 24, 2017

Codility - Lesson 2 Arrays - 2. CyclicRotation

Source Link:
https://codility.com/programmers/lessons/2-arrays/cyclic_rotation/

Question:
A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.
Write a function:

class Solution { public int[] solution(int[] A, int K); }
that, given a zero-indexed array A consisting of N integers and an integer K, returns the array A rotated K times.
For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8].
Assume that:

  • N and K are integers within the range [0..100];
  • each element of array A is an integer within the range [−1,000..1,000].
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.

My Solution:
Note: 
1. Using the concept of "mod" (to make it cyclic)
for(int i=0; i< A.length; i++){
int new_position = (i + K) % A.length;    // using "mod" to do Cyclic Rotation  
new_array[new_position] = A[i];             // put A[i] to the new position
 

Codility - Lesson 2 Arrays - 1. OddOccurrencesInArray

Source Link:
https://codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/

Question:
A non-empty zero-indexed array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9
  • the elements at indexes 0 and 2 have value 9,
  • the elements at indexes 1 and 3 have value 3,
  • the elements at indexes 4 and 6 have value 9,
  • the element at index 5 has value 7 and is unpaired.
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
For example, given array A such that:
A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the function should return 7, as explained in the example above.
Assume that:
  • N is an odd integer within the range [1..1,000,000];
  • each element of array A is an integer within the range [1..1,000,000,000];
  • all but one of the values in A occur an even number of times.
Complexity:
  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

My Solution:
Note: 
Using the concept of "XOR" (^)
When there is a pair A and B,  A^B will be zero
A^B^C (where C is not paired), then A^B^C = C 
for(int i=1; i< A.length; i++){ 
unpaired = unpaired ^ A[i];   // xor  
}

Codility - Lesson 2 Arrays

Source Link:
https://codility.com/programmers/lessons/2-arrays/

Some Notes:
Array is a data-structure that can be used to store many items in one place.

2.4. Iterating over an array

Knowing that the array contains of N elements, we can iterate over consecutive integers from index 0 to index N −1.

2.6. Exercise

Problem: Given array A consisting of N integers, return the reversed array.

Solution: We can iterate over the first half of the array and exchange the elements with those in the second part of the array.


Reversing an array.
1 def reverse(A):
2 N = len(A)
3 for i in xrange(N // 2):      // i from first to last until N/2 <--- important
4 k = N - i - 1                      // k from last to first until N/2 (let k = N-i-1)
5 A[i], A[k] = A[k], A[i]    // then, swap A[i] A[k]
6 return A                           // reverse the array

Wednesday, August 23, 2017

Codility - Lesson 1 Iterations - 1. BinaryGap

Source Link:
https://codility.com/programmers/lessons/1-iterations/binary_gap/

Question: 
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.
Write a function:
class Solution { public int solution(int N); }
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.
Assume that:
  • N is an integer within the range [1..2,147,483,647].
Complexity:
  • expected worst-case time complexity is O(log(N));
  • expected worst-case space complexity is O(1).

My Solution:
Note: 
1. Using While Loop
2. Using the "concept of bit manipulation" and "& operation"
3.  Cannot use n&1 withoug "()"
if( (N&1) == 1){
counting = true;
}
4. shift by one (right side) 
// note: cannot just write "N >> 1"
N = N >> 1 

Codility - Lesson 1 Iterations

Source Link:
https://codility.com/programmers/lessons/1-iterations/

Some Notes:
In programming, iterating means repeating some part of your program.

1.1. For loops

Example 1:
The factorial of n is n! = 1 · 2 · . . . · n.

Code:
1 factorial = 1
2 for i in range (1, n + 1):
3 factorial *= i

Example 2: 
Let’s print a triangle made of asterisks (‘*’) separated by spaces. The triangle should consist of n rows, where n is a given positive integer, and consecutive rows should contain 1, 2, . . . , n asterisks. For example, for n = 4 the triangle should appear as follows:
*
* *
* * *
* * * *

Code:
1 for i in range(1, n + 1):
2 for j in range(i):
3 print ’*’,
4 print

We need to use two loops. (the second loop j <= i)

Example 3: 
Let’s print a triangle made of asterisks (‘*’) separated by spaces and consisting of n rows again, but this time upside down, and make it symmetrical. Consecutive rows should contain 2n − 1, 2n − 3, . . . , 3, 1 asterisks and should be indented by 0, 2, 4, . . . , 2(n − 1) spaces. For example, for n = 4 the triangle should appear as follows:
* * * * * * *
   * * * * *
     * * *
        *

Code:
1 for i in range(n, 0, -1):
2 for j in range(n - i):
3 print ’ ’,
4 for j in range(2 * i - 1):
5 print ’*’,
6 print


1.2. While loops

Example 4: 
Given a positive integer n, how can we count the number of digits in its decimal representation? One way to do it is convert the integer into a string and count the characters. Here, though, we will use only arithmetical operations instead. We can simply keep dividing the number by ten and count how many steps are needed to obtain 0.

Code:
1 result = 0
2 while n > 0:
3 n = n // 10
4 result += 1

The above skill is important.

Example 5:
The Fibonacci numbers4 form a sequence of integers defined recursively in the following way. The first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. The first few elements in this sequence are: 0, 1, 1, 2, 3, 5, 8, 13. Let’s write a program that prints all the Fibonacci numbers, not exceeding a given integer n.

Code:
1 a = 0
2 b = 1
3 while a <= n:
4 print a
5 c = a + b
6 a = b
7 b = c


Sunday, August 20, 2017

LeetCode - 26. Remove Duplicates from Sorted Array

Source Link:
https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 

Question:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2]


Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. 

My Solution: Note:
1. we need to return "the new length" and need to "modify the given array"
2. it doesn't matter what you leave beyond the new length (simple)
3. the array has been sorted (so only need one pass)
4. the value that we need to compare with
int index = nums[0];
5. a different value appears
if(nums[i] != index){
index = nums[i];       // change the value that we need to compare with
nums[count]=index; // modify the given array
count++;                   // the new length++
}

6. skip the case: nums[i] == index
7. return the new length
return count;

LeetCode - 21. Merge Two Sorted Lists

Source Link:
https://leetcode.com/problems/merge-two-sorted-lists/description/ 

Question:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

My Solution: Note:
1. we create a "dummy node" to be the "previous node" of the head of the new list to avoid some potential bugs (and to keep the 1st node)
2. process the nodes of both lists (until one node becomes "null")
while(a != null && b != null)
3. case 1: a is smaller than b
if(a.val <= b.val){
current.next = a;
a = a.next;
current = current.next;
}

4. case 2: b is smaller than a
else{
current.next = b;
b = b.next;
current = current.next;
}

5. the remaining nodes
if(a == null){
current.next = b;
}
if(b == null){
current.next = a;
}

6. dummy.next is the "1st" node
return dummy.next;

Saturday, August 19, 2017

LeetCode - 19. Remove Nth Node From End of List

Source Link:
https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ 

Question:
Given a linked list, remove the nth node from the end of list and return its head.

For example, 
Given linked list: 1->2->3->4->5, and n = 2. 
After removing the second node from the end, the linked list becomes 1->2->3->5

Hint:
https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution/

My Solution:
Note:
1. we will add an auxiliary "dummy" node, which points to the list head. The "dummy" node is used to simplify some corner cases such as a list with only one node, or removing the head of the list.
2. Remove the (L−n+1)th node from the beginning in the list, where L is the list length. This problem is easy to solve once we found list length L.
3. starts from the "head" to count the length of the list.
ListNode dummy = new ListNode(0);
dummy.next = head;

4. starts from the "dummy", so we can remove the "head" (without extra error)
current = dummy;
5. the node number (that we want to remove)
while(node_number != L-n+1){
current = current.next;
node_number++;
}

6. remove the node
current.next = current.next.next; 
7.
return dummy.next;

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...