
class IteratorForPermKArrays :
	
	#Constructor, Time O(n*k), Space O(n*k), n is the max length of arrays, k is number of arrays
	def __init__(self,x, y, z) :
		input = []
		input.append(x)
		input.append(y)
		input.append(z)
		self.permResult = self.permKArrays(input); 
    
	#Call recursion,Time O(n*k), Space O(n*k)
	def permKArrays(self, input) :
		out = set()
		self.permUtil(input.copy(), set(), out)
		return out

	# recursion helper, Time O(n*k), Space O(n*k)
	def permUtil(self, input, part, out) :
		if (len(input) == 0) :
			out.add(frozenset(part))
			return
		if part in out :
			return
		nextIn = input.copy()
		for  s in nextIn.pop(0) :
			nextPart = set(part)
			nextPart.add(s)
			self.permUtil(nextIn, nextPart, out)
	
	# Call set iterator, Time O(1), Space O(1)
	def __iter__(self):
		self.count = len(self.permResult)
		self.it = iter(self.permResult)
		return self

	#Time O(1), Space O(1)
	def __next__(self):
		if self.count >= 0 :
			self.count -= 1
			return next(self.it)
		else:
			raise StopIteration

x = ["a","b","c"]
y = ["p","q"]
z = ["r","s"]		
obj = IteratorForPermKArrays(x, y, z)
for i in obj:
	print(i)