65.2k views
5 votes
We say that a sequence of numbers is a palindrome if it is read the same backward or forward. For example, the sequence: 6, 15, 6, 3, 47, 3, 6, 15, 6 is a palindrome.

Implement the following function:
def construct_a_longest palindrome(numbers_bank)
When given numbers_bank, a non-empty list of integers, it will create and return a list containing a longest possible palindrome made only with numbers from numbers_bank.
Notes:
1. The longest palindrome might NOT contain all of the numbers in the sequence.
2. If no multi-number palindromes can be constructed, the function may return just one number (as a single number, alone, is a palindrome).
3. If there is more than one possible longest palindrome, your function can return any one of them.
For example, if numbers_bank = [3, 47, 6, 6, 5, 6, 15, 3, 22, 1, 6, 15), Then the call construct_a_longest_palindrome (numbers_bank) could return: [6, 15, 6, 3, 47, 3, 6, 15, 6] (Which is a palindrome of length 9, and there is no palindrome made only with numbers from numbers_bank that is longer than 9).
Requirements:
1. You may use one ArrayQueue, one ArrayStack, and one ChaniningHash TableMap.
2. Your function has to run in expected (average) linear time. That is, if numbers bank is a list with n numbers, your function should run in O(n) average case.
3. Besides the queue, stack, hash table, and the list that is created and returned, you may use only constant additional space. That is, besides the queue, stack, hash table, and the returned list, you may use variables to store an integer, a double, etc. However, you may not use an additional data structure (such as another list, stack, queue, etc.) to store non-constant number of elements.

User Lucasweb
by
5.5k points

1 Answer

4 votes

Answer:

The below code would be used to answer the above question

Step-by-step explanation:

import java.io.*;

import java.util.*;

public class Main

{

public static List<Integer> construct_a_longest_pallindrome(int a[]){

Map <Integer,Integer> map = new HashMap<>();

List<Integer> ans1 = new ArrayList<>();

List<Integer> ans2 = new ArrayList<>();

for(int i=0;i<a.length;i++){

if(map.containsKey(a[i])){

map.put(a[i],map.get(a[i])+1);

}else

map.put(a[i],1);

}

int pos1 = 0;

int pos2 = 0;

for(Integer key : map.keySet()){

int val = map.get(key);

while(val % 2 == 0){

ans1.add(key);

ans2.add(key);

val = val-2;

}

if(val == 0)

map.remove(key);

else

map.put(key,1);

}

if(map.isEmpty() == false){

ans1.add(map.keySet().iterator().next());

}

Collections.reverse(ans2);

ans1.addAll(ans2);

return ans1;

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the size of array");

int n = sc.nextInt();

int arr[] = new int[n];

for(int i=0;i<n;i++){

arr[i] = sc.nextInt();

}

System.out.println(construct_a_longest_pallindrome(arr));

}

}

User Raychel
by
5.7k points