MIME Type puzzle discussion

Is a file with an empty basename, just named “.pdf” is a pdf ?
NodeJS disagree : https://nodejs.org/api/path.html#path_path_extname_path :wink:

It can be anything:

> touch .pdf
> file .pdf
.pdf: empty

Hi,

i’m trying to do the challenge in C++, but when i include map from C++ stl, code doesnt compile anymore, for error see screenshot image here: https://ibb.co/9VvxmNs

Hard to say from this piece of stack trace and without your code.
What do you put in your map ? This kind of error typically occurs when you try to use a std container with a class which doesn’t have required operators like < or =. Or if those operators are not tagged ‘const’.

1 Like

I’m creating a map<string, string> , and inside the first for loop i put EXT and MT there using
table.insert(EXT, MT);
But that causes the error… afaik these operators are implemented for std::string, so something stupid that i’m missing i guess…

Ah ! The problem is that the ‘insert()’ method of ‘std::map’ take a ‘std::pair’ not the key and the value like you did. You can try something like:

table.insert(make_pair<string,string>(EXT,MT));

Or with a more friendly method :

table[EXT] = MT;
2 Likes

facepalm shoulda noticed that…

Thanks a lot for replying so quickly and for your patience :slight_smile: all works now

Thanks. Tried my best to optimize the code but wouldn’t let me past large dataset. Submitting gave me 100% though

I’m using a DIY hashmap in vanilla C to hold my mimetypes (“gif” as key, “image/gif” as value) – but I get timed out on the last ‘Large Dataset’ test. Any pointers?

The problem of passing large datasets with C or C++ has been fixed.

1 Like

for gophers: I had to add 1 to all maximum length tests (10, 50, 256 -> 11, 51, 257) to pass the ‘limit extension problem’ …

help me !

/**

  • Auto-generated code below aims at helping you parse
  • the standard input according to the problem statement.
    **/

const N = parseInt(readline()); // Number of elements which make up the association table.
const Q = parseInt(readline()); // Number Q of file names to be analyzed.
let mime = [];
let file = “”;
for (let i = 0; i < N; i++) {
var inputs = readline().split(’ ');
const EXT = inputs[0]; // file extension
const MT = inputs[1]; // MIME type.
if(!Object.keys(mime).includes(EXT.toLowerCase()))
mime[EXT.toLowerCase()] = MT
}
for (let i = 0; i < Q; i++) {
const FNAME = readline(); // One file name per line.
file = FNAME.split(".")
let mt = mime[file[file.length-1].toLowerCase()];
console.log((file.length > 1 && mt !== undefined)?mt:“UNKNOWN”);
}

// Write an answer using console.log()
// To debug: console.error(‘Debug messages…’);

// For each of the Q filenames, display on a line the corresponding MIME type. If there is no corresponding type, then display UNKNOWN.

answer:

Échec

Le délai d’exécution du processus a été dépassé. Cela peut signifier que votre solution n’est pas suffisamment optimisée pour traiter certains cas.

Hello, I am attempting this using C# and have passed all tests except the Large Dataset test as it states my code is not optimized. I was initially storing multiple pieces of the input in 5 different lists and was able to reduce that to a singular Array to store the MIME type input. I am no longer storing the file names. Now the output shows about 300 items before I get the time-out error. I’m not sure how to further optimize this…

class Solution
{
    static void Main(string[] args)
    {
        int N = int.Parse(Console.ReadLine()); // Number of elements which make up the association table.
        int Q = int.Parse(Console.ReadLine()); // Number Q of file names to be analyzed.
        
        string[] MIMEList = new string[N];
       
        for (int b = 0; b < N; b++)
            {
                MIMEList[b] = Console.ReadLine();
            }

        for (int i = 0; i < Q; i++)
        {
                string inputName = Console.ReadLine();
                string nameExt = inputName.Substring(inputName.LastIndexOf(".")+1);
                
                if(inputName.Contains("."))
                {
                        if(inputName.Length == inputName.LastIndexOf(".")+1){
                                Console.WriteLine("UNKNOWN");
                        } else {    
                              for (int e =0; e < N; e++){
                                  string mimeEXT = MIMEList[e].Substring(0,MIMEList[e].IndexOf(" "));

                                if (nameExt.Equals(mimeEXT,StringComparison.OrdinalIgnoreCase)){
                                    Console.WriteLine(MIMEList[e].Substring(MIMEList[e].IndexOf(" ")+1));
                                    break;
                                } else if (MIMEList[e] == MIMEList[^1]){
                                    Console.WriteLine("UNKNOWN");
                                  } 
                                }
                            }
                } else {
                        Console.WriteLine("UNKNOWN");
                        }
        }
    }

}

You’re looking for a string in an array, which is typically an O(n) operation since all entries have to be tested in the worst case scenario. Consider using either a dictionary -O(1)- or a sorted list with binary search -O(log(n))-

2 Likes

Dictionary worked perfectly here and I learned something new along the way. Thanks a lot!

1 Like

Hello, I am using Java and have passed all tests except the Large Dataset test. When I comapre the my output to the expected output is shows that my output skipped a lot of the files. I’m using a HashMap (key, value). I’m not sure what I’m doing wrong. Sorry about the code formatting, I don’t know how to immed it.

import java.util.*;
import java.io.*;
import java.math.*;

class Solution {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt(); // Number of elements which make up the association table.
        int Q = in.nextInt(); // Number Q of file names to be analyzed.
        HashMap<String, String> extMIME = new HashMap<>();
        for (int i = 0; i < N; i++) {
            String EXT = in.next().toLowerCase(); // file extension
            String MT = in.next(); // MIME type.
            extMIME.put(EXT, MT);
        }
        in.nextLine();
        for (int i = 0; i < Q; i++) {
            String FNAME = in.nextLine(); // One file name per line.
            int periodIndex = FNAME.indexOf(".");
            String extension = FNAME.substring(periodIndex + 1).replaceAll("[^a-zA-Z]", "").toLowerCase();
            String MIME = extMIME.get(extension);
            if(MIME == null || periodIndex == -1) {
                System.out.println("UNKNOWN");
            }
            else {
                 System.out.println(MIME);
            }
        }
    }
 }
1 Like

Hello,
You have to rethink the way you look for the extension, it’s not ok when the input contains zero dot or more than one dot.
Also do not hesitate to add some System.err.println() to check intermediate results.
Tip: the String method lastindexof() could help you here.

2 Likes

Thanks for those tips I’ll try System.err.println(). I also forgot about lastindexof(), thanks for reminding me.

I really enjoyed this one. In all, this challenge was the first time I wrote a program in C using struct(), making a hash table, making a linked list, and really taking advantage of pointers. Yet, everything worked when I was done! I feel really proud of myself.

1 Like

It takes too long to compare inputName against the entire list. In order for the program to run fast enough, you need to learn how to make a map of the types so that your program can find the correct one without checking each individually. I used a hashmap pointing to linked lists and it ran super fast. It was my first program using these and I really learned a lot.