Implement the Dutch national flag algorithm to sort an array containing three distinct keys.
The function receives an array and three distinct keys defining the required order: key1, then key2, then key3. Sort the array in place and return it. Use a single traversal with constant extra space; do not call a built-in sorting function.
def dutch_national_flag(nums, key1, key2, key3):