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.

]]>The post Better Compression appeared first on fizzbuzzer.

]]>Consider a string, S, that is a series of characters, each followed by its frequency as an integer. The string is not compressed correctly, so there may be many occurrences of the same character. A properly compressed string will consist of one instance of each character in alphabetical order followed by the total count of that character within the string.

For example, the string a3c9b2c1 has two instances where ‘c’ is followed by a count: once with 9 occurrences, and again with 1. It should be compressed to a3b2c10.

**Function Description**

Complete the function betterCompression in the editor below. The function must return the properly compressed string.

`betterCompression`

has the following parameter:

S: a string

**Constraints**

1 ≤ size of S ≤ 100000

‘a’ ≤ characters in S ≤ ‘z’

1 ≤ frequency of each character in S ≤ 1000

**Sample Input For Custom Testing**

```
a12b56c1
```

**Sample Output**

```
a12b56c1
```

**Explanation**

Nothing gets changed here since each character occurred only once and they are already in the sorted order.

**Solution**

public class BetterCompression { public static String betterCompression(String s) { char[] str = s.toCharArray(); int[] map = new int[26]; int i = 0; int n = s.length(); while (i < n) { char ch = str[i]; if (ch >= 'a' && ch <= 'z') { int start = i + 1; int end = start; while (end < n && (str[end] >= '0' && str[end] <= '9')) { end++; } int count = Integer.parseInt(s.substring(start, end)); map[ch - 'a'] += count; i = end; } else { i++; } } StringBuilder sb = new StringBuilder(); for (char ch = 'a'; ch <= 'z'; ch++) { if (map[ch - 'a'] > 0) { sb.append(ch); sb.append(map[ch - 'a']); } } return sb.toString(); } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in7.txt")); Scanner outputScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "out7.txt")); Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); String expected = outputScanner.nextLine(); String result = betterCompression(s); if (s.equals(expected)) { System.out.println("Fail! Expected '" + expected + "' got '" + result + "'"); } else { System.out.println(result); } //System.out.println(betterCompression("a12c56a1b5")); } }

The post Better Compression appeared first on fizzbuzzer.

]]>The post Mud Walls appeared first on fizzbuzzer.

]]>A child likes to build mud walls by placing mud between sticks positioned on a number line. The gap between sticks will be referred to as a cell, and each cell will contain one segment of wall. The height of mud in a segment cannot exceed 1 unit above an adjacent stick or mud segment. Given the placement of a number of sticks and their heights, determine the maximum height segment of mud that can be built. If no mud segment can be built, return 0.

For example, there are n = 3 sticks at stickPositions = [1, 2, 4, 7] with stickHeights = [4, 5, 7, 11]. There is no space between the first two sticks, so there is no cell for mud. Between positions 2 and 4, there is one cell. Heights of the surrounding sticks are 5 and 7, so the maximum height of mud is 5 + 1 = 6. Between positions 4 and 7 there are two cells. The heights of surrounding sticks are 7 and 11. The maximum height mud segment next to the stick of height 7 is 8. The maximum height mud next to a mud segment of height 8 and a stick of height 11 is 9. Mud segment heights are 6, 8 and 9, and the maximum height is 9. In the table below, digits are in the columns of sticks and M is in the mud segments.

```
7
7
M7
MM7
4MM7
M4MM7
2M4MM7
12M4MM7
12M4MM7
12M4MM7
12M4MM7
```

**Function Description**

Complete the function maxHeight in the editor below. The function must return an integer, the maximum height mud segment that can be built.

`maxHeight`

has the following parameter(s):

stickPositions[stickPositions[0],…stickPositions[n-1]]: an array of integers

stickHeights[stickHeights[0],…stickHeights[n-1]]: an array of integers

**Constraints**

1 ≤ n ≤ 105

1 ≤ stickPositions[i] ≤ 109 (where 0 ≤ i < n)

1 ≤ stickHeights[i] ≤ 109 (where 0 ≤ i < n)

**Sample Input For Custom Testing**

```
3
1
3
7
3
4
3
3
```

**Sample Output**

```
5
```

**Explanation**

```
M
1M MMM
1M3MMM7
1M3MMM7
1M3MMM7
```

Here stickPositions = [1, 3, 7] and stickHeights = [4, 3, 3]. There can be a segment of height 4 at position 2 supported by sticks of heights 4 and 3. Between positions 3 and 7, there can be a segment of height 4 at positions 4 and 6. Between them, a segment can be built of height 5 at position 5.

**Solution**

public class MudWalls { public static int maxHeight(int[] stickPositions, int[] stickHeights) { int n = stickPositions.length; int m = stickHeights.length; int max = 0; for (int i=0; i<n-1; i++) { if (stickPositions[i]<stickPositions[i+1]-1) { // We have a gap int heightDiff = Math.abs(stickHeights[i+1] - stickHeights[i]); int gapLen = stickPositions[i+1] - stickPositions[i] - 1; int localMax = 0; if (gapLen > heightDiff) { int low = Math.max(stickHeights[i+1], stickHeights[i]) + 1; int remainingGap = gapLen - heightDiff - 1; localMax = low + remainingGap/2; } else { localMax = Math.min(stickHeights[i+1], stickHeights[i]) + gapLen; } max = Math.max(max, localMax); } } return max; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in9.txt")); //Scanner outputScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "out.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] stickPositions = new int[n]; for (int i = 0; i < n; i++) { stickPositions[i] = scanner.nextInt(); } n = scanner.nextInt(); int[] stickHeights = new int[n]; for (int i = 0; i < n; i++) { stickHeights[i] = scanner.nextInt(); } System.out.println(maxHeight(stickPositions, stickHeights)); } }

The post Mud Walls appeared first on fizzbuzzer.

]]>The post Weird Faculty appeared first on fizzbuzzer.

]]>This semester you are taking a course taught by a faculty member who has a weird way of grading tests. In a test, n questions will be asked, and the correctness of the answers is already determined. For the ith question, the verdict will be v[i] (where 0 ≤ i < n). If v[i] = 1, the answer is correct but if v[i] = 0, the answer is wrong.

When a test is given, you have to answer the first k questions (indices 0 to k-1) where 0 ≤ k < n, and your friend has to answer the remaining questions (indices k to n-1) on the test. At the end, results are calculated as follows:

Your results:

```
int Your_result = 0;
for(int i=0;i<k;i++)
{
if(v[i]==1)
Your_result++;
else Your_result--;
}
```

Your friend’s results:

```
int YourFriend_result = 0;
for(int i=k;i<n;i++)
{
if(v[i]==1)
YourFriend_result++;
else YourFriend_result--;
}
```

Choose the minimum k such that Your_result > YourFriend_result.

**Function Description **

Complete the function exam in the editor below. The function must return an integer that denotes the minimum number of questions you must answer to have Your_result > YourFriend_result.

`exam`

has the following parameter(s):

v[v[0],…v[n-1]]: an array of integers

**Constraints**

1 ≤ n ≤ 105

v[i] ∈ {0,1} (where 0 ≤ i < n)

**Sample Input 0**

```
5
1
0
0
1
0
```

**Sample Output 0**

```
0
```

**Explanation 0**

n = 5

v = {1, 0, 0, 1, 0}

If you answer 0 questions (k=0) then Your_result = 0 and YourFriend_result = -1 (2 correct answers & 3 wrong answers).

**Solution**

public class WeirdFaculty { public static int exam(int[] a) { int n = a.length; int[] onesUntilIndex = new int[n + 1]; for (int i = 1; i <= n; i++) { onesUntilIndex[i] = a[i - 1] == 1 ? onesUntilIndex[i - 1] + 1 : onesUntilIndex[i - 1]; } int k = 0; for (int i = 0; i <= n; i++) { int your_ones = onesUntilIndex[i]; int you_zeros = i - your_ones; int your_sum = your_ones - you_zeros; int friend_ones = onesUntilIndex[n] - your_ones; int friend_zeros = (n - i) - friend_ones; int friend_sum = friend_ones - friend_zeros; if (your_sum > friend_sum) { k = i; break; } } return k; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in.txt")); //Scanner outputScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "out.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { int x = Integer.parseInt(scanner.next()); a[i] = x; } System.out.println(exam(a)); } }

The post Weird Faculty appeared first on fizzbuzzer.

]]>The post Longest Subarray appeared first on fizzbuzzer.

]]>A subarray of array a is defined as a contiguous block of a’s elements having a length that is less than or equal to the length of the array. For example, the subarrays of array a = [1, 2, 3] are [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3]. Given an integer, k = 3, the subarrays having elements that sum to a number ≤ k are [1], [2], and [1, 2]. The longest of these subarrays is [1, 2], which has a length of 2. Given an array, a, determine its longest subarray that sums to less than or equal to a given value k.

**Function Description **

Complete the function maxLength in the editor below. The function must return an integer that represents the length of the longest subarray of a that sums to a number ≤ k.

`maxLength`

has the following parameter(s):

a[a[0],…a[n-1]]: an array of integers

k: an integer

**Constraints**

1 ≤ n ≤ 105

1 ≤ a[i] ≤ 103

1 ≤ k ≤ 109

**Sample Input 0**

```
3
1
2
3
4
```

**Sample Output 0**

```
2
```

**Explanation 0**

The subarrays of [1, 2, 3] having elements that sum to a number ≤ (k = 4) are [1], [2], [3], and [1, 2]. The longest of these is [1, 2], which has a length of 2. Return 2 as the answer.

**Solution**

public class LongestSubarray { public static int maxLength(List<Integer> a, int k) { int maxLen = -1; int sum = 0; int start = 0; int end = 0; for (int i = 0; i < a.size(); i++) { sum += a.get(i); end = i; while (sum > k) { sum -= a.get(start); start++; } maxLen = Math.max(maxLen, end - start + 1); } return maxLen; } public static void main(String[] args) { System.out.println(maxLength(Arrays.asList(1,2,3), 7)); } }

The post Longest Subarray appeared first on fizzbuzzer.

]]>The post Maximum Difference in an Array appeared first on fizzbuzzer.

]]>You are given an array of integers and must compute the maximum difference between any item and any lower indexed smaller item for all the possible pairs, i.e., for a given array

`'a'`

, find the maximum value of `a[j] - a[i]`

for all `i`

, `j`

where `0 ≤ i < j < n`

and `a[i] < a[j]`

. If no item has a smaller item with a lower index, then return `-1`

.
For example, given an array `[1, 2, 6, 4]`

, you would first compare 2 to the elements to its left. 1 is smaller, so calculate the difference 2 – 1 = 1. 6 is bigger than 2 and 1, so calculate the differences 4 and 5. 4 is only bigger than 2 and 1, and the differences are 2 and 3. The largest difference was 6 – 1 = 5.

**Function Description **

Complete the function maxDifference in the editor below. The function must return an integer representing the maximum difference in a.

`maxDifference`

has the following parameter(s):

* a[a[0],a[1],…a[n-1]]: an array of integers

**Constraints**

1 ≤ n ≤ 2 × 105

−106 ≤ a[i] ≤ 106 ∀ i ∈ [0, n − 1]

**Sample Input 0**

```
7
2
3
10
2
4
8
1
```

**Sample Output**

```
8
```

**Explanation**

n = 7, a = [2, 3, 10, 2, 4, 8, 1]

Differences are calculated as:

3 – [2] = [1]

10 – [3, 2] = [7, 8]

4 – [2, 3, 2] = [2, 1, 2]

8 – [4, 2, 3, 2] = [4, 6, 5, 6]

The maximum is found at 10 – 2 = 8.

**Solution**

class MaxDifferenceInArray2 { public static int maxDifference(List<Integer> a) { int n = a.size(); int[] arr = new int[n]; for (int i=0; i<n; i++) { arr[i] = a.get(i); } int[] min = new int[n]; // min[i] min up to index i min[0] = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min[i - 1]) { min[i] = arr[i]; } else { min[i] = min[i - 1]; } } int max = Integer.MIN_VALUE; for (int i = 1; i < n; i++) { if (arr[i] > min[i - 1]) { max = Math.max(max, (a.get(i) - min[i - 1])); } } if (max == Integer.MIN_VALUE) { return -1; } else { return max; } } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in.txt")); //Scanner outputScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "out.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); List<Integer> a = new LinkedList<>(); for (int i = 0; i < n; i++) { int x = Integer.parseInt(scanner.next()); a.add(x); } System.out.println(a); System.out.println(maxDifference(a)); } }

The post Maximum Difference in an Array appeared first on fizzbuzzer.

]]>The post Fun with Anagrams appeared first on fizzbuzzer.

]]>Two strings are anagrams if they are permutations of each other. For example, “aaagmnrs” is an anagram of “anagrams”. Given an array of strings, remove each string that is an anagram of an earlier string, then return the remaining array in sorted order.

For example, given the strings `s = ['code', 'doce', 'ecod', 'framer', 'frame']`

, the strings `'doce'`

and `'ecod'`

are both anagrams of `'code'`

so they are removed from the list. The words `'frame'`

and `'framer'`

are not anagrams due to the extra `'r'`

in `'framer'`

, so they remain. The final list of strings in alphabetical order is `['code', 'frame', 'framer']`

.

**Function Description**

Complete the function `funWithAnagrams`

in the editor below. It must return a list of strings in alphabetical order, ascending.

funWithAnagrams has the following parameters:

`s[s[0],...s[n-1]]`

: an array of strings

**Constraints**

1 ≤ n ≤ 1000

1 ≤ |s[i]| ≤ 1000

Each string s[i] is made up of characters in the range ascii[a-z]

**Sample Input For Custom Testing**

```
4
code
aaagmnrs
anagrams
doce
```

**Sample Output**

```
aaagmnrs
code
```

**Explanation**

aaagmnrs and anagrams are anagrams, code and doce are anagrams. After sorting aaagmnrs comes first.

**Solution**

public class FunWithAnagrams { public static boolean areAnagram(String w1, String w2) { char[] chr1 = w1.toCharArray(); char[] chr2 = w2.toCharArray(); // Sorting the two arrays and checking for equality also works, but this is faster int[] count = new int[26]; for (char ch : chr1) { count[ch - 97] = count[ch - 97] + 1; } for (char ch : chr2) { count[ch - 97] = count[ch - 97] - 1; } for (int n : count) { if (n != 0) { return false; } } return true; } public static String key(String word) { char[] chrs = word.toCharArray(); Arrays.sort(chrs); return new String(chrs); } public static List<String> funWithAnagrams(List<String> s) { List<String> ans = new LinkedList<String>(); Set<String> found = new HashSet<String>(); for (int i=0; i<s.size(); i++) { String word = s.get(i); String key = key(word); if (!found.contains(key)) { ans.add(word); found.add(key); } } Collections.sort(ans); return ans; } public static void main(String[] args) throws FileNotFoundException { //List<String> a = Arrays.asList("code", "doce", "ecod", "framer", "frame"); List<String> a = Arrays.asList("code", "aaagmnrs", "anagrams", "doce"); System.out.println(funWithAnagrams(a)); } }

The post Fun with Anagrams appeared first on fizzbuzzer.

]]>The post Special Palindrome Again Challenge appeared first on fizzbuzzer.

]]>A string is said to be a special palindromic string if either of two conditions is met:

* All of the characters are the same, e.g.

`aaa`

.* All characters except the middle one are the same, e.g.

`aadaa`

.
A special*palindromic substring* is any substring of a string which meets one of those criteria. Given a string, determine how many special palindromic substrings can be formed from it.

For example, given the string `s=mnonopoo`

, we have the following special palindromic substrings: `{m, n, o, n, o, p, o, o, non, ono, opo, oo}`

.

**Function Description**

Complete the `substrCount`

function. It should return an integer representing the number of special palindromic substrings that can be formed from the given string.

`substrCount`

has the following parameter(s):

* `n`

: an integer, the length of string s

* `s`

: a string

**Input Format**

The first line contains an integer, `n`

, the length of `s`

.

The second line contains the string `s`

.

**Constraints**

*

* Each character of the string is a lowercase alphabet, `ascii[a-z]`

.

**Sample Input 0**

```
5
asasd
```

**Sample Output 0**

```
7
```

**Explanation 0**

The special palindromic substrings of `s=asasd`

are `{a, s, a, s, d, asa, sas}`

.

**Solution**

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.*; public class SpecialPalindromeAgain { static Mapbruteforce(int n, String s) { Map result = new HashMap<>(); for (int i = 0; i < n; i++) { for (int len = 1; len <= n - i; len++) { String substr = s.substring(i, i + len); if (substr.length() == 1) { if (!result.containsKey(substr)) { result.put(substr, 0l); } result.put(substr, result.get(substr) + 1); } else if (substr.length() > 0 && substr.length() % 2 == 0) { boolean allSame = true; for (int j = 1; j < substr.length(); j++) { if (substr.charAt(j) != substr.charAt(j - 1)) { allSame = false; break; } if (allSame) { if (!result.containsKey(substr)) { result.put(substr, 0l); } result.put(substr, result.get(substr) + 1); } } } else if (substr.length() > 0 && substr.length() % 2 == 1) { int mid = substr.length() / 2; String left = substr.substring(0, mid); String right = substr.substring(mid + 1); if (left.equals(right)) { if (!result.containsKey(substr)) { result.put(substr, 0l); } result.put(substr, result.get(substr) + 1); } } } } return result; } static long substrCount(int n, String s) { long ans = 0; for (int i = 0; i < n; i++) { ans++; char previousChar = s.charAt(i); int charsLeftCount = 1; int charsRightCount = 0; boolean reachedMiddle = false; for (int j = i + 1; j < n; j++) { char ch = s.charAt(j); if (!reachedMiddle && ch != previousChar) { reachedMiddle = true; } else if (reachedMiddle && (ch != previousChar || j == n - 1)) { if (j == n - 1 && ch == previousChar) { charsRightCount++; } if (charsLeftCount == charsRightCount) { ans++; } break; } else if (!reachedMiddle && ch == previousChar) { charsLeftCount++; if (charsLeftCount >= 2) { ans++; } } else if (reachedMiddle && ch == previousChar) { charsRightCount++; if (charsLeftCount == charsRightCount) { ans++; break; } } } } return ans; } public static void main(String[] args) throws FileNotFoundException { System.setIn(new FileInputStream(System.getProperty("user.home") + "/" + "in3.txt")); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); String s = scanner.next(); long startTime = System.currentTimeMillis(); long result = substrCount(n, s); long endTime = System.currentTimeMillis(); System.out.println("Took " + (endTime - startTime) + " ms"); Scanner expectedScanner = new Scanner(new FileInputStream(System.getProperty("user.home") + "/" + "expected3.txt")); long expected = expectedScanner.nextLong(); if (result != expected) { System.out.println("Error: expected " + expected + " got " + result); } else { System.out.println("Correct: expected " + expected + " got " + result); } } }

The post Special Palindrome Again Challenge appeared first on fizzbuzzer.

]]>