The post Set Matrix Zeroes appeared first on fizzbuzzer.

]]>Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. Example 1: Input:

[ [1,1,1], [1,0,1], [1,1,1] ]Output:

[ [1,0,1], [0,0,0], [1,0,1] ]

We will use the first cell of every row and column as a flag. This flag would determine whether a row or column should set to zero. These flags are used later to update the matrix. If the first cell of a row is set to zero this means the row should be marked zero. If the first cell of a column is set to zero this means the column should be marked zero. The first cell of row and column for the first row and first column is the same i.e. matrix[0][0]. Hence, we use additional variables to tell us if the first column and row had been marked.

```
class Solution {
public void setZeroes(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRow = false;
boolean firstCol = false;
for (int r=0; r<rows; r++) {
for (int c=0; c<cols; c++) {
if (matrix[r][c] == 0) {
matrix[r][0] = 0;
matrix[0][c] = 0;
if (r==0) {
firstRow = true;
}
if (c==0) {
firstCol = true;
}
}
}
}
for (int r=1; r<rows; r++) {
for (int c=1; c<cols; c++) {
if (matrix[r][0]==0) {
matrix[r][c] = 0;
}
if (matrix[0][c]==0) {
matrix[r][c] = 0;
}
}
}
if (firstRow) {
for (int c=0; c<cols; c++) {
matrix[0][c] = 0;
}
}
if (firstCol) {
for (int r=0; r<rows; r++) {
matrix[r][0] = 0;
}
}
}
}
```

The post Set Matrix Zeroes appeared first on fizzbuzzer.

]]>The post Partition List appeared first on fizzbuzzer.

]]>Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

**Example**

Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5

**Solution**

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode partition(ListNode head, int x) { if (head == null) { return head; } ListNode smallHead = new ListNode(0); ListNode small = smallHead; ListNode largereqHead = new ListNode(0); ListNode largereq = largereqHead; ListNode current = head; while (current != null) { if (current.val < x) { small.next = current; small = small.next; } else { largereq.next = current; largereq = largereq.next; } current = current.next; } largereq.next = null; small.next = largereqHead.next; return smallHead.next; } }

The post Partition List appeared first on fizzbuzzer.

]]>The post Implement strStr() appeared first on fizzbuzzer.

]]>Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Input: haystack = "hello", needle = "ll" Output: 2

```
class Solution {
public int strStr(String haystack, String needle) {
char[] source = haystack.toCharArray();
char[] target = needle.toCharArray();
if (target.length == 0) {
return 0;
}
for (int i=0; i<source.length; i++) {
int t = 0;
int s = i;
while (source[s] == target[t] && i+target.length <= source.length) {
s++;
t++;
if (t==target.length) {
return i;
}
}
}
return -1;
}
}
```

The post Implement strStr() appeared first on fizzbuzzer.

]]>The post Remove Element appeared first on fizzbuzzer.

]]>Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.

**Solution**

public class RemoveElement { public static int removeElement(int[] nums, int val) { int newLen = nums.length; for (int i = 0; i < nums.length; i++) { if (nums[i] == val) { newLen--; } } int lastIndex = -1; for (int i = 0; i < nums.length; i++) { if (nums[i] == val && lastIndex == -1) { lastIndex = i; } else if (nums[i] != val && lastIndex >= 0) { nums[lastIndex] = nums[i]; lastIndex++; } } return newLen; } public static void main(String[] args) { int[] nums = new int[]{0, 1, 2, 2, 3, 0, 4, 2}; int len = removeElement(nums, 2); for (int i = 0; i < len; i++) { System.out.print(nums[i] + " "); } } }

The post Remove Element appeared first on fizzbuzzer.

]]>The post Remove Duplicates from Sorted Array appeared first on fizzbuzzer.

]]>Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.

```
class Solution {
public int removeDuplicates(int[] nums) {
int curr = 0;
for (int i=1; i<nums.length; i++) {
if (nums[i] != nums[curr]) {
curr++;
nums[curr] = nums[i];
}
}
return curr+1;
}
}
```

The post Remove Duplicates from Sorted Array appeared first on fizzbuzzer.

]]>The post Add Two Numbers appeared first on fizzbuzzer.

]]>You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

**Solution**

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0; while (p != null || q != null) { int x = (p != null) ? p.val : 0; int y = (q != null) ? q.val : 0; int sum = carry + x + y; carry = sum / 10; curr.next = new ListNode(sum % 10); curr = curr.next; if (p != null) p = p.next; if (q != null) q = q.next; } if (carry > 0) { curr.next = new ListNode(carry); } return dummyHead.next; }

The post Add Two Numbers appeared first on fizzbuzzer.

]]>The post Two Sum appeared first on fizzbuzzer.

]]>Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

**Example**

Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

**Solution**

public int[] twoSum(int[] nums, int target) { Mapmap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); }

The post Two Sum appeared first on fizzbuzzer.

]]>The post Setup WordPress on an AWS EC2 Instance appeared first on fizzbuzzer.

]]>CREATE USER 'blog_user'@'%'; GRANT ALL PRIVILEGES ON blog_db.* To 'blog_user'@'%' IDENTIFIED BY 's3cret';

To change it later you can use:

SET PASSWORD FOR 'blog_user'@'%' = PASSWORD('xxxx');

**Step 2: install WordPress**

Login into your AWS instance and run the following:

$ cd /var/www/html $ wget http://wordpress.org/latest.tar.gz $ tar -xzvf latest.tar.gz $ mv wordpress blog $ cd blog $ mv wp-config-sample.php wp-config.php

**Step 3: configure WordPress**

$ nano wp-config.php

Make sure it looks as follows:

define( 'DB_NAME', 'blog_db' ); /** MySQL database username */ define( 'DB_USER', 'blog_user' ); /** MySQL database password */ define( 'DB_PASSWORD', 's3cret' ); /** MySQL hostname */ define( 'DB_HOST', 'zzz.xxx.eu-central-2.rds.amazonaws.com:3306' );

**Step 4: add .htaccess**

In you /var/www/html/blog directory add a file named .htaccess with the following content:

RewriteEngine Off

# BEGIN WordPress <ifmodule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </ifmodule>

**Step 5: configure Apache**

Edit /etc/httpd/conf.d/ssl.conf and make sure it includes the following:

<virtualhost *:443> ServerName blog.com ServerAlias www.blog.com DocumentRoot "/var/www/html/blog" ErrorLog logs/ssl_error_blog_log TransferLog logs/ssl_access_blog_log LogLevel warn SSLEngine on SSLProtocol all -SSLv3 SSLProxyProtocol all -SSLv3 SSLHonorCipherOrder on SSLCertificateFile /etc/letsencrypt/live/blog.com/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/blog.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/liveblog.com/chain.pem </virtualhost>

**Step 6: give privileges for upload**

$ sudo chown -R apache:apache /var/www/html/blog/

**Step 7: set PHP upload limits**

$ nano /etc/php.ini

Make sure the following are set:

upload_max_filesize=256mb post_max_size=256M memory_limit=512M

More details about installing Apache on an AWS instance can be found at here. A how-to on installing PHP can be found here.

The post Setup WordPress on an AWS EC2 Instance appeared first on fizzbuzzer.

]]>The post Triple Sum appeared first on fizzbuzzer.

]]>Given arrays of different sizes, find the number of distinct triplets where is an element of , written as , , and , satisfying the criteria: and

For example, given and we find four distinct triplets: $latex(3,6,4), (3,6,6), (5,6,4), (5,6,6)$

**Function Description**

Complete the triplets function in the editor below. It must return the number of distinct triplets that can be formed from the given arrays.

`triplets`

has the following parameter(s):

`a`

, `b`

, `c`

: three arrays of integers.

**Input Format**

The first line contains integers , the sizes of the three arrays.

The next lines contain space-separated integers numbering respectively.

**Constraints**

**Output Format**

Print an integer representing the number of distinct triplets.

**Sample Input 0**

```
3 2 3
1 3 5
2 3
1 2 3
```

**Sample Output 0**

```
8
```

**Explanation 0**

The special triplets are .

**Solution**

public class TripleSum { static int binarySearchIndexForValueLessEqual(int[] arr, int l, int h, int searchVal) { if (l < h) { int mid = (l + h) / 2; if (searchVal < arr[mid]) { return binarySearchIndexForValueLessEqual(arr, l, mid - 1, searchVal); } int result = binarySearchIndexForValueLessEqual(arr, mid + 1, h, searchVal); if (result == -1) { return mid; } else { return result; } } else { if (arr[l] <= searchVal) { return l; } else { return -1; } } } static long triplets(int[] a, int[] b, int[] c) { int[] arr = Arrays.stream(a).sorted().distinct().toArray(); int[] brr = Arrays.stream(b).sorted().distinct().toArray(); int[] crr = Arrays.stream(c).sorted().distinct().toArray(); Map<Integer, Integer> smallerIndexA = new HashMap<>(); Map<Integer, Integer> smallerIndexC = new HashMap<>(); long count = 0; for (int i = 0; i < brr.length; i++) { int left = binarySearchIndexForValueLessEqual(arr, 0, arr.length - 1, brr[i]) + 1; smallerIndexA.put(brr[i], left); int right = binarySearchIndexForValueLessEqual(crr, 0, crr.length - 1, brr[i]) + 1; smallerIndexC.put(brr[i], right); count += ((long)left * (long)right); } return count; } public static void main(String[] args) throws IOException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in4.txt")); Scanner scanner = new Scanner(System.in); String[] lenaLenbLenc = scanner.nextLine().split(" "); int lena = Integer.parseInt(lenaLenbLenc[0]); int lenb = Integer.parseInt(lenaLenbLenc[1]); int lenc = Integer.parseInt(lenaLenbLenc[2]); int[] arra = new int[lena]; String[] arraItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < lena; i++) { int arraItem = Integer.parseInt(arraItems[i]); arra[i] = arraItem; } int[] arrb = new int[lenb]; String[] arrbItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < lenb; i++) { int arrbItem = Integer.parseInt(arrbItems[i]); arrb[i] = arrbItem; } int[] arrc = new int[lenc]; String[] arrcItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < lenc; i++) { int arrcItem = Integer.parseInt(arrcItems[i]); arrc[i] = arrcItem; } long ans = triplets(arra, arrb, arrc); System.out.println(ans); scanner.close(); } }

The post Triple Sum appeared first on fizzbuzzer.

]]>The post Ice Cream Parlor appeared first on fizzbuzzer.

]]>Each time Sunny and Johnny take a trip to the Ice Cream Parlor, they pool their money to buy ice cream. On any given day, the parlor offers a line of flavors. Each flavor has a cost associated with it.

Given the value of and the of each flavor for trips to the Ice Cream Parlor, help Sunny and Johnny choose two distinct flavors such that they spend their entire pool of money during each visit. ID numbers are the 1- based index number associated with a . For each trip to the parlor, print the ID numbers for the two types of ice cream that Sunny and Johnny purchase as two space-separated integers on a new line. You must print the smaller ID first and the larger ID second.

For example, there are flavors having . Together they have to spend. They would purchase flavor ID’s and for a cost of . Use based indexing for your response.

**Note:**

Two ice creams having unique IDs and may have the same cost (i.e., ).

There will always be a unique solution.

**Input Format**

The first line contains an integer, , the number of trips to the ice cream parlor.

Each of the next sets of lines is as follows:

– The first line contains .

– The second line contains an integer, , the size of the array .

– The third line contains space-separated integers denoting the .

**Output Format**

Print two space-separated integers denoting the respective indices for the two distinct flavors they choose to purchase in ascending order. Recall that each ice cream flavor has a unique ID number in the inclusive range from to .

**Sample Input**

```
2
4
5
1 4 5 3 2
4
4
2 2 4 3
```

**Sample Output**

```
1 4
1 2
```

**Explanation**

Sunny and Johnny make the following two trips to the parlor:

– The first time, they pool together dollars. There are five flavors available that day and flavors and have a total cost of .

– The second time, they pool together dollars. There are four flavors available that day and flavors and have a total cost of .

**Solution**

public class IceCreamParlor2 { // Complete the whatFlavors function below. static void whatFlavors(int[] cost, int money) { Map<Integer, Integer> value2index = new HashMap<Integer, Integer>(); for (int i=0; i<cost.length; i++) { int num = cost[i]; if (value2index.containsKey(money-num)) { int id1 = value2index.get(money-num); System.out.println(id1+" "+(i+1)); break; } else { value2index.put(num, i+1); } } } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int t = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int tItr = 0; tItr < t; tItr++) { int money = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] cost = new int[n]; String[] costItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int costItem = Integer.parseInt(costItems[i]); cost[i] = costItem; } whatFlavors(cost, money); } scanner.close(); } }

The post Ice Cream Parlor appeared first on fizzbuzzer.

]]>