How to optimize the time complexity when looping over two arrays

Viewed 108

I have 2 sorted arrays of application names in the user's Android device. I now need to log an event if one array contains at least one item of the other array.

Here is my code:

  appsArray = ["cred","cult","hotstar","netflix","prime","splitwise","spotify"];
  _apps = [...]; // Apps in user's mobile

  bool _isQualityUser() {
    var result = '';
    for (var app in _apps) {
      result = appsArray.singleWhere((el) => app.appName.contains(el));
    }
    return result.isNotEmpty;
  }

I'm looking for an optimized solution for it. If anyone can help with that.

2 Answers

this approach finds similar strings in O(n):

void main() {
  List<String> list1 = ["bc", "ab", "abb", "bb", "aa", "ff"];
  List<String> list2 = ["ab", "bb", "abc", "cb", "bc", "fg", "ff"];

  list1.sort();
  list2.sort();

  int index1 = 0;
  int index2 = 0;
  while (true) {
    if (list1[index1] == list2[index2]) {
      print(list1[index1]);
      index1 += 1;
      index2 += 1;
    } else if (list1[index1].compareTo(list2[index2]) < 0) {
      index1 += 1;
    } else {
      index2 += 1;
    }
    if (index1 == list1.length || index2 == list2.length) break;
  }
}

You could potentially use Set as it has O(1) complexity for read operation.

var appNames = <String>{'cred', 'cult'};

bool _isQualityUser() {
    var result = '';
    for (var app in _apps) {
      result = appNames.contains(app.appName);
    }
    return result.isNotEmpty;
  }
Related