DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 208

Challenge, My solutions

Last minute commit this week, so this blog will be briefer than usual.

Task 1: Minimum Index Sum

Task

You are given two arrays of strings.

Write a script to find out all common strings in the given two arrays with minimum index sum. If no common strings found returns an empty list.

My solution

This is one of those tasks where optimisation of the solution probably isn't required. I'm sure some clever Team PWC people have a blog post on the most optimal solution.

For this task, I extract the word-like strings from the first two parameters, and call them first_list and second_list (yeah, really imaginative list names!)

I then set index_sum to one more than the length of the combined list. This ensures that if we do find a solution index_sum will be lower.

I then iterate over first_list, with i1 as the index position and w being the word at that position. I then retrieve the position of that word in the second_list. If it appears, I calculate the sum of the positions, and take action if it is the same or less than the current index_sum value.

Python doesn't seem to have a built in command to get the index of an item in a list that matches a criteria (in this case the word), so I created a function called find_index_in_list to do this. To be fair, neither does Perl, but first_index from List::MoreUtils does what we want.

Examples

$ ./ch-1.py "Perl Raku Love" "Raku Perl Like"
("Perl", "Raku")

$ ./ch-1.py "A B C" "D E F"
()

$ ./ch-1.py "A B C" "C A B"
("A")
Enter fullscreen mode Exit fullscreen mode

Task 2: Duplicate and Missing

Task

You are given an array of integers in sequence with one missing and one duplicate.

Write a script to find the duplicate and missing integer in the given array. Return -1 if none found.

For the sake of this task, let us assume the array contains no more than one duplicate and missing.

My solution

The examples don't give us an indication on what the expected output is when there is no duplicate, but there is a missing number, as is the case with [1, 2, 33, 4]. In the case, the first value in the output is going to be blank.

For this task, I iterate from 1 to the length of the array, and count the number of items in the list that have that value. If there are none, I set the missing value. If there is more than 1, I set the duplicate value.

Finally I print the output as provided in the examples.

Examples

$ ./ch-2.py 1 2 2 4
(2, 3)

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

$ ./ch-2.py 1 2 3 3
(3, 4)

$ ./ch-2.py 1 2 3 33
(, 4)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)