It is said that the spectral lines of a particular atom or molecule is unique and this could be used to identify the substance by comparing the spectrum with the existing library of spectra of different atoms, molecules and compounds. In other words, spectral lines are like the fingerprints which help to identify different substances. This is used by astronomers to identify the chemical composition of distant stars and planets.
The Wikipedia article on spectral lines gives the spectral lines for most of the elements in the periodic table.
Usually stars and planets have diverse composition i.e., have different atoms, molecules and compounds. So the spectrum observed from these sources must have spectral lines belonging to each and every substance superposed on one another.
Let us assume Star X contains two elements A and B (for which the spectral lines are already known and are given in the first and second spectra in the following figure). When astronomers analyse the light from Star X, they would be seeing something like the third spectrum in the following figure.
My doubt is, on seeing only the third spectrum how can an astronomer conclude the Star X is made of Elements A and B? Why can't it be made of Element C alone which matches the third spectrum all by itself? How do they know which spectral line belongs to which element?
We've just considered two elements but in reality there will be even more. More the number of elements more populated will be the resulting spectrum. So, the process of finding the composition becomes even more complicated. We've seen how difficult it would be to identify the elements. But in addition to this, they find the relative composition of elements in distant stars and planets based on the spectral lines. How do they do this?
To put this question in some common terms - how do investigators identify different criminals when each and everyone places their fingerprint on the same location such that the patterns overlap? However, let's limit the answers explaining only the "optical fingerprints" of elements.