import re


def compress_problem_sizes_label(labels):
  """Shorten the problem size lables by removing redundant information.

  Plotting the entire problem size configuration for every axis tick
  requires a lot of space and results in overlapping labels. The method
  identifies the dimensions that take different values and filters out
  the dimensions that are constant for the entire plot. Additionally,
  the dimension names (it suffices to plot them once) and sizes values
  are returned seperately.

  Example:
  ["H=64,W=32", "H=64,W=64"]
  ->
  ["W"], ["32", "64"]
  """
  label_dicts = []
  for label in labels:
    groups = re.findall(r"""([a-zA-Z]+)=(\d+|\[[0-9, ]+\])""", label)
    label_dicts.append(dict(groups))
  # Collect all values for a specific key.
  value_dict = {}
  for label_dict in label_dicts:
    for k, v in label_dict.items():
      if k in value_dict:
        value_dict[k].add(v)
      else:
        value_dict[k] = set([v])
  # Collect the keys that have multiple values.
  keys = []
  for k, v in value_dict.items():
    if len(v) != 1:
      keys.append(k)
  # Collect the keys for every label
  new_labels = []
  for label_dict in label_dicts:
    new_labels.append(",".join([label_dict[k] for k in keys]))
  return keys, new_labels