DEV Community 👩‍💻👨‍💻

Simon Green
Simon Green

Posted on

Letter and numbers

Weekly Challenge 189

Challenge, My solution

Task 1: Greater Character

Task

You are given an array of characters (a..z) and a target character.

Write a script to find out the smallest character in the given array lexicographically greater than the target character.

My solution

There are two ways this challenge could be tackled. One solution is to work through the alphabet and exit on a match. This is relatively straight forward in Perl (++a is b), it's not that easy in Python.

So the approach I took was as follows:

  1. Take the last value from the input and store it as target
  2. Find all other values in the list greater than the target.
  3. Sort this list
  4. Print the first item in the list. If no item is found, print the target.

Examples

$ ./ch-1.py e m u g b
e

$ ./ch-1.py d c e f a
c

$ ./ch-1.py j a r o
r

$ ./ch-1.py d c a f a
c

$ ./ch-1.py t g a l v
v
Enter fullscreen mode Exit fullscreen mode

Task 2: Array Degree

Task

You are given an array of 2 or more non-negative integers.

Write a script to find out the smallest slice, i.e. contiguous subarray of the original array, having the degree of the given array.

The degree of an array is the maximum frequency of an element in the array.

My solution

For this challenge, I have created a function call get_degree. This returns the frequency of the most used number. The function creates a dict (hash in Perl) counting the frequency of each number, and then returns the maximum of all the values.

I then have a double loop for looking at all possible slices of the array. If the slice has the required degree and either we don't have a solution or the sum of the slice is less than any previous solution, we mark this slice as the solution.

I then print the slice found in the above loop.

Examples

$ ./ch-2.py 1 3 3 2
3, 3

$ ./ch-2.py 1 2 1 3
1, 2, 1

$ ./ch-2.py 1 3 2 1 2
2, 1, 2

$ ./ch-2.py 1 1 3 2 3
1, 1

$ ./ch-2.py 2 1 2 1 1
1, 2, 1, 1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now